180814287SRaphael Isemann //===-- ObjectFilePECOFF.cpp ----------------------------------------------===//
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"
1030c2441aSAleksandr Urakov #include "PECallFrameInfo.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"
193c867898SAlvin Wong #include "lldb/Interpreter/OptionValueDictionary.h"
2025c8a061SAlvin Wong #include "lldb/Interpreter/OptionValueProperties.h"
21f754f88fSGreg Clayton #include "lldb/Symbol/ObjectFile.h"
22f7d1893fSAdrian McCarthy #include "lldb/Target/Process.h"
232756adf3SVirgile Bello #include "lldb/Target/SectionLoadList.h"
242756adf3SVirgile Bello #include "lldb/Target/Target.h"
255f19b907SPavel Labath #include "lldb/Utility/ArchSpec.h"
26666cc0b2SZachary Turner #include "lldb/Utility/DataBufferHeap.h"
275713a05bSZachary Turner #include "lldb/Utility/FileSpec.h"
28c34698a8SPavel Labath #include "lldb/Utility/LLDBLog.h"
29037ed1beSAaron Smith #include "lldb/Utility/Log.h"
30bf9a7730SZachary Turner #include "lldb/Utility/StreamString.h"
3138d0632eSPavel Labath #include "lldb/Utility/Timer.h"
32666cc0b2SZachary Turner #include "lldb/Utility/UUID.h"
335f19b907SPavel Labath #include "llvm/BinaryFormat/COFF.h"
34f754f88fSGreg Clayton 
35037ed1beSAaron Smith #include "llvm/Object/COFFImportFile.h"
36c8daf4a7SAlvin Wong #include "llvm/Support/CRC.h"
37037ed1beSAaron Smith #include "llvm/Support/Error.h"
3825c8a061SAlvin Wong #include "llvm/Support/Host.h"
393f4a4b36SZachary Turner #include "llvm/Support/MemoryBuffer.h"
403f4a4b36SZachary Turner 
41f754f88fSGreg Clayton #define IMAGE_DOS_SIGNATURE 0x5A4D    // MZ
42f754f88fSGreg Clayton #define IMAGE_NT_SIGNATURE 0x00004550 // PE00
43f754f88fSGreg Clayton #define OPT_HEADER_MAGIC_PE32 0x010b
44f754f88fSGreg Clayton #define OPT_HEADER_MAGIC_PE32_PLUS 0x020b
45f754f88fSGreg Clayton 
46f754f88fSGreg Clayton using namespace lldb;
47f754f88fSGreg Clayton using namespace lldb_private;
48f754f88fSGreg Clayton 
49bba9ba8dSJonas Devlieghere LLDB_PLUGIN_DEFINE(ObjectFilePECOFF)
50fbb4d1e4SJonas Devlieghere 
5125c8a061SAlvin Wong namespace {
5225c8a061SAlvin Wong 
5325c8a061SAlvin Wong static constexpr OptionEnumValueElement g_abi_enums[] = {
5425c8a061SAlvin Wong     {
5525c8a061SAlvin Wong         llvm::Triple::UnknownEnvironment,
5625c8a061SAlvin Wong         "default",
5725c8a061SAlvin Wong         "Use default target (if it is Windows) or MSVC",
5825c8a061SAlvin Wong     },
5925c8a061SAlvin Wong     {
6025c8a061SAlvin Wong         llvm::Triple::MSVC,
6125c8a061SAlvin Wong         "msvc",
6225c8a061SAlvin Wong         "MSVC ABI",
6325c8a061SAlvin Wong     },
6425c8a061SAlvin Wong     {
6525c8a061SAlvin Wong         llvm::Triple::GNU,
6625c8a061SAlvin Wong         "gnu",
6725c8a061SAlvin Wong         "MinGW / Itanium ABI",
6825c8a061SAlvin Wong     },
6925c8a061SAlvin Wong };
7025c8a061SAlvin Wong 
7125c8a061SAlvin Wong #define LLDB_PROPERTIES_objectfilepecoff
7225c8a061SAlvin Wong #include "ObjectFilePECOFFProperties.inc"
7325c8a061SAlvin Wong 
7425c8a061SAlvin Wong enum {
7525c8a061SAlvin Wong #define LLDB_PROPERTIES_objectfilepecoff
7625c8a061SAlvin Wong #include "ObjectFilePECOFFPropertiesEnum.inc"
7725c8a061SAlvin Wong };
7825c8a061SAlvin Wong 
7925c8a061SAlvin Wong class PluginProperties : public Properties {
8025c8a061SAlvin Wong public:
GetSettingName()8125c8a061SAlvin Wong   static ConstString GetSettingName() {
8225c8a061SAlvin Wong     return ConstString(ObjectFilePECOFF::GetPluginNameStatic());
8325c8a061SAlvin Wong   }
8425c8a061SAlvin Wong 
PluginProperties()8525c8a061SAlvin Wong   PluginProperties() {
8625c8a061SAlvin Wong     m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
8725c8a061SAlvin Wong     m_collection_sp->Initialize(g_objectfilepecoff_properties);
8825c8a061SAlvin Wong   }
8925c8a061SAlvin Wong 
ABI() const9025c8a061SAlvin Wong   llvm::Triple::EnvironmentType ABI() const {
9125c8a061SAlvin Wong     return (llvm::Triple::EnvironmentType)
9225c8a061SAlvin Wong         m_collection_sp->GetPropertyAtIndexAsEnumeration(
9325c8a061SAlvin Wong             nullptr, ePropertyABI, llvm::Triple::UnknownEnvironment);
9425c8a061SAlvin Wong   }
953c867898SAlvin Wong 
ModuleABIMap() const963c867898SAlvin Wong   OptionValueDictionary *ModuleABIMap() const {
973c867898SAlvin Wong     return m_collection_sp->GetPropertyAtIndexAsOptionValueDictionary(
983c867898SAlvin Wong         nullptr, ePropertyModuleABIMap);
993c867898SAlvin Wong   }
10025c8a061SAlvin Wong };
10125c8a061SAlvin Wong 
GetGlobalPluginProperties()10225c8a061SAlvin Wong static PluginProperties &GetGlobalPluginProperties() {
10325c8a061SAlvin Wong   static PluginProperties g_settings;
10425c8a061SAlvin Wong   return g_settings;
10525c8a061SAlvin Wong }
10625c8a061SAlvin Wong 
10725c8a061SAlvin Wong } // namespace
10825c8a061SAlvin Wong 
GetDebugLinkContents(const llvm::object::COFFObjectFile & coff_obj,std::string & gnu_debuglink_file,uint32_t & gnu_debuglink_crc)109c8daf4a7SAlvin Wong static bool GetDebugLinkContents(const llvm::object::COFFObjectFile &coff_obj,
110c8daf4a7SAlvin Wong                                  std::string &gnu_debuglink_file,
111c8daf4a7SAlvin Wong                                  uint32_t &gnu_debuglink_crc) {
112c8daf4a7SAlvin Wong   static ConstString g_sect_name_gnu_debuglink(".gnu_debuglink");
113c8daf4a7SAlvin Wong   for (const auto &section : coff_obj.sections()) {
114c8daf4a7SAlvin Wong     auto name = section.getName();
115c8daf4a7SAlvin Wong     if (!name) {
116c8daf4a7SAlvin Wong       llvm::consumeError(name.takeError());
117c8daf4a7SAlvin Wong       continue;
118c8daf4a7SAlvin Wong     }
119c8daf4a7SAlvin Wong     if (*name == g_sect_name_gnu_debuglink.GetStringRef()) {
120c8daf4a7SAlvin Wong       auto content = section.getContents();
121c8daf4a7SAlvin Wong       if (!content) {
122c8daf4a7SAlvin Wong         llvm::consumeError(content.takeError());
123c8daf4a7SAlvin Wong         return false;
124c8daf4a7SAlvin Wong       }
125c8daf4a7SAlvin Wong       DataExtractor data(
126c8daf4a7SAlvin Wong           content->data(), content->size(),
127c8daf4a7SAlvin Wong           coff_obj.isLittleEndian() ? eByteOrderLittle : eByteOrderBig, 4);
128c8daf4a7SAlvin Wong       lldb::offset_t gnu_debuglink_offset = 0;
129c8daf4a7SAlvin Wong       gnu_debuglink_file = data.GetCStr(&gnu_debuglink_offset);
130c8daf4a7SAlvin Wong       // Align to the next 4-byte offset
131c8daf4a7SAlvin Wong       gnu_debuglink_offset = llvm::alignTo(gnu_debuglink_offset, 4);
132c8daf4a7SAlvin Wong       data.GetU32(&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
133c8daf4a7SAlvin Wong       return true;
134c8daf4a7SAlvin Wong     }
135c8daf4a7SAlvin Wong   }
136c8daf4a7SAlvin Wong   return false;
137c8daf4a7SAlvin Wong }
138c8daf4a7SAlvin Wong 
GetCoffUUID(llvm::object::COFFObjectFile & coff_obj)139d372a8e8SPavel Labath static UUID GetCoffUUID(llvm::object::COFFObjectFile &coff_obj) {
140b8d03935SAaron Smith   const llvm::codeview::DebugInfo *pdb_info = nullptr;
141b8d03935SAaron Smith   llvm::StringRef pdb_file;
142b8d03935SAaron Smith 
143c8daf4a7SAlvin Wong   // First, prefer to use the PDB build id. LLD generates this even for mingw
144c8daf4a7SAlvin Wong   // targets without PDB output, and it does not get stripped either.
145d372a8e8SPavel Labath   if (!coff_obj.getDebugPDBInfo(pdb_info, pdb_file) && pdb_info) {
146b8d03935SAaron Smith     if (pdb_info->PDB70.CVSignature == llvm::OMF::Signature::PDB70) {
1474348e0eeSZequan Wu       UUID::CvRecordPdb70 info;
1484348e0eeSZequan Wu       memcpy(&info.Uuid, pdb_info->PDB70.Signature, sizeof(info.Uuid));
1494348e0eeSZequan Wu       info.Age = pdb_info->PDB70.Age;
1504348e0eeSZequan Wu       return UUID::fromCvRecord(info);
151b8d03935SAaron Smith     }
152b8d03935SAaron Smith   }
153b8d03935SAaron Smith 
154c8daf4a7SAlvin Wong   std::string gnu_debuglink_file;
155c8daf4a7SAlvin Wong   uint32_t gnu_debuglink_crc;
156c8daf4a7SAlvin Wong 
157c8daf4a7SAlvin Wong   // The GNU linker normally does not write a PDB build id (unless requested
158c8daf4a7SAlvin Wong   // with the --build-id option), so we should fall back to using the crc
159c8daf4a7SAlvin Wong   // from .gnu_debuglink if it exists, just like how ObjectFileELF does it.
160c8daf4a7SAlvin Wong   if (!GetDebugLinkContents(coff_obj, gnu_debuglink_file, gnu_debuglink_crc)) {
161c8daf4a7SAlvin Wong     // If there is no .gnu_debuglink section, then this may be an object
162c8daf4a7SAlvin Wong     // containing DWARF debug info for .gnu_debuglink, so calculate the crc of
163c8daf4a7SAlvin Wong     // the object itself.
164c8daf4a7SAlvin Wong     auto raw_data = coff_obj.getData();
165c8daf4a7SAlvin Wong     LLDB_SCOPED_TIMERF(
166c8daf4a7SAlvin Wong         "Calculating module crc32 %s with size %" PRIu64 " KiB",
167c8daf4a7SAlvin Wong         FileSpec(coff_obj.getFileName()).GetLastPathComponent().AsCString(),
168c8daf4a7SAlvin Wong         static_cast<lldb::offset_t>(raw_data.size()) / 1024);
169c8daf4a7SAlvin Wong     gnu_debuglink_crc = llvm::crc32(0, llvm::arrayRefFromStringRef(raw_data));
170c8daf4a7SAlvin Wong   }
171c8daf4a7SAlvin Wong   // Use 4 bytes of crc from the .gnu_debuglink section.
172c8daf4a7SAlvin Wong   llvm::support::ulittle32_t data(gnu_debuglink_crc);
173c8daf4a7SAlvin Wong   return UUID::fromData(&data, sizeof(data));
174b8d03935SAaron Smith }
175b8d03935SAaron Smith 
176e84f7841SPavel Labath char ObjectFilePECOFF::ID;
177e84f7841SPavel Labath 
Initialize()178b9c1b51eSKate Stone void ObjectFilePECOFF::Initialize() {
17925c8a061SAlvin Wong   PluginManager::RegisterPlugin(GetPluginNameStatic(),
18025c8a061SAlvin Wong                                 GetPluginDescriptionStatic(), CreateInstance,
18125c8a061SAlvin Wong                                 CreateMemoryInstance, GetModuleSpecifications,
18225c8a061SAlvin Wong                                 SaveCore, DebuggerInitialize);
18325c8a061SAlvin Wong }
18425c8a061SAlvin Wong 
DebuggerInitialize(Debugger & debugger)18525c8a061SAlvin Wong void ObjectFilePECOFF::DebuggerInitialize(Debugger &debugger) {
18625c8a061SAlvin Wong   if (!PluginManager::GetSettingForObjectFilePlugin(
18725c8a061SAlvin Wong           debugger, PluginProperties::GetSettingName())) {
18825c8a061SAlvin Wong     const bool is_global_setting = true;
18925c8a061SAlvin Wong     PluginManager::CreateSettingForObjectFilePlugin(
19025c8a061SAlvin Wong         debugger, GetGlobalPluginProperties().GetValueProperties(),
19125c8a061SAlvin Wong         ConstString("Properties for the PE/COFF object-file plug-in."),
19225c8a061SAlvin Wong         is_global_setting);
19325c8a061SAlvin Wong   }
194f754f88fSGreg Clayton }
195f754f88fSGreg Clayton 
Terminate()196b9c1b51eSKate Stone void ObjectFilePECOFF::Terminate() {
197f754f88fSGreg Clayton   PluginManager::UnregisterPlugin(CreateInstance);
198f754f88fSGreg Clayton }
199f754f88fSGreg Clayton 
GetPluginDescriptionStatic()2002ace1e57SPavel Labath llvm::StringRef ObjectFilePECOFF::GetPluginDescriptionStatic() {
201b9c1b51eSKate Stone   return "Portable Executable and Common Object File Format object file reader "
202b9c1b51eSKate Stone          "(32 and 64 bit)";
203f754f88fSGreg Clayton }
204f754f88fSGreg Clayton 
CreateInstance(const lldb::ModuleSP & module_sp,DataBufferSP data_sp,lldb::offset_t data_offset,const lldb_private::FileSpec * file_p,lldb::offset_t file_offset,lldb::offset_t length)205c69307e5SJonas Devlieghere ObjectFile *ObjectFilePECOFF::CreateInstance(
206c69307e5SJonas Devlieghere     const lldb::ModuleSP &module_sp, DataBufferSP data_sp,
207c69307e5SJonas Devlieghere     lldb::offset_t data_offset, const lldb_private::FileSpec *file_p,
208c69307e5SJonas Devlieghere     lldb::offset_t file_offset, lldb::offset_t length) {
20928e4942bSPavel Labath   FileSpec file = file_p ? *file_p : FileSpec();
210b9c1b51eSKate Stone   if (!data_sp) {
21150251fc7SPavel Labath     data_sp = MapFileData(file, length, file_offset);
2123f4a4b36SZachary Turner     if (!data_sp)
2133f4a4b36SZachary Turner       return nullptr;
2145ce9c565SGreg Clayton     data_offset = 0;
2155ce9c565SGreg Clayton   }
2165ce9c565SGreg Clayton 
2173f4a4b36SZachary Turner   if (!ObjectFilePECOFF::MagicBytesMatch(data_sp))
2183f4a4b36SZachary Turner     return nullptr;
2193f4a4b36SZachary Turner 
2205ce9c565SGreg Clayton   // Update the data to contain the entire file if it doesn't already
2213f4a4b36SZachary Turner   if (data_sp->GetByteSize() < length) {
22250251fc7SPavel Labath     data_sp = MapFileData(file, length, file_offset);
2233f4a4b36SZachary Turner     if (!data_sp)
2243f4a4b36SZachary Turner       return nullptr;
225f754f88fSGreg Clayton   }
2263f4a4b36SZachary Turner 
227a8f3ae7cSJonas Devlieghere   auto objfile_up = std::make_unique<ObjectFilePECOFF>(
22828e4942bSPavel Labath       module_sp, data_sp, data_offset, file_p, file_offset, length);
229d5b44036SJonas Devlieghere   if (!objfile_up || !objfile_up->ParseHeader())
2303f4a4b36SZachary Turner     return nullptr;
2313f4a4b36SZachary Turner 
232037ed1beSAaron Smith   // Cache coff binary.
233d5b44036SJonas Devlieghere   if (!objfile_up->CreateBinary())
234037ed1beSAaron Smith     return nullptr;
235d5b44036SJonas Devlieghere   return objfile_up.release();
236f754f88fSGreg Clayton }
237f754f88fSGreg Clayton 
CreateMemoryInstance(const lldb::ModuleSP & module_sp,lldb::WritableDataBufferSP data_sp,const lldb::ProcessSP & process_sp,lldb::addr_t header_addr)238b9c1b51eSKate Stone ObjectFile *ObjectFilePECOFF::CreateMemoryInstance(
239f2ea125eSJonas Devlieghere     const lldb::ModuleSP &module_sp, lldb::WritableDataBufferSP data_sp,
240b9c1b51eSKate Stone     const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) {
241344546bdSWalter Erquinigo   if (!data_sp || !ObjectFilePECOFF::MagicBytesMatch(data_sp))
242344546bdSWalter Erquinigo     return nullptr;
243a8f3ae7cSJonas Devlieghere   auto objfile_up = std::make_unique<ObjectFilePECOFF>(
244344546bdSWalter Erquinigo       module_sp, data_sp, process_sp, header_addr);
245d5b44036SJonas Devlieghere   if (objfile_up.get() && objfile_up->ParseHeader()) {
246d5b44036SJonas Devlieghere     return objfile_up.release();
247344546bdSWalter Erquinigo   }
248344546bdSWalter Erquinigo   return nullptr;
249c9660546SGreg Clayton }
250c9660546SGreg Clayton 
GetModuleSpecifications(const lldb_private::FileSpec & file,lldb::DataBufferSP & data_sp,lldb::offset_t data_offset,lldb::offset_t file_offset,lldb::offset_t length,lldb_private::ModuleSpecList & specs)251b9c1b51eSKate Stone size_t ObjectFilePECOFF::GetModuleSpecifications(
252b9c1b51eSKate Stone     const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
253b9c1b51eSKate Stone     lldb::offset_t data_offset, lldb::offset_t file_offset,
254b9c1b51eSKate Stone     lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
25589eb1baeSVirgile Bello   const size_t initial_count = specs.GetSize();
256b8d03935SAaron Smith   if (!data_sp || !ObjectFilePECOFF::MagicBytesMatch(data_sp))
257b8d03935SAaron Smith     return initial_count;
25889eb1baeSVirgile Bello 
259a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Object);
2603db1d138SMartin Storsjö 
261a4a00cedSFred Riss   if (data_sp->GetByteSize() < length)
262d372a8e8SPavel Labath     if (DataBufferSP full_sp = MapFileData(file, -1, file_offset))
263d372a8e8SPavel Labath       data_sp = std::move(full_sp);
264d372a8e8SPavel Labath   auto binary = llvm::object::createBinary(llvm::MemoryBufferRef(
265d372a8e8SPavel Labath       toStringRef(data_sp->GetData()), file.GetFilename().GetStringRef()));
2663db1d138SMartin Storsjö 
2673db1d138SMartin Storsjö   if (!binary) {
2683db1d138SMartin Storsjö     LLDB_LOG_ERROR(log, binary.takeError(),
2693db1d138SMartin Storsjö                    "Failed to create binary for file ({1}): {0}", file);
270b8d03935SAaron Smith     return initial_count;
2713db1d138SMartin Storsjö   }
27289eb1baeSVirgile Bello 
273d372a8e8SPavel Labath   auto *COFFObj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary->get());
274d372a8e8SPavel Labath   if (!COFFObj)
275b8d03935SAaron Smith     return initial_count;
27689eb1baeSVirgile Bello 
277b8d03935SAaron Smith   ModuleSpec module_spec(file);
278b8d03935SAaron Smith   ArchSpec &spec = module_spec.GetArchitecture();
279b8d03935SAaron Smith   lldb_private::UUID &uuid = module_spec.GetUUID();
280b8d03935SAaron Smith   if (!uuid.IsValid())
281d372a8e8SPavel Labath     uuid = GetCoffUUID(*COFFObj);
282b8d03935SAaron Smith 
28325c8a061SAlvin Wong   static llvm::Triple::EnvironmentType default_env = [] {
28425c8a061SAlvin Wong     auto def_target = llvm::Triple(
28525c8a061SAlvin Wong         llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple()));
28625c8a061SAlvin Wong     if (def_target.getOS() == llvm::Triple::Win32 &&
28725c8a061SAlvin Wong         def_target.getEnvironment() != llvm::Triple::UnknownEnvironment)
28825c8a061SAlvin Wong       return def_target.getEnvironment();
28925c8a061SAlvin Wong     return llvm::Triple::MSVC;
29025c8a061SAlvin Wong   }();
29125c8a061SAlvin Wong 
2923c867898SAlvin Wong   // Check for a module-specific override.
2933c867898SAlvin Wong   OptionValueSP module_env_option;
2943c867898SAlvin Wong   const auto *map = GetGlobalPluginProperties().ModuleABIMap();
2953c867898SAlvin Wong   if (map->GetNumValues() > 0) {
2963c867898SAlvin Wong     // Step 1: Try with the exact file name.
2973c867898SAlvin Wong     auto name = file.GetLastPathComponent();
2983c867898SAlvin Wong     module_env_option = map->GetValueForKey(name);
2993c867898SAlvin Wong     if (!module_env_option) {
3003c867898SAlvin Wong       // Step 2: Try with the file name in lowercase.
3013c867898SAlvin Wong       auto name_lower = name.GetStringRef().lower();
3023c867898SAlvin Wong       module_env_option =
3033c867898SAlvin Wong           map->GetValueForKey(ConstString(llvm::StringRef(name_lower)));
3043c867898SAlvin Wong     }
3053c867898SAlvin Wong     if (!module_env_option) {
3063c867898SAlvin Wong       // Step 3: Try with the file name with ".debug" suffix stripped.
3073c867898SAlvin Wong       auto name_stripped = name.GetStringRef();
3083c867898SAlvin Wong       if (name_stripped.consume_back_insensitive(".debug")) {
3093c867898SAlvin Wong         module_env_option = map->GetValueForKey(ConstString(name_stripped));
3103c867898SAlvin Wong         if (!module_env_option) {
3113c867898SAlvin Wong           // Step 4: Try with the file name in lowercase with ".debug" suffix
3123c867898SAlvin Wong           // stripped.
3133c867898SAlvin Wong           auto name_lower = name_stripped.lower();
3143c867898SAlvin Wong           module_env_option =
3153c867898SAlvin Wong               map->GetValueForKey(ConstString(llvm::StringRef(name_lower)));
3163c867898SAlvin Wong         }
3173c867898SAlvin Wong       }
3183c867898SAlvin Wong     }
3193c867898SAlvin Wong   }
3203c867898SAlvin Wong   llvm::Triple::EnvironmentType env;
3213c867898SAlvin Wong   if (module_env_option)
3223c867898SAlvin Wong     env =
3233c867898SAlvin Wong         (llvm::Triple::EnvironmentType)module_env_option->GetEnumerationValue();
3243c867898SAlvin Wong   else
3253c867898SAlvin Wong     env = GetGlobalPluginProperties().ABI();
3263c867898SAlvin Wong 
32725c8a061SAlvin Wong   if (env == llvm::Triple::UnknownEnvironment)
32825c8a061SAlvin Wong     env = default_env;
32925c8a061SAlvin Wong 
330b8d03935SAaron Smith   switch (COFFObj->getMachine()) {
331b8d03935SAaron Smith   case MachineAmd64:
332ad587ae4SZachary Turner     spec.SetTriple("x86_64-pc-windows");
33325c8a061SAlvin Wong     spec.GetTriple().setEnvironment(env);
334b8d03935SAaron Smith     specs.Append(module_spec);
335b8d03935SAaron Smith     break;
336b8d03935SAaron Smith   case MachineX86:
337ad587ae4SZachary Turner     spec.SetTriple("i386-pc-windows");
33825c8a061SAlvin Wong     spec.GetTriple().setEnvironment(env);
339b8d03935SAaron Smith     specs.Append(module_spec);
340b8d03935SAaron Smith     break;
341b8d03935SAaron Smith   case MachineArmNt:
342544c8f48SMartin Storsjo     spec.SetTriple("armv7-pc-windows");
34325c8a061SAlvin Wong     spec.GetTriple().setEnvironment(env);
344b8d03935SAaron Smith     specs.Append(module_spec);
345b8d03935SAaron Smith     break;
346638f072fSMartin Storsjo   case MachineArm64:
347674d5543SMartin Storsjo     spec.SetTriple("aarch64-pc-windows");
34825c8a061SAlvin Wong     spec.GetTriple().setEnvironment(env);
349638f072fSMartin Storsjo     specs.Append(module_spec);
350638f072fSMartin Storsjo     break;
351b8d03935SAaron Smith   default:
352b8d03935SAaron Smith     break;
35389eb1baeSVirgile Bello   }
35489eb1baeSVirgile Bello 
35589eb1baeSVirgile Bello   return specs.GetSize() - initial_count;
356f4d6de6aSGreg Clayton }
357f4d6de6aSGreg Clayton 
SaveCore(const lldb::ProcessSP & process_sp,const lldb_private::FileSpec & outfile,lldb::SaveCoreStyle & core_style,lldb_private::Status & error)358b9c1b51eSKate Stone bool ObjectFilePECOFF::SaveCore(const lldb::ProcessSP &process_sp,
359f7d1893fSAdrian McCarthy                                 const lldb_private::FileSpec &outfile,
3609ea6dd5cSJason Molenda                                 lldb::SaveCoreStyle &core_style,
36197206d57SZachary Turner                                 lldb_private::Status &error) {
3629ea6dd5cSJason Molenda   core_style = eSaveCoreFull;
363f7d1893fSAdrian McCarthy   return SaveMiniDump(process_sp, outfile, error);
364f7d1893fSAdrian McCarthy }
365f7d1893fSAdrian McCarthy 
MagicBytesMatch(DataBufferSP data_sp)366f2ea125eSJonas Devlieghere bool ObjectFilePECOFF::MagicBytesMatch(DataBufferSP data_sp) {
3675ce9c565SGreg Clayton   DataExtractor data(data_sp, eByteOrderLittle, 4);
368c7bece56SGreg Clayton   lldb::offset_t offset = 0;
369f754f88fSGreg Clayton   uint16_t magic = data.GetU16(&offset);
370f754f88fSGreg Clayton   return magic == IMAGE_DOS_SIGNATURE;
371f754f88fSGreg Clayton }
372f754f88fSGreg Clayton 
MapSymbolType(uint16_t coff_symbol_type)373b9c1b51eSKate Stone lldb::SymbolType ObjectFilePECOFF::MapSymbolType(uint16_t coff_symbol_type) {
374c35b91ceSAdrian McCarthy   // TODO:  We need to complete this mapping of COFF symbol types to LLDB ones.
375c35b91ceSAdrian McCarthy   // For now, here's a hack to make sure our function have types.
376b9c1b51eSKate Stone   const auto complex_type =
377b9c1b51eSKate Stone       coff_symbol_type >> llvm::COFF::SCT_COMPLEX_TYPE_SHIFT;
378b9c1b51eSKate Stone   if (complex_type == llvm::COFF::IMAGE_SYM_DTYPE_FUNCTION) {
379c35b91ceSAdrian McCarthy     return lldb::eSymbolTypeCode;
380c35b91ceSAdrian McCarthy   }
381c35b91ceSAdrian McCarthy   return lldb::eSymbolTypeInvalid;
382c35b91ceSAdrian McCarthy }
383f754f88fSGreg Clayton 
CreateBinary()384037ed1beSAaron Smith bool ObjectFilePECOFF::CreateBinary() {
385d372a8e8SPavel Labath   if (m_binary)
386037ed1beSAaron Smith     return true;
387037ed1beSAaron Smith 
388a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Object);
389037ed1beSAaron Smith 
390d372a8e8SPavel Labath   auto binary = llvm::object::createBinary(llvm::MemoryBufferRef(
391d372a8e8SPavel Labath       toStringRef(m_data.GetData()), m_file.GetFilename().GetStringRef()));
392037ed1beSAaron Smith   if (!binary) {
3933db1d138SMartin Storsjö     LLDB_LOG_ERROR(log, binary.takeError(),
3943db1d138SMartin Storsjö                    "Failed to create binary for file ({1}): {0}", m_file);
395037ed1beSAaron Smith     return false;
396037ed1beSAaron Smith   }
397037ed1beSAaron Smith 
398037ed1beSAaron Smith   // Make sure we only handle COFF format.
399d372a8e8SPavel Labath   m_binary =
400d372a8e8SPavel Labath       llvm::unique_dyn_cast<llvm::object::COFFObjectFile>(std::move(*binary));
401d372a8e8SPavel Labath   if (!m_binary)
402037ed1beSAaron Smith     return false;
403037ed1beSAaron Smith 
404d372a8e8SPavel Labath   LLDB_LOG(log, "this = {0}, module = {1} ({2}), file = {3}, binary = {4}",
405d372a8e8SPavel Labath            this, GetModule().get(), GetModule()->GetSpecificationDescription(),
406d372a8e8SPavel Labath            m_file.GetPath(), m_binary.get());
407037ed1beSAaron Smith   return true;
408037ed1beSAaron Smith }
409037ed1beSAaron Smith 
ObjectFilePECOFF(const lldb::ModuleSP & module_sp,DataBufferSP data_sp,lldb::offset_t data_offset,const FileSpec * file,lldb::offset_t file_offset,lldb::offset_t length)410e72dfb32SGreg Clayton ObjectFilePECOFF::ObjectFilePECOFF(const lldb::ModuleSP &module_sp,
411f2ea125eSJonas Devlieghere                                    DataBufferSP data_sp,
4125ce9c565SGreg Clayton                                    lldb::offset_t data_offset,
413f754f88fSGreg Clayton                                    const FileSpec *file,
4145ce9c565SGreg Clayton                                    lldb::offset_t file_offset,
415b9c1b51eSKate Stone                                    lldb::offset_t length)
416b9c1b51eSKate Stone     : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
417459cfa5eSSlava Gurevich       m_dos_header(), m_coff_header(), m_coff_header_opt(), m_sect_headers(),
418459cfa5eSSlava Gurevich       m_image_base(LLDB_INVALID_ADDRESS), m_entry_point_address(),
419459cfa5eSSlava Gurevich       m_deps_filespec() {}
420f754f88fSGreg Clayton 
ObjectFilePECOFF(const lldb::ModuleSP & module_sp,WritableDataBufferSP header_data_sp,const lldb::ProcessSP & process_sp,addr_t header_addr)421344546bdSWalter Erquinigo ObjectFilePECOFF::ObjectFilePECOFF(const lldb::ModuleSP &module_sp,
422f2ea125eSJonas Devlieghere                                    WritableDataBufferSP header_data_sp,
423344546bdSWalter Erquinigo                                    const lldb::ProcessSP &process_sp,
424344546bdSWalter Erquinigo                                    addr_t header_addr)
425344546bdSWalter Erquinigo     : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
426459cfa5eSSlava Gurevich       m_dos_header(), m_coff_header(), m_coff_header_opt(), m_sect_headers(),
427459cfa5eSSlava Gurevich       m_image_base(LLDB_INVALID_ADDRESS), m_entry_point_address(),
428459cfa5eSSlava Gurevich       m_deps_filespec() {}
429344546bdSWalter Erquinigo 
430fd2433e1SJonas Devlieghere ObjectFilePECOFF::~ObjectFilePECOFF() = default;
431f754f88fSGreg Clayton 
ParseHeader()432b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseHeader() {
433a1743499SGreg Clayton   ModuleSP module_sp(GetModule());
434b9c1b51eSKate Stone   if (module_sp) {
43516ff8604SSaleem Abdulrasool     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
436f754f88fSGreg Clayton     m_sect_headers.clear();
437f754f88fSGreg Clayton     m_data.SetByteOrder(eByteOrderLittle);
438c7bece56SGreg Clayton     lldb::offset_t offset = 0;
439f754f88fSGreg Clayton 
440b9c1b51eSKate Stone     if (ParseDOSHeader(m_data, m_dos_header)) {
441f754f88fSGreg Clayton       offset = m_dos_header.e_lfanew;
442f754f88fSGreg Clayton       uint32_t pe_signature = m_data.GetU32(&offset);
443f754f88fSGreg Clayton       if (pe_signature != IMAGE_NT_SIGNATURE)
444f754f88fSGreg Clayton         return false;
445b9c1b51eSKate Stone       if (ParseCOFFHeader(m_data, &offset, m_coff_header)) {
446f754f88fSGreg Clayton         if (m_coff_header.hdrsize > 0)
447f754f88fSGreg Clayton           ParseCOFFOptionalHeader(&offset);
448f754f88fSGreg Clayton         ParseSectionHeaders(offset);
44928469ca3SGreg Clayton       }
450a0f72441SMartin Storsjö       m_data.SetAddressByteSize(GetAddressByteSize());
451f754f88fSGreg Clayton       return true;
452f754f88fSGreg Clayton     }
453a1743499SGreg Clayton   }
454f754f88fSGreg Clayton   return false;
455f754f88fSGreg Clayton }
456f754f88fSGreg Clayton 
SetLoadAddress(Target & target,addr_t value,bool value_is_offset)457b9c1b51eSKate Stone bool ObjectFilePECOFF::SetLoadAddress(Target &target, addr_t value,
458b9c1b51eSKate Stone                                       bool value_is_offset) {
4592756adf3SVirgile Bello   bool changed = false;
4602756adf3SVirgile Bello   ModuleSP module_sp = GetModule();
461b9c1b51eSKate Stone   if (module_sp) {
4622756adf3SVirgile Bello     size_t num_loaded_sections = 0;
4632756adf3SVirgile Bello     SectionList *section_list = GetSectionList();
464b9c1b51eSKate Stone     if (section_list) {
465b9c1b51eSKate Stone       if (!value_is_offset) {
4662756adf3SVirgile Bello         value -= m_image_base;
4672756adf3SVirgile Bello       }
4682756adf3SVirgile Bello 
4692756adf3SVirgile Bello       const size_t num_sections = section_list->GetSize();
4702756adf3SVirgile Bello       size_t sect_idx = 0;
4712756adf3SVirgile Bello 
472b9c1b51eSKate Stone       for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
47305097246SAdrian Prantl         // Iterate through the object file sections to find all of the sections
47405097246SAdrian Prantl         // that have SHF_ALLOC in their flag bits.
4752756adf3SVirgile Bello         SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
476b9c1b51eSKate Stone         if (section_sp && !section_sp->IsThreadSpecific()) {
477b9c1b51eSKate Stone           if (target.GetSectionLoadList().SetSectionLoadAddress(
478b9c1b51eSKate Stone                   section_sp, section_sp->GetFileAddress() + value))
4792756adf3SVirgile Bello             ++num_loaded_sections;
4802756adf3SVirgile Bello         }
4812756adf3SVirgile Bello       }
4822756adf3SVirgile Bello       changed = num_loaded_sections > 0;
4832756adf3SVirgile Bello     }
4842756adf3SVirgile Bello   }
4852756adf3SVirgile Bello   return changed;
4862756adf3SVirgile Bello }
4872756adf3SVirgile Bello 
GetByteOrder() const488b9c1b51eSKate Stone ByteOrder ObjectFilePECOFF::GetByteOrder() const { return eByteOrderLittle; }
489f754f88fSGreg Clayton 
IsExecutable() const490b9c1b51eSKate Stone bool ObjectFilePECOFF::IsExecutable() const {
491237ad974SCharles Davis   return (m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0;
492f754f88fSGreg Clayton }
493f754f88fSGreg Clayton 
GetAddressByteSize() const494b9c1b51eSKate Stone uint32_t ObjectFilePECOFF::GetAddressByteSize() const {
495f754f88fSGreg Clayton   if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32_PLUS)
496f754f88fSGreg Clayton     return 8;
497f754f88fSGreg Clayton   else if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32)
498f754f88fSGreg Clayton     return 4;
499f754f88fSGreg Clayton   return 4;
500f754f88fSGreg Clayton }
501f754f88fSGreg Clayton 
502f754f88fSGreg Clayton // NeedsEndianSwap
503f754f88fSGreg Clayton //
50405097246SAdrian Prantl // Return true if an endian swap needs to occur when extracting data from this
50505097246SAdrian Prantl // file.
NeedsEndianSwap() const506b9c1b51eSKate Stone bool ObjectFilePECOFF::NeedsEndianSwap() const {
507f754f88fSGreg Clayton #if defined(__LITTLE_ENDIAN__)
508f754f88fSGreg Clayton   return false;
509f754f88fSGreg Clayton #else
510f754f88fSGreg Clayton   return true;
511f754f88fSGreg Clayton #endif
512f754f88fSGreg Clayton }
513f754f88fSGreg Clayton // ParseDOSHeader
ParseDOSHeader(DataExtractor & data,dos_header_t & dos_header)514b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseDOSHeader(DataExtractor &data,
515b9c1b51eSKate Stone                                       dos_header_t &dos_header) {
516f754f88fSGreg Clayton   bool success = false;
517c7bece56SGreg Clayton   lldb::offset_t offset = 0;
51889eb1baeSVirgile Bello   success = data.ValidOffsetForDataOfSize(0, sizeof(dos_header));
519f754f88fSGreg Clayton 
520b9c1b51eSKate Stone   if (success) {
52189eb1baeSVirgile Bello     dos_header.e_magic = data.GetU16(&offset); // Magic number
52289eb1baeSVirgile Bello     success = dos_header.e_magic == IMAGE_DOS_SIGNATURE;
523f754f88fSGreg Clayton 
524b9c1b51eSKate Stone     if (success) {
52589eb1baeSVirgile Bello       dos_header.e_cblp = data.GetU16(&offset); // Bytes on last page of file
52689eb1baeSVirgile Bello       dos_header.e_cp = data.GetU16(&offset);   // Pages in file
52789eb1baeSVirgile Bello       dos_header.e_crlc = data.GetU16(&offset); // Relocations
528b9c1b51eSKate Stone       dos_header.e_cparhdr =
529b9c1b51eSKate Stone           data.GetU16(&offset); // Size of header in paragraphs
530b9c1b51eSKate Stone       dos_header.e_minalloc =
531b9c1b51eSKate Stone           data.GetU16(&offset); // Minimum extra paragraphs needed
532b9c1b51eSKate Stone       dos_header.e_maxalloc =
533b9c1b51eSKate Stone           data.GetU16(&offset);               // Maximum extra paragraphs needed
53489eb1baeSVirgile Bello       dos_header.e_ss = data.GetU16(&offset); // Initial (relative) SS value
53589eb1baeSVirgile Bello       dos_header.e_sp = data.GetU16(&offset); // Initial SP value
53689eb1baeSVirgile Bello       dos_header.e_csum = data.GetU16(&offset); // Checksum
53789eb1baeSVirgile Bello       dos_header.e_ip = data.GetU16(&offset);   // Initial IP value
53889eb1baeSVirgile Bello       dos_header.e_cs = data.GetU16(&offset);   // Initial (relative) CS value
539b9c1b51eSKate Stone       dos_header.e_lfarlc =
540b9c1b51eSKate Stone           data.GetU16(&offset); // File address of relocation table
54189eb1baeSVirgile Bello       dos_header.e_ovno = data.GetU16(&offset); // Overlay number
542f754f88fSGreg Clayton 
54389eb1baeSVirgile Bello       dos_header.e_res[0] = data.GetU16(&offset); // Reserved words
54489eb1baeSVirgile Bello       dos_header.e_res[1] = data.GetU16(&offset); // Reserved words
54589eb1baeSVirgile Bello       dos_header.e_res[2] = data.GetU16(&offset); // Reserved words
54689eb1baeSVirgile Bello       dos_header.e_res[3] = data.GetU16(&offset); // Reserved words
547f754f88fSGreg Clayton 
548b9c1b51eSKate Stone       dos_header.e_oemid =
549b9c1b51eSKate Stone           data.GetU16(&offset); // OEM identifier (for e_oeminfo)
550b9c1b51eSKate Stone       dos_header.e_oeminfo =
551b9c1b51eSKate Stone           data.GetU16(&offset); // OEM information; e_oemid specific
55289eb1baeSVirgile Bello       dos_header.e_res2[0] = data.GetU16(&offset); // Reserved words
55389eb1baeSVirgile Bello       dos_header.e_res2[1] = data.GetU16(&offset); // Reserved words
55489eb1baeSVirgile Bello       dos_header.e_res2[2] = data.GetU16(&offset); // Reserved words
55589eb1baeSVirgile Bello       dos_header.e_res2[3] = data.GetU16(&offset); // Reserved words
55689eb1baeSVirgile Bello       dos_header.e_res2[4] = data.GetU16(&offset); // Reserved words
55789eb1baeSVirgile Bello       dos_header.e_res2[5] = data.GetU16(&offset); // Reserved words
55889eb1baeSVirgile Bello       dos_header.e_res2[6] = data.GetU16(&offset); // Reserved words
55989eb1baeSVirgile Bello       dos_header.e_res2[7] = data.GetU16(&offset); // Reserved words
56089eb1baeSVirgile Bello       dos_header.e_res2[8] = data.GetU16(&offset); // Reserved words
56189eb1baeSVirgile Bello       dos_header.e_res2[9] = data.GetU16(&offset); // Reserved words
562f754f88fSGreg Clayton 
563b9c1b51eSKate Stone       dos_header.e_lfanew =
564b9c1b51eSKate Stone           data.GetU32(&offset); // File address of new exe header
565f754f88fSGreg Clayton     }
566f754f88fSGreg Clayton   }
567f754f88fSGreg Clayton   if (!success)
56889eb1baeSVirgile Bello     memset(&dos_header, 0, sizeof(dos_header));
569f754f88fSGreg Clayton   return success;
570f754f88fSGreg Clayton }
571f754f88fSGreg Clayton 
572f754f88fSGreg Clayton // ParserCOFFHeader
ParseCOFFHeader(DataExtractor & data,lldb::offset_t * offset_ptr,coff_header_t & coff_header)573b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseCOFFHeader(DataExtractor &data,
574b9c1b51eSKate Stone                                        lldb::offset_t *offset_ptr,
575b9c1b51eSKate Stone                                        coff_header_t &coff_header) {
576b9c1b51eSKate Stone   bool success =
577b9c1b51eSKate Stone       data.ValidOffsetForDataOfSize(*offset_ptr, sizeof(coff_header));
578b9c1b51eSKate Stone   if (success) {
57989eb1baeSVirgile Bello     coff_header.machine = data.GetU16(offset_ptr);
58089eb1baeSVirgile Bello     coff_header.nsects = data.GetU16(offset_ptr);
58189eb1baeSVirgile Bello     coff_header.modtime = data.GetU32(offset_ptr);
58289eb1baeSVirgile Bello     coff_header.symoff = data.GetU32(offset_ptr);
58389eb1baeSVirgile Bello     coff_header.nsyms = data.GetU32(offset_ptr);
58489eb1baeSVirgile Bello     coff_header.hdrsize = data.GetU16(offset_ptr);
58589eb1baeSVirgile Bello     coff_header.flags = data.GetU16(offset_ptr);
586f754f88fSGreg Clayton   }
587f754f88fSGreg Clayton   if (!success)
58889eb1baeSVirgile Bello     memset(&coff_header, 0, sizeof(coff_header));
589f754f88fSGreg Clayton   return success;
590f754f88fSGreg Clayton }
591f754f88fSGreg Clayton 
ParseCOFFOptionalHeader(lldb::offset_t * offset_ptr)592b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseCOFFOptionalHeader(lldb::offset_t *offset_ptr) {
593f754f88fSGreg Clayton   bool success = false;
594c7bece56SGreg Clayton   const lldb::offset_t end_offset = *offset_ptr + m_coff_header.hdrsize;
595b9c1b51eSKate Stone   if (*offset_ptr < end_offset) {
596f754f88fSGreg Clayton     success = true;
597f754f88fSGreg Clayton     m_coff_header_opt.magic = m_data.GetU16(offset_ptr);
598f754f88fSGreg Clayton     m_coff_header_opt.major_linker_version = m_data.GetU8(offset_ptr);
599f754f88fSGreg Clayton     m_coff_header_opt.minor_linker_version = m_data.GetU8(offset_ptr);
600f754f88fSGreg Clayton     m_coff_header_opt.code_size = m_data.GetU32(offset_ptr);
601f754f88fSGreg Clayton     m_coff_header_opt.data_size = m_data.GetU32(offset_ptr);
602f754f88fSGreg Clayton     m_coff_header_opt.bss_size = m_data.GetU32(offset_ptr);
603f754f88fSGreg Clayton     m_coff_header_opt.entry = m_data.GetU32(offset_ptr);
604f754f88fSGreg Clayton     m_coff_header_opt.code_offset = m_data.GetU32(offset_ptr);
605f754f88fSGreg Clayton 
606f754f88fSGreg Clayton     const uint32_t addr_byte_size = GetAddressByteSize();
607f754f88fSGreg Clayton 
608b9c1b51eSKate Stone     if (*offset_ptr < end_offset) {
609b9c1b51eSKate Stone       if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32) {
610f754f88fSGreg Clayton         // PE32 only
611f754f88fSGreg Clayton         m_coff_header_opt.data_offset = m_data.GetU32(offset_ptr);
612b9c1b51eSKate Stone       } else
613f754f88fSGreg Clayton         m_coff_header_opt.data_offset = 0;
614f754f88fSGreg Clayton 
615b9c1b51eSKate Stone       if (*offset_ptr < end_offset) {
616b9c1b51eSKate Stone         m_coff_header_opt.image_base =
617b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
618f754f88fSGreg Clayton         m_coff_header_opt.sect_alignment = m_data.GetU32(offset_ptr);
619f754f88fSGreg Clayton         m_coff_header_opt.file_alignment = m_data.GetU32(offset_ptr);
620f754f88fSGreg Clayton         m_coff_header_opt.major_os_system_version = m_data.GetU16(offset_ptr);
621f754f88fSGreg Clayton         m_coff_header_opt.minor_os_system_version = m_data.GetU16(offset_ptr);
622f754f88fSGreg Clayton         m_coff_header_opt.major_image_version = m_data.GetU16(offset_ptr);
623f754f88fSGreg Clayton         m_coff_header_opt.minor_image_version = m_data.GetU16(offset_ptr);
624f754f88fSGreg Clayton         m_coff_header_opt.major_subsystem_version = m_data.GetU16(offset_ptr);
625f754f88fSGreg Clayton         m_coff_header_opt.minor_subsystem_version = m_data.GetU16(offset_ptr);
626f754f88fSGreg Clayton         m_coff_header_opt.reserved1 = m_data.GetU32(offset_ptr);
627f754f88fSGreg Clayton         m_coff_header_opt.image_size = m_data.GetU32(offset_ptr);
628f754f88fSGreg Clayton         m_coff_header_opt.header_size = m_data.GetU32(offset_ptr);
62928469ca3SGreg Clayton         m_coff_header_opt.checksum = m_data.GetU32(offset_ptr);
630f754f88fSGreg Clayton         m_coff_header_opt.subsystem = m_data.GetU16(offset_ptr);
631f754f88fSGreg Clayton         m_coff_header_opt.dll_flags = m_data.GetU16(offset_ptr);
632b9c1b51eSKate Stone         m_coff_header_opt.stack_reserve_size =
633b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
634b9c1b51eSKate Stone         m_coff_header_opt.stack_commit_size =
635b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
636b9c1b51eSKate Stone         m_coff_header_opt.heap_reserve_size =
637b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
638b9c1b51eSKate Stone         m_coff_header_opt.heap_commit_size =
639b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
640f754f88fSGreg Clayton         m_coff_header_opt.loader_flags = m_data.GetU32(offset_ptr);
641f754f88fSGreg Clayton         uint32_t num_data_dir_entries = m_data.GetU32(offset_ptr);
642f754f88fSGreg Clayton         m_coff_header_opt.data_dirs.clear();
643f754f88fSGreg Clayton         m_coff_header_opt.data_dirs.resize(num_data_dir_entries);
644f754f88fSGreg Clayton         uint32_t i;
645b9c1b51eSKate Stone         for (i = 0; i < num_data_dir_entries; i++) {
646f754f88fSGreg Clayton           m_coff_header_opt.data_dirs[i].vmaddr = m_data.GetU32(offset_ptr);
647f754f88fSGreg Clayton           m_coff_header_opt.data_dirs[i].vmsize = m_data.GetU32(offset_ptr);
648f754f88fSGreg Clayton         }
6492756adf3SVirgile Bello 
6502756adf3SVirgile Bello         m_image_base = m_coff_header_opt.image_base;
651f754f88fSGreg Clayton       }
652f754f88fSGreg Clayton     }
653f754f88fSGreg Clayton   }
654f754f88fSGreg Clayton   // Make sure we are on track for section data which follows
655f754f88fSGreg Clayton   *offset_ptr = end_offset;
656f754f88fSGreg Clayton   return success;
657f754f88fSGreg Clayton }
658f754f88fSGreg Clayton 
GetRVA(const Address & addr) const65930c2441aSAleksandr Urakov uint32_t ObjectFilePECOFF::GetRVA(const Address &addr) const {
66030c2441aSAleksandr Urakov   return addr.GetFileAddress() - m_image_base;
66130c2441aSAleksandr Urakov }
66230c2441aSAleksandr Urakov 
GetAddress(uint32_t rva)66330c2441aSAleksandr Urakov Address ObjectFilePECOFF::GetAddress(uint32_t rva) {
66430c2441aSAleksandr Urakov   SectionList *sect_list = GetSectionList();
66530c2441aSAleksandr Urakov   if (!sect_list)
66630c2441aSAleksandr Urakov     return Address(GetFileAddress(rva));
66730c2441aSAleksandr Urakov 
66830c2441aSAleksandr Urakov   return Address(GetFileAddress(rva), sect_list);
66930c2441aSAleksandr Urakov }
67030c2441aSAleksandr Urakov 
GetFileAddress(uint32_t rva) const67130c2441aSAleksandr Urakov lldb::addr_t ObjectFilePECOFF::GetFileAddress(uint32_t rva) const {
67230c2441aSAleksandr Urakov   return m_image_base + rva;
67330c2441aSAleksandr Urakov }
67430c2441aSAleksandr Urakov 
ReadImageData(uint32_t offset,size_t size)675344546bdSWalter Erquinigo DataExtractor ObjectFilePECOFF::ReadImageData(uint32_t offset, size_t size) {
67630c2441aSAleksandr Urakov   if (!size)
67730c2441aSAleksandr Urakov     return {};
67830c2441aSAleksandr Urakov 
679a4a00cedSFred Riss   if (m_data.ValidOffsetForDataOfSize(offset, size))
680a4a00cedSFred Riss     return DataExtractor(m_data, offset, size);
681a4a00cedSFred Riss 
682344546bdSWalter Erquinigo   ProcessSP process_sp(m_process_wp.lock());
683344546bdSWalter Erquinigo   DataExtractor data;
684344546bdSWalter Erquinigo   if (process_sp) {
685a8f3ae7cSJonas Devlieghere     auto data_up = std::make_unique<DataBufferHeap>(size, 0);
68697206d57SZachary Turner     Status readmem_error;
687344546bdSWalter Erquinigo     size_t bytes_read =
688d5b44036SJonas Devlieghere         process_sp->ReadMemory(m_image_base + offset, data_up->GetBytes(),
689d5b44036SJonas Devlieghere                                data_up->GetByteSize(), readmem_error);
690344546bdSWalter Erquinigo     if (bytes_read == size) {
691d5b44036SJonas Devlieghere       DataBufferSP buffer_sp(data_up.release());
692344546bdSWalter Erquinigo       data.SetData(buffer_sp, 0, buffer_sp->GetByteSize());
693344546bdSWalter Erquinigo     }
694344546bdSWalter Erquinigo   }
695344546bdSWalter Erquinigo   return data;
696344546bdSWalter Erquinigo }
697344546bdSWalter Erquinigo 
ReadImageDataByRVA(uint32_t rva,size_t size)69830c2441aSAleksandr Urakov DataExtractor ObjectFilePECOFF::ReadImageDataByRVA(uint32_t rva, size_t size) {
69930c2441aSAleksandr Urakov   Address addr = GetAddress(rva);
7007e1a3076SMartin Storsjö   SectionSP sect = addr.GetSection();
7017e1a3076SMartin Storsjö   if (!sect)
7027e1a3076SMartin Storsjö     return {};
7037e1a3076SMartin Storsjö   rva = sect->GetFileOffset() + addr.GetOffset();
70430c2441aSAleksandr Urakov 
70530c2441aSAleksandr Urakov   return ReadImageData(rva, size);
70630c2441aSAleksandr Urakov }
70730c2441aSAleksandr Urakov 
708f754f88fSGreg Clayton // ParseSectionHeaders
ParseSectionHeaders(uint32_t section_header_data_offset)709b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseSectionHeaders(
710b9c1b51eSKate Stone     uint32_t section_header_data_offset) {
711f754f88fSGreg Clayton   const uint32_t nsects = m_coff_header.nsects;
712f754f88fSGreg Clayton   m_sect_headers.clear();
713f754f88fSGreg Clayton 
714b9c1b51eSKate Stone   if (nsects > 0) {
715f754f88fSGreg Clayton     const size_t section_header_byte_size = nsects * sizeof(section_header_t);
716344546bdSWalter Erquinigo     DataExtractor section_header_data =
717344546bdSWalter Erquinigo         ReadImageData(section_header_data_offset, section_header_byte_size);
718f754f88fSGreg Clayton 
719c7bece56SGreg Clayton     lldb::offset_t offset = 0;
720b9c1b51eSKate Stone     if (section_header_data.ValidOffsetForDataOfSize(
721b9c1b51eSKate Stone             offset, section_header_byte_size)) {
722f754f88fSGreg Clayton       m_sect_headers.resize(nsects);
723f754f88fSGreg Clayton 
724b9c1b51eSKate Stone       for (uint32_t idx = 0; idx < nsects; ++idx) {
725f754f88fSGreg Clayton         const void *name_data = section_header_data.GetData(&offset, 8);
726b9c1b51eSKate Stone         if (name_data) {
727f754f88fSGreg Clayton           memcpy(m_sect_headers[idx].name, name_data, 8);
728f754f88fSGreg Clayton           m_sect_headers[idx].vmsize = section_header_data.GetU32(&offset);
729f754f88fSGreg Clayton           m_sect_headers[idx].vmaddr = section_header_data.GetU32(&offset);
730f754f88fSGreg Clayton           m_sect_headers[idx].size = section_header_data.GetU32(&offset);
731f754f88fSGreg Clayton           m_sect_headers[idx].offset = section_header_data.GetU32(&offset);
732f754f88fSGreg Clayton           m_sect_headers[idx].reloff = section_header_data.GetU32(&offset);
733f754f88fSGreg Clayton           m_sect_headers[idx].lineoff = section_header_data.GetU32(&offset);
734f754f88fSGreg Clayton           m_sect_headers[idx].nreloc = section_header_data.GetU16(&offset);
735f754f88fSGreg Clayton           m_sect_headers[idx].nline = section_header_data.GetU16(&offset);
736f754f88fSGreg Clayton           m_sect_headers[idx].flags = section_header_data.GetU32(&offset);
737f754f88fSGreg Clayton         }
738f754f88fSGreg Clayton       }
739f754f88fSGreg Clayton     }
740f754f88fSGreg Clayton   }
741f754f88fSGreg Clayton 
742a6682a41SJonas Devlieghere   return !m_sect_headers.empty();
743f754f88fSGreg Clayton }
744f754f88fSGreg Clayton 
GetSectionName(const section_header_t & sect)7452886e4a0SPavel Labath llvm::StringRef ObjectFilePECOFF::GetSectionName(const section_header_t &sect) {
746f15014ffSBenjamin Kramer   llvm::StringRef hdr_name(sect.name, llvm::array_lengthof(sect.name));
7472886e4a0SPavel Labath   hdr_name = hdr_name.split('\0').first;
7482886e4a0SPavel Labath   if (hdr_name.consume_front("/")) {
7492886e4a0SPavel Labath     lldb::offset_t stroff;
7502886e4a0SPavel Labath     if (!to_integer(hdr_name, stroff, 10))
7512886e4a0SPavel Labath       return "";
752b9c1b51eSKate Stone     lldb::offset_t string_file_offset =
753b9c1b51eSKate Stone         m_coff_header.symoff + (m_coff_header.nsyms * 18) + stroff;
7542886e4a0SPavel Labath     if (const char *name = m_data.GetCStr(&string_file_offset))
7552886e4a0SPavel Labath       return name;
7562886e4a0SPavel Labath     return "";
757f754f88fSGreg Clayton   }
7582886e4a0SPavel Labath   return hdr_name;
759f754f88fSGreg Clayton }
760f754f88fSGreg Clayton 
ParseSymtab(Symtab & symtab)7617e6df41fSGreg Clayton void ObjectFilePECOFF::ParseSymtab(Symtab &symtab) {
762f754f88fSGreg Clayton   SectionList *sect_list = GetSectionList();
76328469ca3SGreg Clayton   const uint32_t num_syms = m_coff_header.nsyms;
764344546bdSWalter Erquinigo   if (m_file && num_syms > 0 && m_coff_header.symoff > 0) {
7650076e715SGreg Clayton     const uint32_t symbol_size = 18;
76628469ca3SGreg Clayton     const size_t symbol_data_size = num_syms * symbol_size;
767c35b91ceSAdrian McCarthy     // Include the 4-byte string table size at the end of the symbols
768344546bdSWalter Erquinigo     DataExtractor symtab_data =
769344546bdSWalter Erquinigo         ReadImageData(m_coff_header.symoff, symbol_data_size + 4);
770c7bece56SGreg Clayton     lldb::offset_t offset = symbol_data_size;
77128469ca3SGreg Clayton     const uint32_t strtab_size = symtab_data.GetU32(&offset);
772344546bdSWalter Erquinigo     if (strtab_size > 0) {
773344546bdSWalter Erquinigo       DataExtractor strtab_data = ReadImageData(
774344546bdSWalter Erquinigo           m_coff_header.symoff + symbol_data_size, strtab_size);
77528469ca3SGreg Clayton 
77628469ca3SGreg Clayton       offset = 0;
77728469ca3SGreg Clayton       std::string symbol_name;
7787e6df41fSGreg Clayton       Symbol *symbols = symtab.Resize(num_syms);
779b9c1b51eSKate Stone       for (uint32_t i = 0; i < num_syms; ++i) {
780f754f88fSGreg Clayton         coff_symbol_t symbol;
78128469ca3SGreg Clayton         const uint32_t symbol_offset = offset;
782248a1305SKonrad Kleine         const char *symbol_name_cstr = nullptr;
783c35b91ceSAdrian McCarthy         // If the first 4 bytes of the symbol string are zero, then they
784c35b91ceSAdrian McCarthy         // are followed by a 4-byte string table offset. Else these
78528469ca3SGreg Clayton         // 8 bytes contain the symbol name
786b9c1b51eSKate Stone         if (symtab_data.GetU32(&offset) == 0) {
78705097246SAdrian Prantl           // Long string that doesn't fit into the symbol table name, so
78805097246SAdrian Prantl           // now we must read the 4 byte string table offset
78928469ca3SGreg Clayton           uint32_t strtab_offset = symtab_data.GetU32(&offset);
79028469ca3SGreg Clayton           symbol_name_cstr = strtab_data.PeekCStr(strtab_offset);
79128469ca3SGreg Clayton           symbol_name.assign(symbol_name_cstr);
792b9c1b51eSKate Stone         } else {
793b9c1b51eSKate Stone           // Short string that fits into the symbol table name which is 8
794b9c1b51eSKate Stone           // bytes
79528469ca3SGreg Clayton           offset += sizeof(symbol.name) - 4; // Skip remaining
79628469ca3SGreg Clayton           symbol_name_cstr = symtab_data.PeekCStr(symbol_offset);
797248a1305SKonrad Kleine           if (symbol_name_cstr == nullptr)
798f754f88fSGreg Clayton             break;
79928469ca3SGreg Clayton           symbol_name.assign(symbol_name_cstr, sizeof(symbol.name));
80028469ca3SGreg Clayton         }
80128469ca3SGreg Clayton         symbol.value = symtab_data.GetU32(&offset);
80228469ca3SGreg Clayton         symbol.sect = symtab_data.GetU16(&offset);
80328469ca3SGreg Clayton         symbol.type = symtab_data.GetU16(&offset);
80428469ca3SGreg Clayton         symbol.storage = symtab_data.GetU8(&offset);
80528469ca3SGreg Clayton         symbol.naux = symtab_data.GetU8(&offset);
806037520e9SGreg Clayton         symbols[i].GetMangled().SetValue(ConstString(symbol_name.c_str()));
807b9c1b51eSKate Stone         if ((int16_t)symbol.sect >= 1) {
8084394b5beSMartin Storsjö           Address symbol_addr(sect_list->FindSectionByID(symbol.sect),
809b9c1b51eSKate Stone                               symbol.value);
810358cf1eaSGreg Clayton           symbols[i].GetAddressRef() = symbol_addr;
811c35b91ceSAdrian McCarthy           symbols[i].SetType(MapSymbolType(symbol.type));
8120076e715SGreg Clayton         }
813f754f88fSGreg Clayton 
814b9c1b51eSKate Stone         if (symbol.naux > 0) {
815f754f88fSGreg Clayton           i += symbol.naux;
816f07ddbc9SMartin Storsjö           offset += symbol.naux * symbol_size;
8170076e715SGreg Clayton         }
818f754f88fSGreg Clayton       }
819f754f88fSGreg Clayton     }
820344546bdSWalter Erquinigo   }
821a4fe3a12SVirgile Bello 
822a4fe3a12SVirgile Bello   // Read export header
823b9c1b51eSKate Stone   if (coff_data_dir_export_table < m_coff_header_opt.data_dirs.size() &&
824b9c1b51eSKate Stone       m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmsize > 0 &&
825b9c1b51eSKate Stone       m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr > 0) {
826a4fe3a12SVirgile Bello     export_directory_entry export_table;
827b9c1b51eSKate Stone     uint32_t data_start =
828b9c1b51eSKate Stone         m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr;
829344546bdSWalter Erquinigo 
83030c2441aSAleksandr Urakov     DataExtractor symtab_data = ReadImageDataByRVA(
83130c2441aSAleksandr Urakov         data_start, m_coff_header_opt.data_dirs[0].vmsize);
832a4fe3a12SVirgile Bello     lldb::offset_t offset = 0;
833a4fe3a12SVirgile Bello 
834a4fe3a12SVirgile Bello     // Read export_table header
835a4fe3a12SVirgile Bello     export_table.characteristics = symtab_data.GetU32(&offset);
836a4fe3a12SVirgile Bello     export_table.time_date_stamp = symtab_data.GetU32(&offset);
837a4fe3a12SVirgile Bello     export_table.major_version = symtab_data.GetU16(&offset);
838a4fe3a12SVirgile Bello     export_table.minor_version = symtab_data.GetU16(&offset);
839a4fe3a12SVirgile Bello     export_table.name = symtab_data.GetU32(&offset);
840a4fe3a12SVirgile Bello     export_table.base = symtab_data.GetU32(&offset);
841a4fe3a12SVirgile Bello     export_table.number_of_functions = symtab_data.GetU32(&offset);
842a4fe3a12SVirgile Bello     export_table.number_of_names = symtab_data.GetU32(&offset);
843a4fe3a12SVirgile Bello     export_table.address_of_functions = symtab_data.GetU32(&offset);
844a4fe3a12SVirgile Bello     export_table.address_of_names = symtab_data.GetU32(&offset);
845a4fe3a12SVirgile Bello     export_table.address_of_name_ordinals = symtab_data.GetU32(&offset);
846a4fe3a12SVirgile Bello 
847a4fe3a12SVirgile Bello     bool has_ordinal = export_table.address_of_name_ordinals != 0;
848a4fe3a12SVirgile Bello 
849a4fe3a12SVirgile Bello     lldb::offset_t name_offset = export_table.address_of_names - data_start;
850b9c1b51eSKate Stone     lldb::offset_t name_ordinal_offset =
851b9c1b51eSKate Stone         export_table.address_of_name_ordinals - data_start;
852a4fe3a12SVirgile Bello 
8537e6df41fSGreg Clayton     Symbol *symbols = symtab.Resize(export_table.number_of_names);
854a4fe3a12SVirgile Bello 
855a4fe3a12SVirgile Bello     std::string symbol_name;
856a4fe3a12SVirgile Bello 
857a4fe3a12SVirgile Bello     // Read each export table entry
858b9c1b51eSKate Stone     for (size_t i = 0; i < export_table.number_of_names; ++i) {
859b9c1b51eSKate Stone       uint32_t name_ordinal =
860b9c1b51eSKate Stone           has_ordinal ? symtab_data.GetU16(&name_ordinal_offset) : i;
861a4fe3a12SVirgile Bello       uint32_t name_address = symtab_data.GetU32(&name_offset);
862a4fe3a12SVirgile Bello 
863b9c1b51eSKate Stone       const char *symbol_name_cstr =
864b9c1b51eSKate Stone           symtab_data.PeekCStr(name_address - data_start);
865a4fe3a12SVirgile Bello       symbol_name.assign(symbol_name_cstr);
866a4fe3a12SVirgile Bello 
867b9c1b51eSKate Stone       lldb::offset_t function_offset = export_table.address_of_functions -
868b9c1b51eSKate Stone                                         data_start +
869b9c1b51eSKate Stone                                         sizeof(uint32_t) * name_ordinal;
870a4fe3a12SVirgile Bello       uint32_t function_rva = symtab_data.GetU32(&function_offset);
871a4fe3a12SVirgile Bello 
872b9c1b51eSKate Stone       Address symbol_addr(m_coff_header_opt.image_base + function_rva,
873b9c1b51eSKate Stone                           sect_list);
874a4fe3a12SVirgile Bello       symbols[i].GetMangled().SetValue(ConstString(symbol_name.c_str()));
875358cf1eaSGreg Clayton       symbols[i].GetAddressRef() = symbol_addr;
876a4fe3a12SVirgile Bello       symbols[i].SetType(lldb::eSymbolTypeCode);
877a4fe3a12SVirgile Bello       symbols[i].SetDebug(true);
878a4fe3a12SVirgile Bello     }
879a4fe3a12SVirgile Bello   }
880f754f88fSGreg Clayton }
881f754f88fSGreg Clayton 
CreateCallFrameInfo()88230c2441aSAleksandr Urakov std::unique_ptr<CallFrameInfo> ObjectFilePECOFF::CreateCallFrameInfo() {
88330c2441aSAleksandr Urakov   if (coff_data_dir_exception_table >= m_coff_header_opt.data_dirs.size())
88430c2441aSAleksandr Urakov     return {};
88530c2441aSAleksandr Urakov 
88630c2441aSAleksandr Urakov   data_directory data_dir_exception =
88730c2441aSAleksandr Urakov       m_coff_header_opt.data_dirs[coff_data_dir_exception_table];
88830c2441aSAleksandr Urakov   if (!data_dir_exception.vmaddr)
88930c2441aSAleksandr Urakov     return {};
89030c2441aSAleksandr Urakov 
891aa786b88SMartin Storsjö   if (m_coff_header.machine != llvm::COFF::IMAGE_FILE_MACHINE_AMD64)
892aa786b88SMartin Storsjö     return {};
893aa786b88SMartin Storsjö 
89430c2441aSAleksandr Urakov   return std::make_unique<PECallFrameInfo>(*this, data_dir_exception.vmaddr,
89530c2441aSAleksandr Urakov                                            data_dir_exception.vmsize);
89630c2441aSAleksandr Urakov }
89730c2441aSAleksandr Urakov 
IsStripped()898b9c1b51eSKate Stone bool ObjectFilePECOFF::IsStripped() {
8993046e668SGreg Clayton   // TODO: determine this for COFF
9003046e668SGreg Clayton   return false;
9013046e668SGreg Clayton }
9023046e668SGreg Clayton 
GetSectionType(llvm::StringRef sect_name,const section_header_t & sect)9032e5bb6d8SMartin Storsjö SectionType ObjectFilePECOFF::GetSectionType(llvm::StringRef sect_name,
9042e5bb6d8SMartin Storsjö                                              const section_header_t &sect) {
9052e5bb6d8SMartin Storsjö   ConstString const_sect_name(sect_name);
9062e5bb6d8SMartin Storsjö   static ConstString g_code_sect_name(".code");
9072e5bb6d8SMartin Storsjö   static ConstString g_CODE_sect_name("CODE");
9082e5bb6d8SMartin Storsjö   static ConstString g_data_sect_name(".data");
9092e5bb6d8SMartin Storsjö   static ConstString g_DATA_sect_name("DATA");
9102e5bb6d8SMartin Storsjö   static ConstString g_bss_sect_name(".bss");
9112e5bb6d8SMartin Storsjö   static ConstString g_BSS_sect_name("BSS");
9122e5bb6d8SMartin Storsjö 
9132e5bb6d8SMartin Storsjö   if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_CODE &&
9142e5bb6d8SMartin Storsjö       ((const_sect_name == g_code_sect_name) ||
9152e5bb6d8SMartin Storsjö        (const_sect_name == g_CODE_sect_name))) {
9162e5bb6d8SMartin Storsjö     return eSectionTypeCode;
9172e5bb6d8SMartin Storsjö   }
9182e5bb6d8SMartin Storsjö   if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA &&
9192e5bb6d8SMartin Storsjö              ((const_sect_name == g_data_sect_name) ||
9202e5bb6d8SMartin Storsjö               (const_sect_name == g_DATA_sect_name))) {
9212e5bb6d8SMartin Storsjö     if (sect.size == 0 && sect.offset == 0)
9222e5bb6d8SMartin Storsjö       return eSectionTypeZeroFill;
9232e5bb6d8SMartin Storsjö     else
9242e5bb6d8SMartin Storsjö       return eSectionTypeData;
9252e5bb6d8SMartin Storsjö   }
9262e5bb6d8SMartin Storsjö   if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA &&
9272e5bb6d8SMartin Storsjö              ((const_sect_name == g_bss_sect_name) ||
9282e5bb6d8SMartin Storsjö               (const_sect_name == g_BSS_sect_name))) {
9292e5bb6d8SMartin Storsjö     if (sect.size == 0)
9302e5bb6d8SMartin Storsjö       return eSectionTypeZeroFill;
9312e5bb6d8SMartin Storsjö     else
9322e5bb6d8SMartin Storsjö       return eSectionTypeData;
9332e5bb6d8SMartin Storsjö   }
9342e5bb6d8SMartin Storsjö 
9352e5bb6d8SMartin Storsjö   SectionType section_type =
9362e5bb6d8SMartin Storsjö       llvm::StringSwitch<SectionType>(sect_name)
9372e5bb6d8SMartin Storsjö           .Case(".debug", eSectionTypeDebug)
9382e5bb6d8SMartin Storsjö           .Case(".stabstr", eSectionTypeDataCString)
9392e5bb6d8SMartin Storsjö           .Case(".reloc", eSectionTypeOther)
9402e5bb6d8SMartin Storsjö           .Case(".debug_abbrev", eSectionTypeDWARFDebugAbbrev)
9412e5bb6d8SMartin Storsjö           .Case(".debug_aranges", eSectionTypeDWARFDebugAranges)
9422e5bb6d8SMartin Storsjö           .Case(".debug_frame", eSectionTypeDWARFDebugFrame)
9432e5bb6d8SMartin Storsjö           .Case(".debug_info", eSectionTypeDWARFDebugInfo)
9442e5bb6d8SMartin Storsjö           .Case(".debug_line", eSectionTypeDWARFDebugLine)
9452e5bb6d8SMartin Storsjö           .Case(".debug_loc", eSectionTypeDWARFDebugLoc)
9462e5bb6d8SMartin Storsjö           .Case(".debug_loclists", eSectionTypeDWARFDebugLocLists)
9472e5bb6d8SMartin Storsjö           .Case(".debug_macinfo", eSectionTypeDWARFDebugMacInfo)
9482e5bb6d8SMartin Storsjö           .Case(".debug_names", eSectionTypeDWARFDebugNames)
9492e5bb6d8SMartin Storsjö           .Case(".debug_pubnames", eSectionTypeDWARFDebugPubNames)
9502e5bb6d8SMartin Storsjö           .Case(".debug_pubtypes", eSectionTypeDWARFDebugPubTypes)
9512e5bb6d8SMartin Storsjö           .Case(".debug_ranges", eSectionTypeDWARFDebugRanges)
9522e5bb6d8SMartin Storsjö           .Case(".debug_str", eSectionTypeDWARFDebugStr)
9532e5bb6d8SMartin Storsjö           .Case(".debug_types", eSectionTypeDWARFDebugTypes)
954934c025eSMartin Storsjö           // .eh_frame can be truncated to 8 chars.
955934c025eSMartin Storsjö           .Cases(".eh_frame", ".eh_fram", eSectionTypeEHFrame)
9562e5bb6d8SMartin Storsjö           .Case(".gosymtab", eSectionTypeGoSymtab)
9572e5bb6d8SMartin Storsjö           .Default(eSectionTypeInvalid);
9582e5bb6d8SMartin Storsjö   if (section_type != eSectionTypeInvalid)
9592e5bb6d8SMartin Storsjö     return section_type;
9602e5bb6d8SMartin Storsjö 
9612e5bb6d8SMartin Storsjö   if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_CODE)
9622e5bb6d8SMartin Storsjö     return eSectionTypeCode;
9632e5bb6d8SMartin Storsjö   if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
9642e5bb6d8SMartin Storsjö     return eSectionTypeData;
9652e5bb6d8SMartin Storsjö   if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) {
9662e5bb6d8SMartin Storsjö     if (sect.size == 0)
9672e5bb6d8SMartin Storsjö       return eSectionTypeZeroFill;
9682e5bb6d8SMartin Storsjö     else
9692e5bb6d8SMartin Storsjö       return eSectionTypeData;
9702e5bb6d8SMartin Storsjö   }
9712e5bb6d8SMartin Storsjö   return eSectionTypeOther;
9722e5bb6d8SMartin Storsjö }
9732e5bb6d8SMartin Storsjö 
CreateSections(SectionList & unified_section_list)974b9c1b51eSKate Stone void ObjectFilePECOFF::CreateSections(SectionList &unified_section_list) {
975d5b44036SJonas Devlieghere   if (m_sections_up)
97688a2c2a4SPavel Labath     return;
97706412daeSJonas Devlieghere   m_sections_up = std::make_unique<SectionList>();
978a1743499SGreg Clayton   ModuleSP module_sp(GetModule());
979b9c1b51eSKate Stone   if (module_sp) {
98016ff8604SSaleem Abdulrasool     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
9817db8b5c4SPavel Labath 
98273a7a55cSPavel Labath     SectionSP header_sp = std::make_shared<Section>(
98373a7a55cSPavel Labath         module_sp, this, ~user_id_t(0), ConstString("PECOFF header"),
98473a7a55cSPavel Labath         eSectionTypeOther, m_coff_header_opt.image_base,
98573a7a55cSPavel Labath         m_coff_header_opt.header_size,
98673a7a55cSPavel Labath         /*file_offset*/ 0, m_coff_header_opt.header_size,
98773a7a55cSPavel Labath         m_coff_header_opt.sect_alignment,
9887db8b5c4SPavel Labath         /*flags*/ 0);
989f1e0ae34SPavel Labath     header_sp->SetPermissions(ePermissionsReadable);
99073a7a55cSPavel Labath     m_sections_up->AddSection(header_sp);
99173a7a55cSPavel Labath     unified_section_list.AddSection(header_sp);
9927db8b5c4SPavel Labath 
993f754f88fSGreg Clayton     const uint32_t nsects = m_sect_headers.size();
994e72dfb32SGreg Clayton     ModuleSP module_sp(GetModule());
995b9c1b51eSKate Stone     for (uint32_t idx = 0; idx < nsects; ++idx) {
9962e5bb6d8SMartin Storsjö       llvm::StringRef sect_name = GetSectionName(m_sect_headers[idx]);
9972e5bb6d8SMartin Storsjö       ConstString const_sect_name(sect_name);
9982e5bb6d8SMartin Storsjö       SectionType section_type = GetSectionType(sect_name, m_sect_headers[idx]);
999f754f88fSGreg Clayton 
1000b9c1b51eSKate Stone       SectionSP section_sp(new Section(
1001b9c1b51eSKate Stone           module_sp,       // Module to which this section belongs
1002a7499c98SMichael Sartain           this,            // Object file to which this section belongs
10037db8b5c4SPavel Labath           idx + 1,         // Section ID is the 1 based section index.
1004f754f88fSGreg Clayton           const_sect_name, // Name of this section
10057db8b5c4SPavel Labath           section_type,
100673a7a55cSPavel Labath           m_coff_header_opt.image_base +
1007b9c1b51eSKate Stone               m_sect_headers[idx].vmaddr, // File VM address == addresses as
1008b9c1b51eSKate Stone                                           // they are found in the object file
1009f754f88fSGreg Clayton           m_sect_headers[idx].vmsize,     // VM size in bytes of this section
1010b9c1b51eSKate Stone           m_sect_headers[idx]
1011b9c1b51eSKate Stone               .offset, // Offset to the data for this section in the file
1012b9c1b51eSKate Stone           m_sect_headers[idx]
1013b9c1b51eSKate Stone               .size, // Size in bytes of this section as found in the file
101448672afbSGreg Clayton           m_coff_header_opt.sect_alignment, // Section alignment
1015f754f88fSGreg Clayton           m_sect_headers[idx].flags));      // Flags for this section
1016f754f88fSGreg Clayton 
1017f1e0ae34SPavel Labath       uint32_t permissions = 0;
1018f1e0ae34SPavel Labath       if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_EXECUTE)
1019f1e0ae34SPavel Labath         permissions |= ePermissionsExecutable;
1020f1e0ae34SPavel Labath       if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_READ)
1021f1e0ae34SPavel Labath         permissions |= ePermissionsReadable;
1022f1e0ae34SPavel Labath       if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_WRITE)
1023f1e0ae34SPavel Labath         permissions |= ePermissionsWritable;
1024f1e0ae34SPavel Labath       section_sp->SetPermissions(permissions);
1025f1e0ae34SPavel Labath 
102673a7a55cSPavel Labath       m_sections_up->AddSection(section_sp);
102773a7a55cSPavel Labath       unified_section_list.AddSection(section_sp);
1028f754f88fSGreg Clayton     }
1029f754f88fSGreg Clayton   }
1030a1743499SGreg Clayton }
1031f754f88fSGreg Clayton 
GetUUID()1032b8d03935SAaron Smith UUID ObjectFilePECOFF::GetUUID() {
1033b8d03935SAaron Smith   if (m_uuid.IsValid())
1034b8d03935SAaron Smith     return m_uuid;
1035b8d03935SAaron Smith 
1036b8d03935SAaron Smith   if (!CreateBinary())
1037b8d03935SAaron Smith     return UUID();
1038b8d03935SAaron Smith 
1039d372a8e8SPavel Labath   m_uuid = GetCoffUUID(*m_binary);
1040b8d03935SAaron Smith   return m_uuid;
1041b8d03935SAaron Smith }
1042f754f88fSGreg Clayton 
GetDebugLink()1043c8daf4a7SAlvin Wong llvm::Optional<FileSpec> ObjectFilePECOFF::GetDebugLink() {
1044c8daf4a7SAlvin Wong   std::string gnu_debuglink_file;
1045c8daf4a7SAlvin Wong   uint32_t gnu_debuglink_crc;
1046c8daf4a7SAlvin Wong   if (GetDebugLinkContents(*m_binary, gnu_debuglink_file, gnu_debuglink_crc))
1047c8daf4a7SAlvin Wong     return FileSpec(gnu_debuglink_file);
1048c8daf4a7SAlvin Wong   return llvm::None;
1049c8daf4a7SAlvin Wong }
1050c8daf4a7SAlvin Wong 
ParseDependentModules()1051037ed1beSAaron Smith uint32_t ObjectFilePECOFF::ParseDependentModules() {
1052037ed1beSAaron Smith   ModuleSP module_sp(GetModule());
1053037ed1beSAaron Smith   if (!module_sp)
1054f754f88fSGreg Clayton     return 0;
1055037ed1beSAaron Smith 
1056037ed1beSAaron Smith   std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1057037ed1beSAaron Smith   if (m_deps_filespec)
1058037ed1beSAaron Smith     return m_deps_filespec->GetSize();
1059037ed1beSAaron Smith 
1060037ed1beSAaron Smith   // Cache coff binary if it is not done yet.
1061037ed1beSAaron Smith   if (!CreateBinary())
1062037ed1beSAaron Smith     return 0;
1063037ed1beSAaron Smith 
1064a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Object);
1065d372a8e8SPavel Labath   LLDB_LOG(log, "this = {0}, module = {1} ({2}), file = {3}, binary = {4}",
1066d372a8e8SPavel Labath            this, GetModule().get(), GetModule()->GetSpecificationDescription(),
1067d372a8e8SPavel Labath            m_file.GetPath(), m_binary.get());
1068037ed1beSAaron Smith 
1069037ed1beSAaron Smith   m_deps_filespec = FileSpecList();
1070037ed1beSAaron Smith 
1071d372a8e8SPavel Labath   for (const auto &entry : m_binary->import_directories()) {
1072037ed1beSAaron Smith     llvm::StringRef dll_name;
1073037ed1beSAaron Smith     // Report a bogus entry.
10741c03389cSReid Kleckner     if (llvm::Error e = entry.getName(dll_name)) {
107563e5fb76SJonas Devlieghere       LLDB_LOGF(log,
107663e5fb76SJonas Devlieghere                 "ObjectFilePECOFF::ParseDependentModules() - failed to get "
1077037ed1beSAaron Smith                 "import directory entry name: %s",
10781c03389cSReid Kleckner                 llvm::toString(std::move(e)).c_str());
1079037ed1beSAaron Smith       continue;
1080037ed1beSAaron Smith     }
1081037ed1beSAaron Smith 
1082037ed1beSAaron Smith     // At this moment we only have the base name of the DLL. The full path can
1083037ed1beSAaron Smith     // only be seen after the dynamic loading.  Our best guess is Try to get it
1084037ed1beSAaron Smith     // with the help of the object file's directory.
1085b3f44ad9SStella Stamenova     llvm::SmallString<128> dll_fullpath;
1086037ed1beSAaron Smith     FileSpec dll_specs(dll_name);
1087*1b4b12a3SNico Weber     dll_specs.GetDirectory().SetString(m_file.GetDirectory().GetCString());
1088037ed1beSAaron Smith 
1089037ed1beSAaron Smith     if (!llvm::sys::fs::real_path(dll_specs.GetPath(), dll_fullpath))
1090f893d5bfSJonas Devlieghere       m_deps_filespec->EmplaceBack(dll_fullpath);
1091037ed1beSAaron Smith     else {
1092037ed1beSAaron Smith       // Known DLLs or DLL not found in the object file directory.
1093f893d5bfSJonas Devlieghere       m_deps_filespec->EmplaceBack(dll_name);
1094037ed1beSAaron Smith     }
1095037ed1beSAaron Smith   }
1096037ed1beSAaron Smith   return m_deps_filespec->GetSize();
1097037ed1beSAaron Smith }
1098037ed1beSAaron Smith 
GetDependentModules(FileSpecList & files)1099037ed1beSAaron Smith uint32_t ObjectFilePECOFF::GetDependentModules(FileSpecList &files) {
1100037ed1beSAaron Smith   auto num_modules = ParseDependentModules();
1101037ed1beSAaron Smith   auto original_size = files.GetSize();
1102037ed1beSAaron Smith 
1103037ed1beSAaron Smith   for (unsigned i = 0; i < num_modules; ++i)
1104037ed1beSAaron Smith     files.AppendIfUnique(m_deps_filespec->GetFileSpecAtIndex(i));
1105037ed1beSAaron Smith 
1106037ed1beSAaron Smith   return files.GetSize() - original_size;
1107f754f88fSGreg Clayton }
1108f754f88fSGreg Clayton 
GetEntryPointAddress()1109b9c1b51eSKate Stone lldb_private::Address ObjectFilePECOFF::GetEntryPointAddress() {
11108e38c666SStephane Sezer   if (m_entry_point_address.IsValid())
11118e38c666SStephane Sezer     return m_entry_point_address;
11128e38c666SStephane Sezer 
11138e38c666SStephane Sezer   if (!ParseHeader() || !IsExecutable())
11148e38c666SStephane Sezer     return m_entry_point_address;
11158e38c666SStephane Sezer 
11168e38c666SStephane Sezer   SectionList *section_list = GetSectionList();
1117a5235af9SAleksandr Urakov   addr_t file_addr = m_coff_header_opt.entry + m_coff_header_opt.image_base;
11188e38c666SStephane Sezer 
11198e38c666SStephane Sezer   if (!section_list)
1120a5235af9SAleksandr Urakov     m_entry_point_address.SetOffset(file_addr);
11218e38c666SStephane Sezer   else
1122b8d03935SAaron Smith     m_entry_point_address.ResolveAddressUsingFileSections(file_addr,
1123b8d03935SAaron Smith                                                           section_list);
11248e38c666SStephane Sezer   return m_entry_point_address;
11258e38c666SStephane Sezer }
11268e38c666SStephane Sezer 
GetBaseAddress()1127d1304bbaSPavel Labath Address ObjectFilePECOFF::GetBaseAddress() {
1128d1304bbaSPavel Labath   return Address(GetSectionList()->GetSectionAtIndex(0), 0);
1129d1304bbaSPavel Labath }
1130d1304bbaSPavel Labath 
1131f754f88fSGreg Clayton // Dump
1132f754f88fSGreg Clayton //
1133f754f88fSGreg Clayton // Dump the specifics of the runtime file container (such as any headers
1134f754f88fSGreg Clayton // segments, sections, etc).
Dump(Stream * s)1135b9c1b51eSKate Stone void ObjectFilePECOFF::Dump(Stream *s) {
1136a1743499SGreg Clayton   ModuleSP module_sp(GetModule());
1137b9c1b51eSKate Stone   if (module_sp) {
113816ff8604SSaleem Abdulrasool     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1139324a1036SSaleem Abdulrasool     s->Printf("%p: ", static_cast<void *>(this));
1140f754f88fSGreg Clayton     s->Indent();
1141f754f88fSGreg Clayton     s->PutCString("ObjectFilePECOFF");
1142f754f88fSGreg Clayton 
1143f760f5aeSPavel Labath     ArchSpec header_arch = GetArchitecture();
1144f754f88fSGreg Clayton 
1145b9c1b51eSKate Stone     *s << ", file = '" << m_file
1146b9c1b51eSKate Stone        << "', arch = " << header_arch.GetArchitectureName() << "\n";
1147f754f88fSGreg Clayton 
11483046e668SGreg Clayton     SectionList *sections = GetSectionList();
11493046e668SGreg Clayton     if (sections)
11503a168297SPavel Labath       sections->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true,
11513a168297SPavel Labath                      UINT32_MAX);
1152f754f88fSGreg Clayton 
1153d5b44036SJonas Devlieghere     if (m_symtab_up)
1154248a1305SKonrad Kleine       m_symtab_up->Dump(s, nullptr, eSortOrderNone);
1155f754f88fSGreg Clayton 
1156f754f88fSGreg Clayton     if (m_dos_header.e_magic)
1157f754f88fSGreg Clayton       DumpDOSHeader(s, m_dos_header);
1158b9c1b51eSKate Stone     if (m_coff_header.machine) {
1159f754f88fSGreg Clayton       DumpCOFFHeader(s, m_coff_header);
1160f754f88fSGreg Clayton       if (m_coff_header.hdrsize)
1161f754f88fSGreg Clayton         DumpOptCOFFHeader(s, m_coff_header_opt);
1162f754f88fSGreg Clayton     }
1163f754f88fSGreg Clayton     s->EOL();
1164f754f88fSGreg Clayton     DumpSectionHeaders(s);
1165f754f88fSGreg Clayton     s->EOL();
1166037ed1beSAaron Smith 
1167037ed1beSAaron Smith     DumpDependentModules(s);
1168037ed1beSAaron Smith     s->EOL();
1169f754f88fSGreg Clayton   }
1170a1743499SGreg Clayton }
1171f754f88fSGreg Clayton 
1172f754f88fSGreg Clayton // DumpDOSHeader
1173f754f88fSGreg Clayton //
1174f754f88fSGreg Clayton // Dump the MS-DOS header to the specified output stream
DumpDOSHeader(Stream * s,const dos_header_t & header)1175b9c1b51eSKate Stone void ObjectFilePECOFF::DumpDOSHeader(Stream *s, const dos_header_t &header) {
1176f754f88fSGreg Clayton   s->PutCString("MSDOS Header\n");
1177f754f88fSGreg Clayton   s->Printf("  e_magic    = 0x%4.4x\n", header.e_magic);
1178f754f88fSGreg Clayton   s->Printf("  e_cblp     = 0x%4.4x\n", header.e_cblp);
1179f754f88fSGreg Clayton   s->Printf("  e_cp       = 0x%4.4x\n", header.e_cp);
1180f754f88fSGreg Clayton   s->Printf("  e_crlc     = 0x%4.4x\n", header.e_crlc);
1181f754f88fSGreg Clayton   s->Printf("  e_cparhdr  = 0x%4.4x\n", header.e_cparhdr);
1182f754f88fSGreg Clayton   s->Printf("  e_minalloc = 0x%4.4x\n", header.e_minalloc);
1183f754f88fSGreg Clayton   s->Printf("  e_maxalloc = 0x%4.4x\n", header.e_maxalloc);
1184f754f88fSGreg Clayton   s->Printf("  e_ss       = 0x%4.4x\n", header.e_ss);
1185f754f88fSGreg Clayton   s->Printf("  e_sp       = 0x%4.4x\n", header.e_sp);
1186f754f88fSGreg Clayton   s->Printf("  e_csum     = 0x%4.4x\n", header.e_csum);
1187f754f88fSGreg Clayton   s->Printf("  e_ip       = 0x%4.4x\n", header.e_ip);
1188f754f88fSGreg Clayton   s->Printf("  e_cs       = 0x%4.4x\n", header.e_cs);
1189f754f88fSGreg Clayton   s->Printf("  e_lfarlc   = 0x%4.4x\n", header.e_lfarlc);
1190f754f88fSGreg Clayton   s->Printf("  e_ovno     = 0x%4.4x\n", header.e_ovno);
1191f754f88fSGreg Clayton   s->Printf("  e_res[4]   = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
1192b9c1b51eSKate Stone             header.e_res[0], header.e_res[1], header.e_res[2], header.e_res[3]);
1193f754f88fSGreg Clayton   s->Printf("  e_oemid    = 0x%4.4x\n", header.e_oemid);
1194f754f88fSGreg Clayton   s->Printf("  e_oeminfo  = 0x%4.4x\n", header.e_oeminfo);
1195b9c1b51eSKate Stone   s->Printf("  e_res2[10] = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, "
1196b9c1b51eSKate Stone             "0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
1197b9c1b51eSKate Stone             header.e_res2[0], header.e_res2[1], header.e_res2[2],
1198b9c1b51eSKate Stone             header.e_res2[3], header.e_res2[4], header.e_res2[5],
1199b9c1b51eSKate Stone             header.e_res2[6], header.e_res2[7], header.e_res2[8],
1200f754f88fSGreg Clayton             header.e_res2[9]);
1201f754f88fSGreg Clayton   s->Printf("  e_lfanew   = 0x%8.8x\n", header.e_lfanew);
1202f754f88fSGreg Clayton }
1203f754f88fSGreg Clayton 
1204f754f88fSGreg Clayton // DumpCOFFHeader
1205f754f88fSGreg Clayton //
1206f754f88fSGreg Clayton // Dump the COFF header to the specified output stream
DumpCOFFHeader(Stream * s,const coff_header_t & header)1207b9c1b51eSKate Stone void ObjectFilePECOFF::DumpCOFFHeader(Stream *s, const coff_header_t &header) {
1208f754f88fSGreg Clayton   s->PutCString("COFF Header\n");
1209f754f88fSGreg Clayton   s->Printf("  machine = 0x%4.4x\n", header.machine);
1210f754f88fSGreg Clayton   s->Printf("  nsects  = 0x%4.4x\n", header.nsects);
1211f754f88fSGreg Clayton   s->Printf("  modtime = 0x%8.8x\n", header.modtime);
1212f754f88fSGreg Clayton   s->Printf("  symoff  = 0x%8.8x\n", header.symoff);
1213f754f88fSGreg Clayton   s->Printf("  nsyms   = 0x%8.8x\n", header.nsyms);
1214f754f88fSGreg Clayton   s->Printf("  hdrsize = 0x%4.4x\n", header.hdrsize);
1215f754f88fSGreg Clayton }
1216f754f88fSGreg Clayton 
1217f754f88fSGreg Clayton // DumpOptCOFFHeader
1218f754f88fSGreg Clayton //
1219f754f88fSGreg Clayton // Dump the optional COFF header to the specified output stream
DumpOptCOFFHeader(Stream * s,const coff_opt_header_t & header)1220b9c1b51eSKate Stone void ObjectFilePECOFF::DumpOptCOFFHeader(Stream *s,
1221b9c1b51eSKate Stone                                          const coff_opt_header_t &header) {
1222f754f88fSGreg Clayton   s->PutCString("Optional COFF Header\n");
1223f754f88fSGreg Clayton   s->Printf("  magic                   = 0x%4.4x\n", header.magic);
1224b9c1b51eSKate Stone   s->Printf("  major_linker_version    = 0x%2.2x\n",
1225b9c1b51eSKate Stone             header.major_linker_version);
1226b9c1b51eSKate Stone   s->Printf("  minor_linker_version    = 0x%2.2x\n",
1227b9c1b51eSKate Stone             header.minor_linker_version);
1228f754f88fSGreg Clayton   s->Printf("  code_size               = 0x%8.8x\n", header.code_size);
1229f754f88fSGreg Clayton   s->Printf("  data_size               = 0x%8.8x\n", header.data_size);
1230f754f88fSGreg Clayton   s->Printf("  bss_size                = 0x%8.8x\n", header.bss_size);
1231f754f88fSGreg Clayton   s->Printf("  entry                   = 0x%8.8x\n", header.entry);
1232f754f88fSGreg Clayton   s->Printf("  code_offset             = 0x%8.8x\n", header.code_offset);
1233f754f88fSGreg Clayton   s->Printf("  data_offset             = 0x%8.8x\n", header.data_offset);
1234b9c1b51eSKate Stone   s->Printf("  image_base              = 0x%16.16" PRIx64 "\n",
1235b9c1b51eSKate Stone             header.image_base);
1236f754f88fSGreg Clayton   s->Printf("  sect_alignment          = 0x%8.8x\n", header.sect_alignment);
1237f754f88fSGreg Clayton   s->Printf("  file_alignment          = 0x%8.8x\n", header.file_alignment);
1238b9c1b51eSKate Stone   s->Printf("  major_os_system_version = 0x%4.4x\n",
1239b9c1b51eSKate Stone             header.major_os_system_version);
1240b9c1b51eSKate Stone   s->Printf("  minor_os_system_version = 0x%4.4x\n",
1241b9c1b51eSKate Stone             header.minor_os_system_version);
1242b9c1b51eSKate Stone   s->Printf("  major_image_version     = 0x%4.4x\n",
1243b9c1b51eSKate Stone             header.major_image_version);
1244b9c1b51eSKate Stone   s->Printf("  minor_image_version     = 0x%4.4x\n",
1245b9c1b51eSKate Stone             header.minor_image_version);
1246b9c1b51eSKate Stone   s->Printf("  major_subsystem_version = 0x%4.4x\n",
1247b9c1b51eSKate Stone             header.major_subsystem_version);
1248b9c1b51eSKate Stone   s->Printf("  minor_subsystem_version = 0x%4.4x\n",
1249b9c1b51eSKate Stone             header.minor_subsystem_version);
1250f754f88fSGreg Clayton   s->Printf("  reserved1               = 0x%8.8x\n", header.reserved1);
1251f754f88fSGreg Clayton   s->Printf("  image_size              = 0x%8.8x\n", header.image_size);
1252f754f88fSGreg Clayton   s->Printf("  header_size             = 0x%8.8x\n", header.header_size);
125328469ca3SGreg Clayton   s->Printf("  checksum                = 0x%8.8x\n", header.checksum);
1254f754f88fSGreg Clayton   s->Printf("  subsystem               = 0x%4.4x\n", header.subsystem);
1255f754f88fSGreg Clayton   s->Printf("  dll_flags               = 0x%4.4x\n", header.dll_flags);
1256b9c1b51eSKate Stone   s->Printf("  stack_reserve_size      = 0x%16.16" PRIx64 "\n",
1257b9c1b51eSKate Stone             header.stack_reserve_size);
1258b9c1b51eSKate Stone   s->Printf("  stack_commit_size       = 0x%16.16" PRIx64 "\n",
1259b9c1b51eSKate Stone             header.stack_commit_size);
1260b9c1b51eSKate Stone   s->Printf("  heap_reserve_size       = 0x%16.16" PRIx64 "\n",
1261b9c1b51eSKate Stone             header.heap_reserve_size);
1262b9c1b51eSKate Stone   s->Printf("  heap_commit_size        = 0x%16.16" PRIx64 "\n",
1263b9c1b51eSKate Stone             header.heap_commit_size);
1264f754f88fSGreg Clayton   s->Printf("  loader_flags            = 0x%8.8x\n", header.loader_flags);
1265b9c1b51eSKate Stone   s->Printf("  num_data_dir_entries    = 0x%8.8x\n",
1266b9c1b51eSKate Stone             (uint32_t)header.data_dirs.size());
1267f754f88fSGreg Clayton   uint32_t i;
1268b9c1b51eSKate Stone   for (i = 0; i < header.data_dirs.size(); i++) {
1269b9c1b51eSKate Stone     s->Printf("  data_dirs[%2u] vmaddr = 0x%8.8x, vmsize = 0x%8.8x\n", i,
1270b9c1b51eSKate Stone               header.data_dirs[i].vmaddr, header.data_dirs[i].vmsize);
1271f754f88fSGreg Clayton   }
1272f754f88fSGreg Clayton }
1273f754f88fSGreg Clayton // DumpSectionHeader
1274f754f88fSGreg Clayton //
1275f754f88fSGreg Clayton // Dump a single ELF section header to the specified output stream
DumpSectionHeader(Stream * s,const section_header_t & sh)1276b9c1b51eSKate Stone void ObjectFilePECOFF::DumpSectionHeader(Stream *s,
1277b9c1b51eSKate Stone                                          const section_header_t &sh) {
1278adcd0268SBenjamin Kramer   std::string name = std::string(GetSectionName(sh));
1279b9c1b51eSKate 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 "
1280b9c1b51eSKate Stone             "0x%4.4x 0x%8.8x\n",
1281b9c1b51eSKate Stone             name.c_str(), sh.vmaddr, sh.vmsize, sh.offset, sh.size, sh.reloff,
1282b9c1b51eSKate Stone             sh.lineoff, sh.nreloc, sh.nline, sh.flags);
1283f754f88fSGreg Clayton }
1284f754f88fSGreg Clayton 
1285f754f88fSGreg Clayton // DumpSectionHeaders
1286f754f88fSGreg Clayton //
1287f754f88fSGreg Clayton // Dump all of the ELF section header to the specified output stream
DumpSectionHeaders(Stream * s)1288b9c1b51eSKate Stone void ObjectFilePECOFF::DumpSectionHeaders(Stream *s) {
1289f754f88fSGreg Clayton 
1290f754f88fSGreg Clayton   s->PutCString("Section Headers\n");
1291b9c1b51eSKate Stone   s->PutCString("IDX  name             vm addr    vm size    file off   file "
1292b9c1b51eSKate Stone                 "size  reloc off  line off   nreloc nline  flags\n");
1293b9c1b51eSKate Stone   s->PutCString("==== ---------------- ---------- ---------- ---------- "
1294b9c1b51eSKate Stone                 "---------- ---------- ---------- ------ ------ ----------\n");
1295f754f88fSGreg Clayton 
1296f754f88fSGreg Clayton   uint32_t idx = 0;
1297f754f88fSGreg Clayton   SectionHeaderCollIter pos, end = m_sect_headers.end();
1298f754f88fSGreg Clayton 
1299b9c1b51eSKate Stone   for (pos = m_sect_headers.begin(); pos != end; ++pos, ++idx) {
1300f754f88fSGreg Clayton     s->Printf("[%2u] ", idx);
1301f754f88fSGreg Clayton     ObjectFilePECOFF::DumpSectionHeader(s, *pos);
1302f754f88fSGreg Clayton   }
1303f754f88fSGreg Clayton }
1304f754f88fSGreg Clayton 
1305037ed1beSAaron Smith // DumpDependentModules
1306037ed1beSAaron Smith //
1307037ed1beSAaron Smith // Dump all of the dependent modules to the specified output stream
DumpDependentModules(lldb_private::Stream * s)1308037ed1beSAaron Smith void ObjectFilePECOFF::DumpDependentModules(lldb_private::Stream *s) {
1309037ed1beSAaron Smith   auto num_modules = ParseDependentModules();
1310037ed1beSAaron Smith   if (num_modules > 0) {
1311037ed1beSAaron Smith     s->PutCString("Dependent Modules\n");
1312037ed1beSAaron Smith     for (unsigned i = 0; i < num_modules; ++i) {
1313037ed1beSAaron Smith       auto spec = m_deps_filespec->GetFileSpecAtIndex(i);
1314037ed1beSAaron Smith       s->Printf("  %s\n", spec.GetFilename().GetCString());
1315037ed1beSAaron Smith     }
1316037ed1beSAaron Smith   }
1317037ed1beSAaron Smith }
1318037ed1beSAaron Smith 
IsWindowsSubsystem()1319fb3b3bd1SZachary Turner bool ObjectFilePECOFF::IsWindowsSubsystem() {
1320fb3b3bd1SZachary Turner   switch (m_coff_header_opt.subsystem) {
1321fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE:
1322fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI:
1323fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI:
1324fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE_WINDOWS:
1325fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
1326fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_XBOX:
1327fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION:
1328fb3b3bd1SZachary Turner     return true;
1329fb3b3bd1SZachary Turner   default:
1330fb3b3bd1SZachary Turner     return false;
1331fb3b3bd1SZachary Turner   }
1332fb3b3bd1SZachary Turner }
1333fb3b3bd1SZachary Turner 
GetArchitecture()1334f760f5aeSPavel Labath ArchSpec ObjectFilePECOFF::GetArchitecture() {
1335237ad974SCharles Davis   uint16_t machine = m_coff_header.machine;
1336b9c1b51eSKate Stone   switch (machine) {
1337f760f5aeSPavel Labath   default:
1338f760f5aeSPavel Labath     break;
1339237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_AMD64:
1340237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_I386:
1341237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_POWERPC:
1342237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_POWERPCFP:
1343237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_ARM:
13441108cb36SSaleem Abdulrasool   case llvm::COFF::IMAGE_FILE_MACHINE_ARMNT:
1345237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_THUMB:
1346638f072fSMartin Storsjo   case llvm::COFF::IMAGE_FILE_MACHINE_ARM64:
1347f760f5aeSPavel Labath     ArchSpec arch;
1348fb3b3bd1SZachary Turner     arch.SetArchitecture(eArchTypeCOFF, machine, LLDB_INVALID_CPUTYPE,
1349fb3b3bd1SZachary Turner                          IsWindowsSubsystem() ? llvm::Triple::Win32
1350fb3b3bd1SZachary Turner                                               : llvm::Triple::UnknownOS);
1351f760f5aeSPavel Labath     return arch;
1352237ad974SCharles Davis   }
1353f760f5aeSPavel Labath   return ArchSpec();
1354f754f88fSGreg Clayton }
1355f754f88fSGreg Clayton 
CalculateType()1356b9c1b51eSKate Stone ObjectFile::Type ObjectFilePECOFF::CalculateType() {
1357b9c1b51eSKate Stone   if (m_coff_header.machine != 0) {
1358237ad974SCharles Davis     if ((m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0)
1359f754f88fSGreg Clayton       return eTypeExecutable;
1360f754f88fSGreg Clayton     else
1361f754f88fSGreg Clayton       return eTypeSharedLibrary;
1362f754f88fSGreg Clayton   }
1363f754f88fSGreg Clayton   return eTypeExecutable;
1364f754f88fSGreg Clayton }
1365f754f88fSGreg Clayton 
CalculateStrata()1366b9c1b51eSKate Stone ObjectFile::Strata ObjectFilePECOFF::CalculateStrata() { return eStrataUser; }
1367