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"
19f754f88fSGreg Clayton #include "lldb/Symbol/ObjectFile.h"
20f7d1893fSAdrian McCarthy #include "lldb/Target/Process.h"
212756adf3SVirgile Bello #include "lldb/Target/SectionLoadList.h"
222756adf3SVirgile Bello #include "lldb/Target/Target.h"
235f19b907SPavel Labath #include "lldb/Utility/ArchSpec.h"
24666cc0b2SZachary Turner #include "lldb/Utility/DataBufferHeap.h"
255713a05bSZachary Turner #include "lldb/Utility/FileSpec.h"
26c34698a8SPavel Labath #include "lldb/Utility/LLDBLog.h"
27037ed1beSAaron Smith #include "lldb/Utility/Log.h"
28bf9a7730SZachary Turner #include "lldb/Utility/StreamString.h"
2938d0632eSPavel Labath #include "lldb/Utility/Timer.h"
30666cc0b2SZachary Turner #include "lldb/Utility/UUID.h"
315f19b907SPavel Labath #include "llvm/BinaryFormat/COFF.h"
32f754f88fSGreg Clayton 
33037ed1beSAaron Smith #include "llvm/Object/COFFImportFile.h"
34037ed1beSAaron Smith #include "llvm/Support/Error.h"
353f4a4b36SZachary Turner #include "llvm/Support/MemoryBuffer.h"
363f4a4b36SZachary Turner 
37f754f88fSGreg Clayton #define IMAGE_DOS_SIGNATURE 0x5A4D    // MZ
38f754f88fSGreg Clayton #define IMAGE_NT_SIGNATURE 0x00004550 // PE00
39f754f88fSGreg Clayton #define OPT_HEADER_MAGIC_PE32 0x010b
40f754f88fSGreg Clayton #define OPT_HEADER_MAGIC_PE32_PLUS 0x020b
41f754f88fSGreg Clayton 
42f754f88fSGreg Clayton using namespace lldb;
43f754f88fSGreg Clayton using namespace lldb_private;
44f754f88fSGreg Clayton 
45bba9ba8dSJonas Devlieghere LLDB_PLUGIN_DEFINE(ObjectFilePECOFF)
46fbb4d1e4SJonas Devlieghere 
47d372a8e8SPavel Labath static UUID GetCoffUUID(llvm::object::COFFObjectFile &coff_obj) {
48b8d03935SAaron Smith   const llvm::codeview::DebugInfo *pdb_info = nullptr;
49b8d03935SAaron Smith   llvm::StringRef pdb_file;
50b8d03935SAaron Smith 
51d372a8e8SPavel Labath   if (!coff_obj.getDebugPDBInfo(pdb_info, pdb_file) && pdb_info) {
52b8d03935SAaron Smith     if (pdb_info->PDB70.CVSignature == llvm::OMF::Signature::PDB70) {
534348e0eeSZequan Wu       UUID::CvRecordPdb70 info;
544348e0eeSZequan Wu       memcpy(&info.Uuid, pdb_info->PDB70.Signature, sizeof(info.Uuid));
554348e0eeSZequan Wu       info.Age = pdb_info->PDB70.Age;
564348e0eeSZequan Wu       return UUID::fromCvRecord(info);
57b8d03935SAaron Smith     }
58b8d03935SAaron Smith   }
59b8d03935SAaron Smith 
60b8d03935SAaron Smith   return UUID();
61b8d03935SAaron Smith }
62b8d03935SAaron Smith 
63e84f7841SPavel Labath char ObjectFilePECOFF::ID;
64e84f7841SPavel Labath 
65b9c1b51eSKate Stone void ObjectFilePECOFF::Initialize() {
66b9c1b51eSKate Stone   PluginManager::RegisterPlugin(
67b9c1b51eSKate Stone       GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance,
68b9c1b51eSKate Stone       CreateMemoryInstance, GetModuleSpecifications, SaveCore);
69f754f88fSGreg Clayton }
70f754f88fSGreg Clayton 
71b9c1b51eSKate Stone void ObjectFilePECOFF::Terminate() {
72f754f88fSGreg Clayton   PluginManager::UnregisterPlugin(CreateInstance);
73f754f88fSGreg Clayton }
74f754f88fSGreg Clayton 
752ace1e57SPavel Labath llvm::StringRef ObjectFilePECOFF::GetPluginDescriptionStatic() {
76b9c1b51eSKate Stone   return "Portable Executable and Common Object File Format object file reader "
77b9c1b51eSKate Stone          "(32 and 64 bit)";
78f754f88fSGreg Clayton }
79f754f88fSGreg Clayton 
80c69307e5SJonas Devlieghere ObjectFile *ObjectFilePECOFF::CreateInstance(
81c69307e5SJonas Devlieghere     const lldb::ModuleSP &module_sp, DataBufferSP data_sp,
82c69307e5SJonas Devlieghere     lldb::offset_t data_offset, const lldb_private::FileSpec *file_p,
83c69307e5SJonas Devlieghere     lldb::offset_t file_offset, lldb::offset_t length) {
8428e4942bSPavel Labath   FileSpec file = file_p ? *file_p : FileSpec();
85b9c1b51eSKate Stone   if (!data_sp) {
8650251fc7SPavel Labath     data_sp = MapFileData(file, length, file_offset);
873f4a4b36SZachary Turner     if (!data_sp)
883f4a4b36SZachary Turner       return nullptr;
895ce9c565SGreg Clayton     data_offset = 0;
905ce9c565SGreg Clayton   }
915ce9c565SGreg Clayton 
923f4a4b36SZachary Turner   if (!ObjectFilePECOFF::MagicBytesMatch(data_sp))
933f4a4b36SZachary Turner     return nullptr;
943f4a4b36SZachary Turner 
955ce9c565SGreg Clayton   // Update the data to contain the entire file if it doesn't already
963f4a4b36SZachary Turner   if (data_sp->GetByteSize() < length) {
9750251fc7SPavel Labath     data_sp = MapFileData(file, length, file_offset);
983f4a4b36SZachary Turner     if (!data_sp)
993f4a4b36SZachary Turner       return nullptr;
100f754f88fSGreg Clayton   }
1013f4a4b36SZachary Turner 
102a8f3ae7cSJonas Devlieghere   auto objfile_up = std::make_unique<ObjectFilePECOFF>(
10328e4942bSPavel Labath       module_sp, data_sp, data_offset, file_p, file_offset, length);
104d5b44036SJonas Devlieghere   if (!objfile_up || !objfile_up->ParseHeader())
1053f4a4b36SZachary Turner     return nullptr;
1063f4a4b36SZachary Turner 
107037ed1beSAaron Smith   // Cache coff binary.
108d5b44036SJonas Devlieghere   if (!objfile_up->CreateBinary())
109037ed1beSAaron Smith     return nullptr;
110d5b44036SJonas Devlieghere   return objfile_up.release();
111f754f88fSGreg Clayton }
112f754f88fSGreg Clayton 
113b9c1b51eSKate Stone ObjectFile *ObjectFilePECOFF::CreateMemoryInstance(
114*f2ea125eSJonas Devlieghere     const lldb::ModuleSP &module_sp, lldb::WritableDataBufferSP data_sp,
115b9c1b51eSKate Stone     const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) {
116344546bdSWalter Erquinigo   if (!data_sp || !ObjectFilePECOFF::MagicBytesMatch(data_sp))
117344546bdSWalter Erquinigo     return nullptr;
118a8f3ae7cSJonas Devlieghere   auto objfile_up = std::make_unique<ObjectFilePECOFF>(
119344546bdSWalter Erquinigo       module_sp, data_sp, process_sp, header_addr);
120d5b44036SJonas Devlieghere   if (objfile_up.get() && objfile_up->ParseHeader()) {
121d5b44036SJonas Devlieghere     return objfile_up.release();
122344546bdSWalter Erquinigo   }
123344546bdSWalter Erquinigo   return nullptr;
124c9660546SGreg Clayton }
125c9660546SGreg Clayton 
126b9c1b51eSKate Stone size_t ObjectFilePECOFF::GetModuleSpecifications(
127b9c1b51eSKate Stone     const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
128b9c1b51eSKate Stone     lldb::offset_t data_offset, lldb::offset_t file_offset,
129b9c1b51eSKate Stone     lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
13089eb1baeSVirgile Bello   const size_t initial_count = specs.GetSize();
131b8d03935SAaron Smith   if (!data_sp || !ObjectFilePECOFF::MagicBytesMatch(data_sp))
132b8d03935SAaron Smith     return initial_count;
13389eb1baeSVirgile Bello 
134a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Object);
1353db1d138SMartin Storsjö 
136a4a00cedSFred Riss   if (data_sp->GetByteSize() < length)
137d372a8e8SPavel Labath     if (DataBufferSP full_sp = MapFileData(file, -1, file_offset))
138d372a8e8SPavel Labath       data_sp = std::move(full_sp);
139d372a8e8SPavel Labath   auto binary = llvm::object::createBinary(llvm::MemoryBufferRef(
140d372a8e8SPavel Labath       toStringRef(data_sp->GetData()), file.GetFilename().GetStringRef()));
1413db1d138SMartin Storsjö 
1423db1d138SMartin Storsjö   if (!binary) {
1433db1d138SMartin Storsjö     LLDB_LOG_ERROR(log, binary.takeError(),
1443db1d138SMartin Storsjö                    "Failed to create binary for file ({1}): {0}", file);
145b8d03935SAaron Smith     return initial_count;
1463db1d138SMartin Storsjö   }
14789eb1baeSVirgile Bello 
148d372a8e8SPavel Labath   auto *COFFObj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary->get());
149d372a8e8SPavel Labath   if (!COFFObj)
150b8d03935SAaron Smith     return initial_count;
15189eb1baeSVirgile Bello 
152b8d03935SAaron Smith   ModuleSpec module_spec(file);
153b8d03935SAaron Smith   ArchSpec &spec = module_spec.GetArchitecture();
154b8d03935SAaron Smith   lldb_private::UUID &uuid = module_spec.GetUUID();
155b8d03935SAaron Smith   if (!uuid.IsValid())
156d372a8e8SPavel Labath     uuid = GetCoffUUID(*COFFObj);
157b8d03935SAaron Smith 
158b8d03935SAaron Smith   switch (COFFObj->getMachine()) {
159b8d03935SAaron Smith   case MachineAmd64:
160ad587ae4SZachary Turner     spec.SetTriple("x86_64-pc-windows");
161b8d03935SAaron Smith     specs.Append(module_spec);
162b8d03935SAaron Smith     break;
163b8d03935SAaron Smith   case MachineX86:
164ad587ae4SZachary Turner     spec.SetTriple("i386-pc-windows");
165b8d03935SAaron Smith     specs.Append(module_spec);
1665e6f4520SZachary Turner     spec.SetTriple("i686-pc-windows");
167b8d03935SAaron Smith     specs.Append(module_spec);
168b8d03935SAaron Smith     break;
169b8d03935SAaron Smith   case MachineArmNt:
170544c8f48SMartin Storsjo     spec.SetTriple("armv7-pc-windows");
171b8d03935SAaron Smith     specs.Append(module_spec);
172b8d03935SAaron Smith     break;
173638f072fSMartin Storsjo   case MachineArm64:
174674d5543SMartin Storsjo     spec.SetTriple("aarch64-pc-windows");
175638f072fSMartin Storsjo     specs.Append(module_spec);
176638f072fSMartin Storsjo     break;
177b8d03935SAaron Smith   default:
178b8d03935SAaron Smith     break;
17989eb1baeSVirgile Bello   }
18089eb1baeSVirgile Bello 
18189eb1baeSVirgile Bello   return specs.GetSize() - initial_count;
182f4d6de6aSGreg Clayton }
183f4d6de6aSGreg Clayton 
184b9c1b51eSKate Stone bool ObjectFilePECOFF::SaveCore(const lldb::ProcessSP &process_sp,
185f7d1893fSAdrian McCarthy                                 const lldb_private::FileSpec &outfile,
1869ea6dd5cSJason Molenda                                 lldb::SaveCoreStyle &core_style,
18797206d57SZachary Turner                                 lldb_private::Status &error) {
1889ea6dd5cSJason Molenda   core_style = eSaveCoreFull;
189f7d1893fSAdrian McCarthy   return SaveMiniDump(process_sp, outfile, error);
190f7d1893fSAdrian McCarthy }
191f7d1893fSAdrian McCarthy 
192*f2ea125eSJonas Devlieghere bool ObjectFilePECOFF::MagicBytesMatch(DataBufferSP data_sp) {
1935ce9c565SGreg Clayton   DataExtractor data(data_sp, eByteOrderLittle, 4);
194c7bece56SGreg Clayton   lldb::offset_t offset = 0;
195f754f88fSGreg Clayton   uint16_t magic = data.GetU16(&offset);
196f754f88fSGreg Clayton   return magic == IMAGE_DOS_SIGNATURE;
197f754f88fSGreg Clayton }
198f754f88fSGreg Clayton 
199b9c1b51eSKate Stone lldb::SymbolType ObjectFilePECOFF::MapSymbolType(uint16_t coff_symbol_type) {
200c35b91ceSAdrian McCarthy   // TODO:  We need to complete this mapping of COFF symbol types to LLDB ones.
201c35b91ceSAdrian McCarthy   // For now, here's a hack to make sure our function have types.
202b9c1b51eSKate Stone   const auto complex_type =
203b9c1b51eSKate Stone       coff_symbol_type >> llvm::COFF::SCT_COMPLEX_TYPE_SHIFT;
204b9c1b51eSKate Stone   if (complex_type == llvm::COFF::IMAGE_SYM_DTYPE_FUNCTION) {
205c35b91ceSAdrian McCarthy     return lldb::eSymbolTypeCode;
206c35b91ceSAdrian McCarthy   }
207c35b91ceSAdrian McCarthy   return lldb::eSymbolTypeInvalid;
208c35b91ceSAdrian McCarthy }
209f754f88fSGreg Clayton 
210037ed1beSAaron Smith bool ObjectFilePECOFF::CreateBinary() {
211d372a8e8SPavel Labath   if (m_binary)
212037ed1beSAaron Smith     return true;
213037ed1beSAaron Smith 
214a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Object);
215037ed1beSAaron Smith 
216d372a8e8SPavel Labath   auto binary = llvm::object::createBinary(llvm::MemoryBufferRef(
217d372a8e8SPavel Labath       toStringRef(m_data.GetData()), m_file.GetFilename().GetStringRef()));
218037ed1beSAaron Smith   if (!binary) {
2193db1d138SMartin Storsjö     LLDB_LOG_ERROR(log, binary.takeError(),
2203db1d138SMartin Storsjö                    "Failed to create binary for file ({1}): {0}", m_file);
221037ed1beSAaron Smith     return false;
222037ed1beSAaron Smith   }
223037ed1beSAaron Smith 
224037ed1beSAaron Smith   // Make sure we only handle COFF format.
225d372a8e8SPavel Labath   m_binary =
226d372a8e8SPavel Labath       llvm::unique_dyn_cast<llvm::object::COFFObjectFile>(std::move(*binary));
227d372a8e8SPavel Labath   if (!m_binary)
228037ed1beSAaron Smith     return false;
229037ed1beSAaron Smith 
230d372a8e8SPavel Labath   LLDB_LOG(log, "this = {0}, module = {1} ({2}), file = {3}, binary = {4}",
231d372a8e8SPavel Labath            this, GetModule().get(), GetModule()->GetSpecificationDescription(),
232d372a8e8SPavel Labath            m_file.GetPath(), m_binary.get());
233037ed1beSAaron Smith   return true;
234037ed1beSAaron Smith }
235037ed1beSAaron Smith 
236e72dfb32SGreg Clayton ObjectFilePECOFF::ObjectFilePECOFF(const lldb::ModuleSP &module_sp,
237*f2ea125eSJonas Devlieghere                                    DataBufferSP data_sp,
2385ce9c565SGreg Clayton                                    lldb::offset_t data_offset,
239f754f88fSGreg Clayton                                    const FileSpec *file,
2405ce9c565SGreg Clayton                                    lldb::offset_t file_offset,
241b9c1b51eSKate Stone                                    lldb::offset_t length)
242b9c1b51eSKate Stone     : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
2435c43ffd6SPavel Labath       m_dos_header(), m_coff_header(), m_sect_headers(),
244d372a8e8SPavel Labath       m_entry_point_address(), m_deps_filespec() {
245f754f88fSGreg Clayton   ::memset(&m_dos_header, 0, sizeof(m_dos_header));
246f754f88fSGreg Clayton   ::memset(&m_coff_header, 0, sizeof(m_coff_header));
247f754f88fSGreg Clayton }
248f754f88fSGreg Clayton 
249344546bdSWalter Erquinigo ObjectFilePECOFF::ObjectFilePECOFF(const lldb::ModuleSP &module_sp,
250*f2ea125eSJonas Devlieghere                                    WritableDataBufferSP header_data_sp,
251344546bdSWalter Erquinigo                                    const lldb::ProcessSP &process_sp,
252344546bdSWalter Erquinigo                                    addr_t header_addr)
253344546bdSWalter Erquinigo     : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
2545c43ffd6SPavel Labath       m_dos_header(), m_coff_header(), m_sect_headers(),
255d372a8e8SPavel Labath       m_entry_point_address(), m_deps_filespec() {
256344546bdSWalter Erquinigo   ::memset(&m_dos_header, 0, sizeof(m_dos_header));
257344546bdSWalter Erquinigo   ::memset(&m_coff_header, 0, sizeof(m_coff_header));
258344546bdSWalter Erquinigo }
259344546bdSWalter Erquinigo 
260fd2433e1SJonas Devlieghere ObjectFilePECOFF::~ObjectFilePECOFF() = default;
261f754f88fSGreg Clayton 
262b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseHeader() {
263a1743499SGreg Clayton   ModuleSP module_sp(GetModule());
264b9c1b51eSKate Stone   if (module_sp) {
26516ff8604SSaleem Abdulrasool     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
266f754f88fSGreg Clayton     m_sect_headers.clear();
267f754f88fSGreg Clayton     m_data.SetByteOrder(eByteOrderLittle);
268c7bece56SGreg Clayton     lldb::offset_t offset = 0;
269f754f88fSGreg Clayton 
270b9c1b51eSKate Stone     if (ParseDOSHeader(m_data, m_dos_header)) {
271f754f88fSGreg Clayton       offset = m_dos_header.e_lfanew;
272f754f88fSGreg Clayton       uint32_t pe_signature = m_data.GetU32(&offset);
273f754f88fSGreg Clayton       if (pe_signature != IMAGE_NT_SIGNATURE)
274f754f88fSGreg Clayton         return false;
275b9c1b51eSKate Stone       if (ParseCOFFHeader(m_data, &offset, m_coff_header)) {
276f754f88fSGreg Clayton         if (m_coff_header.hdrsize > 0)
277f754f88fSGreg Clayton           ParseCOFFOptionalHeader(&offset);
278f754f88fSGreg Clayton         ParseSectionHeaders(offset);
27928469ca3SGreg Clayton       }
280a0f72441SMartin Storsjö       m_data.SetAddressByteSize(GetAddressByteSize());
281f754f88fSGreg Clayton       return true;
282f754f88fSGreg Clayton     }
283a1743499SGreg Clayton   }
284f754f88fSGreg Clayton   return false;
285f754f88fSGreg Clayton }
286f754f88fSGreg Clayton 
287b9c1b51eSKate Stone bool ObjectFilePECOFF::SetLoadAddress(Target &target, addr_t value,
288b9c1b51eSKate Stone                                       bool value_is_offset) {
2892756adf3SVirgile Bello   bool changed = false;
2902756adf3SVirgile Bello   ModuleSP module_sp = GetModule();
291b9c1b51eSKate Stone   if (module_sp) {
2922756adf3SVirgile Bello     size_t num_loaded_sections = 0;
2932756adf3SVirgile Bello     SectionList *section_list = GetSectionList();
294b9c1b51eSKate Stone     if (section_list) {
295b9c1b51eSKate Stone       if (!value_is_offset) {
2962756adf3SVirgile Bello         value -= m_image_base;
2972756adf3SVirgile Bello       }
2982756adf3SVirgile Bello 
2992756adf3SVirgile Bello       const size_t num_sections = section_list->GetSize();
3002756adf3SVirgile Bello       size_t sect_idx = 0;
3012756adf3SVirgile Bello 
302b9c1b51eSKate Stone       for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
30305097246SAdrian Prantl         // Iterate through the object file sections to find all of the sections
30405097246SAdrian Prantl         // that have SHF_ALLOC in their flag bits.
3052756adf3SVirgile Bello         SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
306b9c1b51eSKate Stone         if (section_sp && !section_sp->IsThreadSpecific()) {
307b9c1b51eSKate Stone           if (target.GetSectionLoadList().SetSectionLoadAddress(
308b9c1b51eSKate Stone                   section_sp, section_sp->GetFileAddress() + value))
3092756adf3SVirgile Bello             ++num_loaded_sections;
3102756adf3SVirgile Bello         }
3112756adf3SVirgile Bello       }
3122756adf3SVirgile Bello       changed = num_loaded_sections > 0;
3132756adf3SVirgile Bello     }
3142756adf3SVirgile Bello   }
3152756adf3SVirgile Bello   return changed;
3162756adf3SVirgile Bello }
3172756adf3SVirgile Bello 
318b9c1b51eSKate Stone ByteOrder ObjectFilePECOFF::GetByteOrder() const { return eByteOrderLittle; }
319f754f88fSGreg Clayton 
320b9c1b51eSKate Stone bool ObjectFilePECOFF::IsExecutable() const {
321237ad974SCharles Davis   return (m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0;
322f754f88fSGreg Clayton }
323f754f88fSGreg Clayton 
324b9c1b51eSKate Stone uint32_t ObjectFilePECOFF::GetAddressByteSize() const {
325f754f88fSGreg Clayton   if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32_PLUS)
326f754f88fSGreg Clayton     return 8;
327f754f88fSGreg Clayton   else if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32)
328f754f88fSGreg Clayton     return 4;
329f754f88fSGreg Clayton   return 4;
330f754f88fSGreg Clayton }
331f754f88fSGreg Clayton 
332f754f88fSGreg Clayton // NeedsEndianSwap
333f754f88fSGreg Clayton //
33405097246SAdrian Prantl // Return true if an endian swap needs to occur when extracting data from this
33505097246SAdrian Prantl // file.
336b9c1b51eSKate Stone bool ObjectFilePECOFF::NeedsEndianSwap() const {
337f754f88fSGreg Clayton #if defined(__LITTLE_ENDIAN__)
338f754f88fSGreg Clayton   return false;
339f754f88fSGreg Clayton #else
340f754f88fSGreg Clayton   return true;
341f754f88fSGreg Clayton #endif
342f754f88fSGreg Clayton }
343f754f88fSGreg Clayton // ParseDOSHeader
344b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseDOSHeader(DataExtractor &data,
345b9c1b51eSKate Stone                                       dos_header_t &dos_header) {
346f754f88fSGreg Clayton   bool success = false;
347c7bece56SGreg Clayton   lldb::offset_t offset = 0;
34889eb1baeSVirgile Bello   success = data.ValidOffsetForDataOfSize(0, sizeof(dos_header));
349f754f88fSGreg Clayton 
350b9c1b51eSKate Stone   if (success) {
35189eb1baeSVirgile Bello     dos_header.e_magic = data.GetU16(&offset); // Magic number
35289eb1baeSVirgile Bello     success = dos_header.e_magic == IMAGE_DOS_SIGNATURE;
353f754f88fSGreg Clayton 
354b9c1b51eSKate Stone     if (success) {
35589eb1baeSVirgile Bello       dos_header.e_cblp = data.GetU16(&offset); // Bytes on last page of file
35689eb1baeSVirgile Bello       dos_header.e_cp = data.GetU16(&offset);   // Pages in file
35789eb1baeSVirgile Bello       dos_header.e_crlc = data.GetU16(&offset); // Relocations
358b9c1b51eSKate Stone       dos_header.e_cparhdr =
359b9c1b51eSKate Stone           data.GetU16(&offset); // Size of header in paragraphs
360b9c1b51eSKate Stone       dos_header.e_minalloc =
361b9c1b51eSKate Stone           data.GetU16(&offset); // Minimum extra paragraphs needed
362b9c1b51eSKate Stone       dos_header.e_maxalloc =
363b9c1b51eSKate Stone           data.GetU16(&offset);               // Maximum extra paragraphs needed
36489eb1baeSVirgile Bello       dos_header.e_ss = data.GetU16(&offset); // Initial (relative) SS value
36589eb1baeSVirgile Bello       dos_header.e_sp = data.GetU16(&offset); // Initial SP value
36689eb1baeSVirgile Bello       dos_header.e_csum = data.GetU16(&offset); // Checksum
36789eb1baeSVirgile Bello       dos_header.e_ip = data.GetU16(&offset);   // Initial IP value
36889eb1baeSVirgile Bello       dos_header.e_cs = data.GetU16(&offset);   // Initial (relative) CS value
369b9c1b51eSKate Stone       dos_header.e_lfarlc =
370b9c1b51eSKate Stone           data.GetU16(&offset); // File address of relocation table
37189eb1baeSVirgile Bello       dos_header.e_ovno = data.GetU16(&offset); // Overlay number
372f754f88fSGreg Clayton 
37389eb1baeSVirgile Bello       dos_header.e_res[0] = data.GetU16(&offset); // Reserved words
37489eb1baeSVirgile Bello       dos_header.e_res[1] = data.GetU16(&offset); // Reserved words
37589eb1baeSVirgile Bello       dos_header.e_res[2] = data.GetU16(&offset); // Reserved words
37689eb1baeSVirgile Bello       dos_header.e_res[3] = data.GetU16(&offset); // Reserved words
377f754f88fSGreg Clayton 
378b9c1b51eSKate Stone       dos_header.e_oemid =
379b9c1b51eSKate Stone           data.GetU16(&offset); // OEM identifier (for e_oeminfo)
380b9c1b51eSKate Stone       dos_header.e_oeminfo =
381b9c1b51eSKate Stone           data.GetU16(&offset); // OEM information; e_oemid specific
38289eb1baeSVirgile Bello       dos_header.e_res2[0] = data.GetU16(&offset); // Reserved words
38389eb1baeSVirgile Bello       dos_header.e_res2[1] = data.GetU16(&offset); // Reserved words
38489eb1baeSVirgile Bello       dos_header.e_res2[2] = data.GetU16(&offset); // Reserved words
38589eb1baeSVirgile Bello       dos_header.e_res2[3] = data.GetU16(&offset); // Reserved words
38689eb1baeSVirgile Bello       dos_header.e_res2[4] = data.GetU16(&offset); // Reserved words
38789eb1baeSVirgile Bello       dos_header.e_res2[5] = data.GetU16(&offset); // Reserved words
38889eb1baeSVirgile Bello       dos_header.e_res2[6] = data.GetU16(&offset); // Reserved words
38989eb1baeSVirgile Bello       dos_header.e_res2[7] = data.GetU16(&offset); // Reserved words
39089eb1baeSVirgile Bello       dos_header.e_res2[8] = data.GetU16(&offset); // Reserved words
39189eb1baeSVirgile Bello       dos_header.e_res2[9] = data.GetU16(&offset); // Reserved words
392f754f88fSGreg Clayton 
393b9c1b51eSKate Stone       dos_header.e_lfanew =
394b9c1b51eSKate Stone           data.GetU32(&offset); // File address of new exe header
395f754f88fSGreg Clayton     }
396f754f88fSGreg Clayton   }
397f754f88fSGreg Clayton   if (!success)
39889eb1baeSVirgile Bello     memset(&dos_header, 0, sizeof(dos_header));
399f754f88fSGreg Clayton   return success;
400f754f88fSGreg Clayton }
401f754f88fSGreg Clayton 
402f754f88fSGreg Clayton // ParserCOFFHeader
403b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseCOFFHeader(DataExtractor &data,
404b9c1b51eSKate Stone                                        lldb::offset_t *offset_ptr,
405b9c1b51eSKate Stone                                        coff_header_t &coff_header) {
406b9c1b51eSKate Stone   bool success =
407b9c1b51eSKate Stone       data.ValidOffsetForDataOfSize(*offset_ptr, sizeof(coff_header));
408b9c1b51eSKate Stone   if (success) {
40989eb1baeSVirgile Bello     coff_header.machine = data.GetU16(offset_ptr);
41089eb1baeSVirgile Bello     coff_header.nsects = data.GetU16(offset_ptr);
41189eb1baeSVirgile Bello     coff_header.modtime = data.GetU32(offset_ptr);
41289eb1baeSVirgile Bello     coff_header.symoff = data.GetU32(offset_ptr);
41389eb1baeSVirgile Bello     coff_header.nsyms = data.GetU32(offset_ptr);
41489eb1baeSVirgile Bello     coff_header.hdrsize = data.GetU16(offset_ptr);
41589eb1baeSVirgile Bello     coff_header.flags = data.GetU16(offset_ptr);
416f754f88fSGreg Clayton   }
417f754f88fSGreg Clayton   if (!success)
41889eb1baeSVirgile Bello     memset(&coff_header, 0, sizeof(coff_header));
419f754f88fSGreg Clayton   return success;
420f754f88fSGreg Clayton }
421f754f88fSGreg Clayton 
422b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseCOFFOptionalHeader(lldb::offset_t *offset_ptr) {
423f754f88fSGreg Clayton   bool success = false;
424c7bece56SGreg Clayton   const lldb::offset_t end_offset = *offset_ptr + m_coff_header.hdrsize;
425b9c1b51eSKate Stone   if (*offset_ptr < end_offset) {
426f754f88fSGreg Clayton     success = true;
427f754f88fSGreg Clayton     m_coff_header_opt.magic = m_data.GetU16(offset_ptr);
428f754f88fSGreg Clayton     m_coff_header_opt.major_linker_version = m_data.GetU8(offset_ptr);
429f754f88fSGreg Clayton     m_coff_header_opt.minor_linker_version = m_data.GetU8(offset_ptr);
430f754f88fSGreg Clayton     m_coff_header_opt.code_size = m_data.GetU32(offset_ptr);
431f754f88fSGreg Clayton     m_coff_header_opt.data_size = m_data.GetU32(offset_ptr);
432f754f88fSGreg Clayton     m_coff_header_opt.bss_size = m_data.GetU32(offset_ptr);
433f754f88fSGreg Clayton     m_coff_header_opt.entry = m_data.GetU32(offset_ptr);
434f754f88fSGreg Clayton     m_coff_header_opt.code_offset = m_data.GetU32(offset_ptr);
435f754f88fSGreg Clayton 
436f754f88fSGreg Clayton     const uint32_t addr_byte_size = GetAddressByteSize();
437f754f88fSGreg Clayton 
438b9c1b51eSKate Stone     if (*offset_ptr < end_offset) {
439b9c1b51eSKate Stone       if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32) {
440f754f88fSGreg Clayton         // PE32 only
441f754f88fSGreg Clayton         m_coff_header_opt.data_offset = m_data.GetU32(offset_ptr);
442b9c1b51eSKate Stone       } else
443f754f88fSGreg Clayton         m_coff_header_opt.data_offset = 0;
444f754f88fSGreg Clayton 
445b9c1b51eSKate Stone       if (*offset_ptr < end_offset) {
446b9c1b51eSKate Stone         m_coff_header_opt.image_base =
447b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
448f754f88fSGreg Clayton         m_coff_header_opt.sect_alignment = m_data.GetU32(offset_ptr);
449f754f88fSGreg Clayton         m_coff_header_opt.file_alignment = m_data.GetU32(offset_ptr);
450f754f88fSGreg Clayton         m_coff_header_opt.major_os_system_version = m_data.GetU16(offset_ptr);
451f754f88fSGreg Clayton         m_coff_header_opt.minor_os_system_version = m_data.GetU16(offset_ptr);
452f754f88fSGreg Clayton         m_coff_header_opt.major_image_version = m_data.GetU16(offset_ptr);
453f754f88fSGreg Clayton         m_coff_header_opt.minor_image_version = m_data.GetU16(offset_ptr);
454f754f88fSGreg Clayton         m_coff_header_opt.major_subsystem_version = m_data.GetU16(offset_ptr);
455f754f88fSGreg Clayton         m_coff_header_opt.minor_subsystem_version = m_data.GetU16(offset_ptr);
456f754f88fSGreg Clayton         m_coff_header_opt.reserved1 = m_data.GetU32(offset_ptr);
457f754f88fSGreg Clayton         m_coff_header_opt.image_size = m_data.GetU32(offset_ptr);
458f754f88fSGreg Clayton         m_coff_header_opt.header_size = m_data.GetU32(offset_ptr);
45928469ca3SGreg Clayton         m_coff_header_opt.checksum = m_data.GetU32(offset_ptr);
460f754f88fSGreg Clayton         m_coff_header_opt.subsystem = m_data.GetU16(offset_ptr);
461f754f88fSGreg Clayton         m_coff_header_opt.dll_flags = m_data.GetU16(offset_ptr);
462b9c1b51eSKate Stone         m_coff_header_opt.stack_reserve_size =
463b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
464b9c1b51eSKate Stone         m_coff_header_opt.stack_commit_size =
465b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
466b9c1b51eSKate Stone         m_coff_header_opt.heap_reserve_size =
467b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
468b9c1b51eSKate Stone         m_coff_header_opt.heap_commit_size =
469b9c1b51eSKate Stone             m_data.GetMaxU64(offset_ptr, addr_byte_size);
470f754f88fSGreg Clayton         m_coff_header_opt.loader_flags = m_data.GetU32(offset_ptr);
471f754f88fSGreg Clayton         uint32_t num_data_dir_entries = m_data.GetU32(offset_ptr);
472f754f88fSGreg Clayton         m_coff_header_opt.data_dirs.clear();
473f754f88fSGreg Clayton         m_coff_header_opt.data_dirs.resize(num_data_dir_entries);
474f754f88fSGreg Clayton         uint32_t i;
475b9c1b51eSKate Stone         for (i = 0; i < num_data_dir_entries; i++) {
476f754f88fSGreg Clayton           m_coff_header_opt.data_dirs[i].vmaddr = m_data.GetU32(offset_ptr);
477f754f88fSGreg Clayton           m_coff_header_opt.data_dirs[i].vmsize = m_data.GetU32(offset_ptr);
478f754f88fSGreg Clayton         }
4792756adf3SVirgile Bello 
4802756adf3SVirgile Bello         m_image_base = m_coff_header_opt.image_base;
481f754f88fSGreg Clayton       }
482f754f88fSGreg Clayton     }
483f754f88fSGreg Clayton   }
484f754f88fSGreg Clayton   // Make sure we are on track for section data which follows
485f754f88fSGreg Clayton   *offset_ptr = end_offset;
486f754f88fSGreg Clayton   return success;
487f754f88fSGreg Clayton }
488f754f88fSGreg Clayton 
48930c2441aSAleksandr Urakov uint32_t ObjectFilePECOFF::GetRVA(const Address &addr) const {
49030c2441aSAleksandr Urakov   return addr.GetFileAddress() - m_image_base;
49130c2441aSAleksandr Urakov }
49230c2441aSAleksandr Urakov 
49330c2441aSAleksandr Urakov Address ObjectFilePECOFF::GetAddress(uint32_t rva) {
49430c2441aSAleksandr Urakov   SectionList *sect_list = GetSectionList();
49530c2441aSAleksandr Urakov   if (!sect_list)
49630c2441aSAleksandr Urakov     return Address(GetFileAddress(rva));
49730c2441aSAleksandr Urakov 
49830c2441aSAleksandr Urakov   return Address(GetFileAddress(rva), sect_list);
49930c2441aSAleksandr Urakov }
50030c2441aSAleksandr Urakov 
50130c2441aSAleksandr Urakov lldb::addr_t ObjectFilePECOFF::GetFileAddress(uint32_t rva) const {
50230c2441aSAleksandr Urakov   return m_image_base + rva;
50330c2441aSAleksandr Urakov }
50430c2441aSAleksandr Urakov 
505344546bdSWalter Erquinigo DataExtractor ObjectFilePECOFF::ReadImageData(uint32_t offset, size_t size) {
50630c2441aSAleksandr Urakov   if (!size)
50730c2441aSAleksandr Urakov     return {};
50830c2441aSAleksandr Urakov 
509a4a00cedSFred Riss   if (m_data.ValidOffsetForDataOfSize(offset, size))
510a4a00cedSFred Riss     return DataExtractor(m_data, offset, size);
511a4a00cedSFred Riss 
512344546bdSWalter Erquinigo   ProcessSP process_sp(m_process_wp.lock());
513344546bdSWalter Erquinigo   DataExtractor data;
514344546bdSWalter Erquinigo   if (process_sp) {
515a8f3ae7cSJonas Devlieghere     auto data_up = std::make_unique<DataBufferHeap>(size, 0);
51697206d57SZachary Turner     Status readmem_error;
517344546bdSWalter Erquinigo     size_t bytes_read =
518d5b44036SJonas Devlieghere         process_sp->ReadMemory(m_image_base + offset, data_up->GetBytes(),
519d5b44036SJonas Devlieghere                                data_up->GetByteSize(), readmem_error);
520344546bdSWalter Erquinigo     if (bytes_read == size) {
521d5b44036SJonas Devlieghere       DataBufferSP buffer_sp(data_up.release());
522344546bdSWalter Erquinigo       data.SetData(buffer_sp, 0, buffer_sp->GetByteSize());
523344546bdSWalter Erquinigo     }
524344546bdSWalter Erquinigo   }
525344546bdSWalter Erquinigo   return data;
526344546bdSWalter Erquinigo }
527344546bdSWalter Erquinigo 
52830c2441aSAleksandr Urakov DataExtractor ObjectFilePECOFF::ReadImageDataByRVA(uint32_t rva, size_t size) {
52930c2441aSAleksandr Urakov   Address addr = GetAddress(rva);
5307e1a3076SMartin Storsjö   SectionSP sect = addr.GetSection();
5317e1a3076SMartin Storsjö   if (!sect)
5327e1a3076SMartin Storsjö     return {};
5337e1a3076SMartin Storsjö   rva = sect->GetFileOffset() + addr.GetOffset();
53430c2441aSAleksandr Urakov 
53530c2441aSAleksandr Urakov   return ReadImageData(rva, size);
53630c2441aSAleksandr Urakov }
53730c2441aSAleksandr Urakov 
538f754f88fSGreg Clayton // ParseSectionHeaders
539b9c1b51eSKate Stone bool ObjectFilePECOFF::ParseSectionHeaders(
540b9c1b51eSKate Stone     uint32_t section_header_data_offset) {
541f754f88fSGreg Clayton   const uint32_t nsects = m_coff_header.nsects;
542f754f88fSGreg Clayton   m_sect_headers.clear();
543f754f88fSGreg Clayton 
544b9c1b51eSKate Stone   if (nsects > 0) {
545f754f88fSGreg Clayton     const size_t section_header_byte_size = nsects * sizeof(section_header_t);
546344546bdSWalter Erquinigo     DataExtractor section_header_data =
547344546bdSWalter Erquinigo         ReadImageData(section_header_data_offset, section_header_byte_size);
548f754f88fSGreg Clayton 
549c7bece56SGreg Clayton     lldb::offset_t offset = 0;
550b9c1b51eSKate Stone     if (section_header_data.ValidOffsetForDataOfSize(
551b9c1b51eSKate Stone             offset, section_header_byte_size)) {
552f754f88fSGreg Clayton       m_sect_headers.resize(nsects);
553f754f88fSGreg Clayton 
554b9c1b51eSKate Stone       for (uint32_t idx = 0; idx < nsects; ++idx) {
555f754f88fSGreg Clayton         const void *name_data = section_header_data.GetData(&offset, 8);
556b9c1b51eSKate Stone         if (name_data) {
557f754f88fSGreg Clayton           memcpy(m_sect_headers[idx].name, name_data, 8);
558f754f88fSGreg Clayton           m_sect_headers[idx].vmsize = section_header_data.GetU32(&offset);
559f754f88fSGreg Clayton           m_sect_headers[idx].vmaddr = section_header_data.GetU32(&offset);
560f754f88fSGreg Clayton           m_sect_headers[idx].size = section_header_data.GetU32(&offset);
561f754f88fSGreg Clayton           m_sect_headers[idx].offset = section_header_data.GetU32(&offset);
562f754f88fSGreg Clayton           m_sect_headers[idx].reloff = section_header_data.GetU32(&offset);
563f754f88fSGreg Clayton           m_sect_headers[idx].lineoff = section_header_data.GetU32(&offset);
564f754f88fSGreg Clayton           m_sect_headers[idx].nreloc = section_header_data.GetU16(&offset);
565f754f88fSGreg Clayton           m_sect_headers[idx].nline = section_header_data.GetU16(&offset);
566f754f88fSGreg Clayton           m_sect_headers[idx].flags = section_header_data.GetU32(&offset);
567f754f88fSGreg Clayton         }
568f754f88fSGreg Clayton       }
569f754f88fSGreg Clayton     }
570f754f88fSGreg Clayton   }
571f754f88fSGreg Clayton 
572a6682a41SJonas Devlieghere   return !m_sect_headers.empty();
573f754f88fSGreg Clayton }
574f754f88fSGreg Clayton 
5752886e4a0SPavel Labath llvm::StringRef ObjectFilePECOFF::GetSectionName(const section_header_t &sect) {
576f15014ffSBenjamin Kramer   llvm::StringRef hdr_name(sect.name, llvm::array_lengthof(sect.name));
5772886e4a0SPavel Labath   hdr_name = hdr_name.split('\0').first;
5782886e4a0SPavel Labath   if (hdr_name.consume_front("/")) {
5792886e4a0SPavel Labath     lldb::offset_t stroff;
5802886e4a0SPavel Labath     if (!to_integer(hdr_name, stroff, 10))
5812886e4a0SPavel Labath       return "";
582b9c1b51eSKate Stone     lldb::offset_t string_file_offset =
583b9c1b51eSKate Stone         m_coff_header.symoff + (m_coff_header.nsyms * 18) + stroff;
5842886e4a0SPavel Labath     if (const char *name = m_data.GetCStr(&string_file_offset))
5852886e4a0SPavel Labath       return name;
5862886e4a0SPavel Labath     return "";
587f754f88fSGreg Clayton   }
5882886e4a0SPavel Labath   return hdr_name;
589f754f88fSGreg Clayton }
590f754f88fSGreg Clayton 
5917e6df41fSGreg Clayton void ObjectFilePECOFF::ParseSymtab(Symtab &symtab) {
592f754f88fSGreg Clayton   SectionList *sect_list = GetSectionList();
59328469ca3SGreg Clayton   const uint32_t num_syms = m_coff_header.nsyms;
594344546bdSWalter Erquinigo   if (m_file && num_syms > 0 && m_coff_header.symoff > 0) {
5950076e715SGreg Clayton     const uint32_t symbol_size = 18;
59628469ca3SGreg Clayton     const size_t symbol_data_size = num_syms * symbol_size;
597c35b91ceSAdrian McCarthy     // Include the 4-byte string table size at the end of the symbols
598344546bdSWalter Erquinigo     DataExtractor symtab_data =
599344546bdSWalter Erquinigo         ReadImageData(m_coff_header.symoff, symbol_data_size + 4);
600c7bece56SGreg Clayton     lldb::offset_t offset = symbol_data_size;
60128469ca3SGreg Clayton     const uint32_t strtab_size = symtab_data.GetU32(&offset);
602344546bdSWalter Erquinigo     if (strtab_size > 0) {
603344546bdSWalter Erquinigo       DataExtractor strtab_data = ReadImageData(
604344546bdSWalter Erquinigo           m_coff_header.symoff + symbol_data_size, strtab_size);
60528469ca3SGreg Clayton 
60628469ca3SGreg Clayton       offset = 0;
60728469ca3SGreg Clayton       std::string symbol_name;
6087e6df41fSGreg Clayton       Symbol *symbols = symtab.Resize(num_syms);
609b9c1b51eSKate Stone       for (uint32_t i = 0; i < num_syms; ++i) {
610f754f88fSGreg Clayton         coff_symbol_t symbol;
61128469ca3SGreg Clayton         const uint32_t symbol_offset = offset;
612248a1305SKonrad Kleine         const char *symbol_name_cstr = nullptr;
613c35b91ceSAdrian McCarthy         // If the first 4 bytes of the symbol string are zero, then they
614c35b91ceSAdrian McCarthy         // are followed by a 4-byte string table offset. Else these
61528469ca3SGreg Clayton         // 8 bytes contain the symbol name
616b9c1b51eSKate Stone         if (symtab_data.GetU32(&offset) == 0) {
61705097246SAdrian Prantl           // Long string that doesn't fit into the symbol table name, so
61805097246SAdrian Prantl           // now we must read the 4 byte string table offset
61928469ca3SGreg Clayton           uint32_t strtab_offset = symtab_data.GetU32(&offset);
62028469ca3SGreg Clayton           symbol_name_cstr = strtab_data.PeekCStr(strtab_offset);
62128469ca3SGreg Clayton           symbol_name.assign(symbol_name_cstr);
622b9c1b51eSKate Stone         } else {
623b9c1b51eSKate Stone           // Short string that fits into the symbol table name which is 8
624b9c1b51eSKate Stone           // bytes
62528469ca3SGreg Clayton           offset += sizeof(symbol.name) - 4; // Skip remaining
62628469ca3SGreg Clayton           symbol_name_cstr = symtab_data.PeekCStr(symbol_offset);
627248a1305SKonrad Kleine           if (symbol_name_cstr == nullptr)
628f754f88fSGreg Clayton             break;
62928469ca3SGreg Clayton           symbol_name.assign(symbol_name_cstr, sizeof(symbol.name));
63028469ca3SGreg Clayton         }
63128469ca3SGreg Clayton         symbol.value = symtab_data.GetU32(&offset);
63228469ca3SGreg Clayton         symbol.sect = symtab_data.GetU16(&offset);
63328469ca3SGreg Clayton         symbol.type = symtab_data.GetU16(&offset);
63428469ca3SGreg Clayton         symbol.storage = symtab_data.GetU8(&offset);
63528469ca3SGreg Clayton         symbol.naux = symtab_data.GetU8(&offset);
636037520e9SGreg Clayton         symbols[i].GetMangled().SetValue(ConstString(symbol_name.c_str()));
637b9c1b51eSKate Stone         if ((int16_t)symbol.sect >= 1) {
6384394b5beSMartin Storsjö           Address symbol_addr(sect_list->FindSectionByID(symbol.sect),
639b9c1b51eSKate Stone                               symbol.value);
640358cf1eaSGreg Clayton           symbols[i].GetAddressRef() = symbol_addr;
641c35b91ceSAdrian McCarthy           symbols[i].SetType(MapSymbolType(symbol.type));
6420076e715SGreg Clayton         }
643f754f88fSGreg Clayton 
644b9c1b51eSKate Stone         if (symbol.naux > 0) {
645f754f88fSGreg Clayton           i += symbol.naux;
646f07ddbc9SMartin Storsjö           offset += symbol.naux * symbol_size;
6470076e715SGreg Clayton         }
648f754f88fSGreg Clayton       }
649f754f88fSGreg Clayton     }
650344546bdSWalter Erquinigo   }
651a4fe3a12SVirgile Bello 
652a4fe3a12SVirgile Bello   // Read export header
653b9c1b51eSKate Stone   if (coff_data_dir_export_table < m_coff_header_opt.data_dirs.size() &&
654b9c1b51eSKate Stone       m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmsize > 0 &&
655b9c1b51eSKate Stone       m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr > 0) {
656a4fe3a12SVirgile Bello     export_directory_entry export_table;
657b9c1b51eSKate Stone     uint32_t data_start =
658b9c1b51eSKate Stone         m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr;
659344546bdSWalter Erquinigo 
66030c2441aSAleksandr Urakov     DataExtractor symtab_data = ReadImageDataByRVA(
66130c2441aSAleksandr Urakov         data_start, m_coff_header_opt.data_dirs[0].vmsize);
662a4fe3a12SVirgile Bello     lldb::offset_t offset = 0;
663a4fe3a12SVirgile Bello 
664a4fe3a12SVirgile Bello     // Read export_table header
665a4fe3a12SVirgile Bello     export_table.characteristics = symtab_data.GetU32(&offset);
666a4fe3a12SVirgile Bello     export_table.time_date_stamp = symtab_data.GetU32(&offset);
667a4fe3a12SVirgile Bello     export_table.major_version = symtab_data.GetU16(&offset);
668a4fe3a12SVirgile Bello     export_table.minor_version = symtab_data.GetU16(&offset);
669a4fe3a12SVirgile Bello     export_table.name = symtab_data.GetU32(&offset);
670a4fe3a12SVirgile Bello     export_table.base = symtab_data.GetU32(&offset);
671a4fe3a12SVirgile Bello     export_table.number_of_functions = symtab_data.GetU32(&offset);
672a4fe3a12SVirgile Bello     export_table.number_of_names = symtab_data.GetU32(&offset);
673a4fe3a12SVirgile Bello     export_table.address_of_functions = symtab_data.GetU32(&offset);
674a4fe3a12SVirgile Bello     export_table.address_of_names = symtab_data.GetU32(&offset);
675a4fe3a12SVirgile Bello     export_table.address_of_name_ordinals = symtab_data.GetU32(&offset);
676a4fe3a12SVirgile Bello 
677a4fe3a12SVirgile Bello     bool has_ordinal = export_table.address_of_name_ordinals != 0;
678a4fe3a12SVirgile Bello 
679a4fe3a12SVirgile Bello     lldb::offset_t name_offset = export_table.address_of_names - data_start;
680b9c1b51eSKate Stone     lldb::offset_t name_ordinal_offset =
681b9c1b51eSKate Stone         export_table.address_of_name_ordinals - data_start;
682a4fe3a12SVirgile Bello 
6837e6df41fSGreg Clayton     Symbol *symbols = symtab.Resize(export_table.number_of_names);
684a4fe3a12SVirgile Bello 
685a4fe3a12SVirgile Bello     std::string symbol_name;
686a4fe3a12SVirgile Bello 
687a4fe3a12SVirgile Bello     // Read each export table entry
688b9c1b51eSKate Stone     for (size_t i = 0; i < export_table.number_of_names; ++i) {
689b9c1b51eSKate Stone       uint32_t name_ordinal =
690b9c1b51eSKate Stone           has_ordinal ? symtab_data.GetU16(&name_ordinal_offset) : i;
691a4fe3a12SVirgile Bello       uint32_t name_address = symtab_data.GetU32(&name_offset);
692a4fe3a12SVirgile Bello 
693b9c1b51eSKate Stone       const char *symbol_name_cstr =
694b9c1b51eSKate Stone           symtab_data.PeekCStr(name_address - data_start);
695a4fe3a12SVirgile Bello       symbol_name.assign(symbol_name_cstr);
696a4fe3a12SVirgile Bello 
697b9c1b51eSKate Stone       lldb::offset_t function_offset = export_table.address_of_functions -
698b9c1b51eSKate Stone                                         data_start +
699b9c1b51eSKate Stone                                         sizeof(uint32_t) * name_ordinal;
700a4fe3a12SVirgile Bello       uint32_t function_rva = symtab_data.GetU32(&function_offset);
701a4fe3a12SVirgile Bello 
702b9c1b51eSKate Stone       Address symbol_addr(m_coff_header_opt.image_base + function_rva,
703b9c1b51eSKate Stone                           sect_list);
704a4fe3a12SVirgile Bello       symbols[i].GetMangled().SetValue(ConstString(symbol_name.c_str()));
705358cf1eaSGreg Clayton       symbols[i].GetAddressRef() = symbol_addr;
706a4fe3a12SVirgile Bello       symbols[i].SetType(lldb::eSymbolTypeCode);
707a4fe3a12SVirgile Bello       symbols[i].SetDebug(true);
708a4fe3a12SVirgile Bello     }
709a4fe3a12SVirgile Bello   }
710f754f88fSGreg Clayton }
711f754f88fSGreg Clayton 
71230c2441aSAleksandr Urakov std::unique_ptr<CallFrameInfo> ObjectFilePECOFF::CreateCallFrameInfo() {
71330c2441aSAleksandr Urakov   if (coff_data_dir_exception_table >= m_coff_header_opt.data_dirs.size())
71430c2441aSAleksandr Urakov     return {};
71530c2441aSAleksandr Urakov 
71630c2441aSAleksandr Urakov   data_directory data_dir_exception =
71730c2441aSAleksandr Urakov       m_coff_header_opt.data_dirs[coff_data_dir_exception_table];
71830c2441aSAleksandr Urakov   if (!data_dir_exception.vmaddr)
71930c2441aSAleksandr Urakov     return {};
72030c2441aSAleksandr Urakov 
721aa786b88SMartin Storsjö   if (m_coff_header.machine != llvm::COFF::IMAGE_FILE_MACHINE_AMD64)
722aa786b88SMartin Storsjö     return {};
723aa786b88SMartin Storsjö 
72430c2441aSAleksandr Urakov   return std::make_unique<PECallFrameInfo>(*this, data_dir_exception.vmaddr,
72530c2441aSAleksandr Urakov                                            data_dir_exception.vmsize);
72630c2441aSAleksandr Urakov }
72730c2441aSAleksandr Urakov 
728b9c1b51eSKate Stone bool ObjectFilePECOFF::IsStripped() {
7293046e668SGreg Clayton   // TODO: determine this for COFF
7303046e668SGreg Clayton   return false;
7313046e668SGreg Clayton }
7323046e668SGreg Clayton 
7332e5bb6d8SMartin Storsjö SectionType ObjectFilePECOFF::GetSectionType(llvm::StringRef sect_name,
7342e5bb6d8SMartin Storsjö                                              const section_header_t &sect) {
7352e5bb6d8SMartin Storsjö   ConstString const_sect_name(sect_name);
7362e5bb6d8SMartin Storsjö   static ConstString g_code_sect_name(".code");
7372e5bb6d8SMartin Storsjö   static ConstString g_CODE_sect_name("CODE");
7382e5bb6d8SMartin Storsjö   static ConstString g_data_sect_name(".data");
7392e5bb6d8SMartin Storsjö   static ConstString g_DATA_sect_name("DATA");
7402e5bb6d8SMartin Storsjö   static ConstString g_bss_sect_name(".bss");
7412e5bb6d8SMartin Storsjö   static ConstString g_BSS_sect_name("BSS");
7422e5bb6d8SMartin Storsjö 
7432e5bb6d8SMartin Storsjö   if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_CODE &&
7442e5bb6d8SMartin Storsjö       ((const_sect_name == g_code_sect_name) ||
7452e5bb6d8SMartin Storsjö        (const_sect_name == g_CODE_sect_name))) {
7462e5bb6d8SMartin Storsjö     return eSectionTypeCode;
7472e5bb6d8SMartin Storsjö   }
7482e5bb6d8SMartin Storsjö   if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA &&
7492e5bb6d8SMartin Storsjö              ((const_sect_name == g_data_sect_name) ||
7502e5bb6d8SMartin Storsjö               (const_sect_name == g_DATA_sect_name))) {
7512e5bb6d8SMartin Storsjö     if (sect.size == 0 && sect.offset == 0)
7522e5bb6d8SMartin Storsjö       return eSectionTypeZeroFill;
7532e5bb6d8SMartin Storsjö     else
7542e5bb6d8SMartin Storsjö       return eSectionTypeData;
7552e5bb6d8SMartin Storsjö   }
7562e5bb6d8SMartin Storsjö   if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA &&
7572e5bb6d8SMartin Storsjö              ((const_sect_name == g_bss_sect_name) ||
7582e5bb6d8SMartin Storsjö               (const_sect_name == g_BSS_sect_name))) {
7592e5bb6d8SMartin Storsjö     if (sect.size == 0)
7602e5bb6d8SMartin Storsjö       return eSectionTypeZeroFill;
7612e5bb6d8SMartin Storsjö     else
7622e5bb6d8SMartin Storsjö       return eSectionTypeData;
7632e5bb6d8SMartin Storsjö   }
7642e5bb6d8SMartin Storsjö 
7652e5bb6d8SMartin Storsjö   SectionType section_type =
7662e5bb6d8SMartin Storsjö       llvm::StringSwitch<SectionType>(sect_name)
7672e5bb6d8SMartin Storsjö           .Case(".debug", eSectionTypeDebug)
7682e5bb6d8SMartin Storsjö           .Case(".stabstr", eSectionTypeDataCString)
7692e5bb6d8SMartin Storsjö           .Case(".reloc", eSectionTypeOther)
7702e5bb6d8SMartin Storsjö           .Case(".debug_abbrev", eSectionTypeDWARFDebugAbbrev)
7712e5bb6d8SMartin Storsjö           .Case(".debug_aranges", eSectionTypeDWARFDebugAranges)
7722e5bb6d8SMartin Storsjö           .Case(".debug_frame", eSectionTypeDWARFDebugFrame)
7732e5bb6d8SMartin Storsjö           .Case(".debug_info", eSectionTypeDWARFDebugInfo)
7742e5bb6d8SMartin Storsjö           .Case(".debug_line", eSectionTypeDWARFDebugLine)
7752e5bb6d8SMartin Storsjö           .Case(".debug_loc", eSectionTypeDWARFDebugLoc)
7762e5bb6d8SMartin Storsjö           .Case(".debug_loclists", eSectionTypeDWARFDebugLocLists)
7772e5bb6d8SMartin Storsjö           .Case(".debug_macinfo", eSectionTypeDWARFDebugMacInfo)
7782e5bb6d8SMartin Storsjö           .Case(".debug_names", eSectionTypeDWARFDebugNames)
7792e5bb6d8SMartin Storsjö           .Case(".debug_pubnames", eSectionTypeDWARFDebugPubNames)
7802e5bb6d8SMartin Storsjö           .Case(".debug_pubtypes", eSectionTypeDWARFDebugPubTypes)
7812e5bb6d8SMartin Storsjö           .Case(".debug_ranges", eSectionTypeDWARFDebugRanges)
7822e5bb6d8SMartin Storsjö           .Case(".debug_str", eSectionTypeDWARFDebugStr)
7832e5bb6d8SMartin Storsjö           .Case(".debug_types", eSectionTypeDWARFDebugTypes)
784934c025eSMartin Storsjö           // .eh_frame can be truncated to 8 chars.
785934c025eSMartin Storsjö           .Cases(".eh_frame", ".eh_fram", eSectionTypeEHFrame)
7862e5bb6d8SMartin Storsjö           .Case(".gosymtab", eSectionTypeGoSymtab)
7872e5bb6d8SMartin Storsjö           .Default(eSectionTypeInvalid);
7882e5bb6d8SMartin Storsjö   if (section_type != eSectionTypeInvalid)
7892e5bb6d8SMartin Storsjö     return section_type;
7902e5bb6d8SMartin Storsjö 
7912e5bb6d8SMartin Storsjö   if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_CODE)
7922e5bb6d8SMartin Storsjö     return eSectionTypeCode;
7932e5bb6d8SMartin Storsjö   if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
7942e5bb6d8SMartin Storsjö     return eSectionTypeData;
7952e5bb6d8SMartin Storsjö   if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) {
7962e5bb6d8SMartin Storsjö     if (sect.size == 0)
7972e5bb6d8SMartin Storsjö       return eSectionTypeZeroFill;
7982e5bb6d8SMartin Storsjö     else
7992e5bb6d8SMartin Storsjö       return eSectionTypeData;
8002e5bb6d8SMartin Storsjö   }
8012e5bb6d8SMartin Storsjö   return eSectionTypeOther;
8022e5bb6d8SMartin Storsjö }
8032e5bb6d8SMartin Storsjö 
804b9c1b51eSKate Stone void ObjectFilePECOFF::CreateSections(SectionList &unified_section_list) {
805d5b44036SJonas Devlieghere   if (m_sections_up)
80688a2c2a4SPavel Labath     return;
80706412daeSJonas Devlieghere   m_sections_up = std::make_unique<SectionList>();
808a1743499SGreg Clayton   ModuleSP module_sp(GetModule());
809b9c1b51eSKate Stone   if (module_sp) {
81016ff8604SSaleem Abdulrasool     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
8117db8b5c4SPavel Labath 
81273a7a55cSPavel Labath     SectionSP header_sp = std::make_shared<Section>(
81373a7a55cSPavel Labath         module_sp, this, ~user_id_t(0), ConstString("PECOFF header"),
81473a7a55cSPavel Labath         eSectionTypeOther, m_coff_header_opt.image_base,
81573a7a55cSPavel Labath         m_coff_header_opt.header_size,
81673a7a55cSPavel Labath         /*file_offset*/ 0, m_coff_header_opt.header_size,
81773a7a55cSPavel Labath         m_coff_header_opt.sect_alignment,
8187db8b5c4SPavel Labath         /*flags*/ 0);
819f1e0ae34SPavel Labath     header_sp->SetPermissions(ePermissionsReadable);
82073a7a55cSPavel Labath     m_sections_up->AddSection(header_sp);
82173a7a55cSPavel Labath     unified_section_list.AddSection(header_sp);
8227db8b5c4SPavel Labath 
823f754f88fSGreg Clayton     const uint32_t nsects = m_sect_headers.size();
824e72dfb32SGreg Clayton     ModuleSP module_sp(GetModule());
825b9c1b51eSKate Stone     for (uint32_t idx = 0; idx < nsects; ++idx) {
8262e5bb6d8SMartin Storsjö       llvm::StringRef sect_name = GetSectionName(m_sect_headers[idx]);
8272e5bb6d8SMartin Storsjö       ConstString const_sect_name(sect_name);
8282e5bb6d8SMartin Storsjö       SectionType section_type = GetSectionType(sect_name, m_sect_headers[idx]);
829f754f88fSGreg Clayton 
830b9c1b51eSKate Stone       SectionSP section_sp(new Section(
831b9c1b51eSKate Stone           module_sp,       // Module to which this section belongs
832a7499c98SMichael Sartain           this,            // Object file to which this section belongs
8337db8b5c4SPavel Labath           idx + 1,         // Section ID is the 1 based section index.
834f754f88fSGreg Clayton           const_sect_name, // Name of this section
8357db8b5c4SPavel Labath           section_type,
83673a7a55cSPavel Labath           m_coff_header_opt.image_base +
837b9c1b51eSKate Stone               m_sect_headers[idx].vmaddr, // File VM address == addresses as
838b9c1b51eSKate Stone                                           // they are found in the object file
839f754f88fSGreg Clayton           m_sect_headers[idx].vmsize,     // VM size in bytes of this section
840b9c1b51eSKate Stone           m_sect_headers[idx]
841b9c1b51eSKate Stone               .offset, // Offset to the data for this section in the file
842b9c1b51eSKate Stone           m_sect_headers[idx]
843b9c1b51eSKate Stone               .size, // Size in bytes of this section as found in the file
84448672afbSGreg Clayton           m_coff_header_opt.sect_alignment, // Section alignment
845f754f88fSGreg Clayton           m_sect_headers[idx].flags));      // Flags for this section
846f754f88fSGreg Clayton 
847f1e0ae34SPavel Labath       uint32_t permissions = 0;
848f1e0ae34SPavel Labath       if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_EXECUTE)
849f1e0ae34SPavel Labath         permissions |= ePermissionsExecutable;
850f1e0ae34SPavel Labath       if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_READ)
851f1e0ae34SPavel Labath         permissions |= ePermissionsReadable;
852f1e0ae34SPavel Labath       if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_WRITE)
853f1e0ae34SPavel Labath         permissions |= ePermissionsWritable;
854f1e0ae34SPavel Labath       section_sp->SetPermissions(permissions);
855f1e0ae34SPavel Labath 
85673a7a55cSPavel Labath       m_sections_up->AddSection(section_sp);
85773a7a55cSPavel Labath       unified_section_list.AddSection(section_sp);
858f754f88fSGreg Clayton     }
859f754f88fSGreg Clayton   }
860a1743499SGreg Clayton }
861f754f88fSGreg Clayton 
862b8d03935SAaron Smith UUID ObjectFilePECOFF::GetUUID() {
863b8d03935SAaron Smith   if (m_uuid.IsValid())
864b8d03935SAaron Smith     return m_uuid;
865b8d03935SAaron Smith 
866b8d03935SAaron Smith   if (!CreateBinary())
867b8d03935SAaron Smith     return UUID();
868b8d03935SAaron Smith 
869d372a8e8SPavel Labath   m_uuid = GetCoffUUID(*m_binary);
870b8d03935SAaron Smith   return m_uuid;
871b8d03935SAaron Smith }
872f754f88fSGreg Clayton 
873037ed1beSAaron Smith uint32_t ObjectFilePECOFF::ParseDependentModules() {
874037ed1beSAaron Smith   ModuleSP module_sp(GetModule());
875037ed1beSAaron Smith   if (!module_sp)
876f754f88fSGreg Clayton     return 0;
877037ed1beSAaron Smith 
878037ed1beSAaron Smith   std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
879037ed1beSAaron Smith   if (m_deps_filespec)
880037ed1beSAaron Smith     return m_deps_filespec->GetSize();
881037ed1beSAaron Smith 
882037ed1beSAaron Smith   // Cache coff binary if it is not done yet.
883037ed1beSAaron Smith   if (!CreateBinary())
884037ed1beSAaron Smith     return 0;
885037ed1beSAaron Smith 
886a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Object);
887d372a8e8SPavel Labath   LLDB_LOG(log, "this = {0}, module = {1} ({2}), file = {3}, binary = {4}",
888d372a8e8SPavel Labath            this, GetModule().get(), GetModule()->GetSpecificationDescription(),
889d372a8e8SPavel Labath            m_file.GetPath(), m_binary.get());
890037ed1beSAaron Smith 
891037ed1beSAaron Smith   m_deps_filespec = FileSpecList();
892037ed1beSAaron Smith 
893d372a8e8SPavel Labath   for (const auto &entry : m_binary->import_directories()) {
894037ed1beSAaron Smith     llvm::StringRef dll_name;
895037ed1beSAaron Smith     // Report a bogus entry.
8961c03389cSReid Kleckner     if (llvm::Error e = entry.getName(dll_name)) {
89763e5fb76SJonas Devlieghere       LLDB_LOGF(log,
89863e5fb76SJonas Devlieghere                 "ObjectFilePECOFF::ParseDependentModules() - failed to get "
899037ed1beSAaron Smith                 "import directory entry name: %s",
9001c03389cSReid Kleckner                 llvm::toString(std::move(e)).c_str());
901037ed1beSAaron Smith       continue;
902037ed1beSAaron Smith     }
903037ed1beSAaron Smith 
904037ed1beSAaron Smith     // At this moment we only have the base name of the DLL. The full path can
905037ed1beSAaron Smith     // only be seen after the dynamic loading.  Our best guess is Try to get it
906037ed1beSAaron Smith     // with the help of the object file's directory.
907b3f44ad9SStella Stamenova     llvm::SmallString<128> dll_fullpath;
908037ed1beSAaron Smith     FileSpec dll_specs(dll_name);
909037ed1beSAaron Smith     dll_specs.GetDirectory().SetString(m_file.GetDirectory().GetCString());
910037ed1beSAaron Smith 
911037ed1beSAaron Smith     if (!llvm::sys::fs::real_path(dll_specs.GetPath(), dll_fullpath))
912f893d5bfSJonas Devlieghere       m_deps_filespec->EmplaceBack(dll_fullpath);
913037ed1beSAaron Smith     else {
914037ed1beSAaron Smith       // Known DLLs or DLL not found in the object file directory.
915f893d5bfSJonas Devlieghere       m_deps_filespec->EmplaceBack(dll_name);
916037ed1beSAaron Smith     }
917037ed1beSAaron Smith   }
918037ed1beSAaron Smith   return m_deps_filespec->GetSize();
919037ed1beSAaron Smith }
920037ed1beSAaron Smith 
921037ed1beSAaron Smith uint32_t ObjectFilePECOFF::GetDependentModules(FileSpecList &files) {
922037ed1beSAaron Smith   auto num_modules = ParseDependentModules();
923037ed1beSAaron Smith   auto original_size = files.GetSize();
924037ed1beSAaron Smith 
925037ed1beSAaron Smith   for (unsigned i = 0; i < num_modules; ++i)
926037ed1beSAaron Smith     files.AppendIfUnique(m_deps_filespec->GetFileSpecAtIndex(i));
927037ed1beSAaron Smith 
928037ed1beSAaron Smith   return files.GetSize() - original_size;
929f754f88fSGreg Clayton }
930f754f88fSGreg Clayton 
931b9c1b51eSKate Stone lldb_private::Address ObjectFilePECOFF::GetEntryPointAddress() {
9328e38c666SStephane Sezer   if (m_entry_point_address.IsValid())
9338e38c666SStephane Sezer     return m_entry_point_address;
9348e38c666SStephane Sezer 
9358e38c666SStephane Sezer   if (!ParseHeader() || !IsExecutable())
9368e38c666SStephane Sezer     return m_entry_point_address;
9378e38c666SStephane Sezer 
9388e38c666SStephane Sezer   SectionList *section_list = GetSectionList();
939a5235af9SAleksandr Urakov   addr_t file_addr = m_coff_header_opt.entry + m_coff_header_opt.image_base;
9408e38c666SStephane Sezer 
9418e38c666SStephane Sezer   if (!section_list)
942a5235af9SAleksandr Urakov     m_entry_point_address.SetOffset(file_addr);
9438e38c666SStephane Sezer   else
944b8d03935SAaron Smith     m_entry_point_address.ResolveAddressUsingFileSections(file_addr,
945b8d03935SAaron Smith                                                           section_list);
9468e38c666SStephane Sezer   return m_entry_point_address;
9478e38c666SStephane Sezer }
9488e38c666SStephane Sezer 
949d1304bbaSPavel Labath Address ObjectFilePECOFF::GetBaseAddress() {
950d1304bbaSPavel Labath   return Address(GetSectionList()->GetSectionAtIndex(0), 0);
951d1304bbaSPavel Labath }
952d1304bbaSPavel Labath 
953f754f88fSGreg Clayton // Dump
954f754f88fSGreg Clayton //
955f754f88fSGreg Clayton // Dump the specifics of the runtime file container (such as any headers
956f754f88fSGreg Clayton // segments, sections, etc).
957b9c1b51eSKate Stone void ObjectFilePECOFF::Dump(Stream *s) {
958a1743499SGreg Clayton   ModuleSP module_sp(GetModule());
959b9c1b51eSKate Stone   if (module_sp) {
96016ff8604SSaleem Abdulrasool     std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
961324a1036SSaleem Abdulrasool     s->Printf("%p: ", static_cast<void *>(this));
962f754f88fSGreg Clayton     s->Indent();
963f754f88fSGreg Clayton     s->PutCString("ObjectFilePECOFF");
964f754f88fSGreg Clayton 
965f760f5aeSPavel Labath     ArchSpec header_arch = GetArchitecture();
966f754f88fSGreg Clayton 
967b9c1b51eSKate Stone     *s << ", file = '" << m_file
968b9c1b51eSKate Stone        << "', arch = " << header_arch.GetArchitectureName() << "\n";
969f754f88fSGreg Clayton 
9703046e668SGreg Clayton     SectionList *sections = GetSectionList();
9713046e668SGreg Clayton     if (sections)
9723a168297SPavel Labath       sections->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true,
9733a168297SPavel Labath                      UINT32_MAX);
974f754f88fSGreg Clayton 
975d5b44036SJonas Devlieghere     if (m_symtab_up)
976248a1305SKonrad Kleine       m_symtab_up->Dump(s, nullptr, eSortOrderNone);
977f754f88fSGreg Clayton 
978f754f88fSGreg Clayton     if (m_dos_header.e_magic)
979f754f88fSGreg Clayton       DumpDOSHeader(s, m_dos_header);
980b9c1b51eSKate Stone     if (m_coff_header.machine) {
981f754f88fSGreg Clayton       DumpCOFFHeader(s, m_coff_header);
982f754f88fSGreg Clayton       if (m_coff_header.hdrsize)
983f754f88fSGreg Clayton         DumpOptCOFFHeader(s, m_coff_header_opt);
984f754f88fSGreg Clayton     }
985f754f88fSGreg Clayton     s->EOL();
986f754f88fSGreg Clayton     DumpSectionHeaders(s);
987f754f88fSGreg Clayton     s->EOL();
988037ed1beSAaron Smith 
989037ed1beSAaron Smith     DumpDependentModules(s);
990037ed1beSAaron Smith     s->EOL();
991f754f88fSGreg Clayton   }
992a1743499SGreg Clayton }
993f754f88fSGreg Clayton 
994f754f88fSGreg Clayton // DumpDOSHeader
995f754f88fSGreg Clayton //
996f754f88fSGreg Clayton // Dump the MS-DOS header to the specified output stream
997b9c1b51eSKate Stone void ObjectFilePECOFF::DumpDOSHeader(Stream *s, const dos_header_t &header) {
998f754f88fSGreg Clayton   s->PutCString("MSDOS Header\n");
999f754f88fSGreg Clayton   s->Printf("  e_magic    = 0x%4.4x\n", header.e_magic);
1000f754f88fSGreg Clayton   s->Printf("  e_cblp     = 0x%4.4x\n", header.e_cblp);
1001f754f88fSGreg Clayton   s->Printf("  e_cp       = 0x%4.4x\n", header.e_cp);
1002f754f88fSGreg Clayton   s->Printf("  e_crlc     = 0x%4.4x\n", header.e_crlc);
1003f754f88fSGreg Clayton   s->Printf("  e_cparhdr  = 0x%4.4x\n", header.e_cparhdr);
1004f754f88fSGreg Clayton   s->Printf("  e_minalloc = 0x%4.4x\n", header.e_minalloc);
1005f754f88fSGreg Clayton   s->Printf("  e_maxalloc = 0x%4.4x\n", header.e_maxalloc);
1006f754f88fSGreg Clayton   s->Printf("  e_ss       = 0x%4.4x\n", header.e_ss);
1007f754f88fSGreg Clayton   s->Printf("  e_sp       = 0x%4.4x\n", header.e_sp);
1008f754f88fSGreg Clayton   s->Printf("  e_csum     = 0x%4.4x\n", header.e_csum);
1009f754f88fSGreg Clayton   s->Printf("  e_ip       = 0x%4.4x\n", header.e_ip);
1010f754f88fSGreg Clayton   s->Printf("  e_cs       = 0x%4.4x\n", header.e_cs);
1011f754f88fSGreg Clayton   s->Printf("  e_lfarlc   = 0x%4.4x\n", header.e_lfarlc);
1012f754f88fSGreg Clayton   s->Printf("  e_ovno     = 0x%4.4x\n", header.e_ovno);
1013f754f88fSGreg Clayton   s->Printf("  e_res[4]   = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
1014b9c1b51eSKate Stone             header.e_res[0], header.e_res[1], header.e_res[2], header.e_res[3]);
1015f754f88fSGreg Clayton   s->Printf("  e_oemid    = 0x%4.4x\n", header.e_oemid);
1016f754f88fSGreg Clayton   s->Printf("  e_oeminfo  = 0x%4.4x\n", header.e_oeminfo);
1017b9c1b51eSKate Stone   s->Printf("  e_res2[10] = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, "
1018b9c1b51eSKate Stone             "0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
1019b9c1b51eSKate Stone             header.e_res2[0], header.e_res2[1], header.e_res2[2],
1020b9c1b51eSKate Stone             header.e_res2[3], header.e_res2[4], header.e_res2[5],
1021b9c1b51eSKate Stone             header.e_res2[6], header.e_res2[7], header.e_res2[8],
1022f754f88fSGreg Clayton             header.e_res2[9]);
1023f754f88fSGreg Clayton   s->Printf("  e_lfanew   = 0x%8.8x\n", header.e_lfanew);
1024f754f88fSGreg Clayton }
1025f754f88fSGreg Clayton 
1026f754f88fSGreg Clayton // DumpCOFFHeader
1027f754f88fSGreg Clayton //
1028f754f88fSGreg Clayton // Dump the COFF header to the specified output stream
1029b9c1b51eSKate Stone void ObjectFilePECOFF::DumpCOFFHeader(Stream *s, const coff_header_t &header) {
1030f754f88fSGreg Clayton   s->PutCString("COFF Header\n");
1031f754f88fSGreg Clayton   s->Printf("  machine = 0x%4.4x\n", header.machine);
1032f754f88fSGreg Clayton   s->Printf("  nsects  = 0x%4.4x\n", header.nsects);
1033f754f88fSGreg Clayton   s->Printf("  modtime = 0x%8.8x\n", header.modtime);
1034f754f88fSGreg Clayton   s->Printf("  symoff  = 0x%8.8x\n", header.symoff);
1035f754f88fSGreg Clayton   s->Printf("  nsyms   = 0x%8.8x\n", header.nsyms);
1036f754f88fSGreg Clayton   s->Printf("  hdrsize = 0x%4.4x\n", header.hdrsize);
1037f754f88fSGreg Clayton }
1038f754f88fSGreg Clayton 
1039f754f88fSGreg Clayton // DumpOptCOFFHeader
1040f754f88fSGreg Clayton //
1041f754f88fSGreg Clayton // Dump the optional COFF header to the specified output stream
1042b9c1b51eSKate Stone void ObjectFilePECOFF::DumpOptCOFFHeader(Stream *s,
1043b9c1b51eSKate Stone                                          const coff_opt_header_t &header) {
1044f754f88fSGreg Clayton   s->PutCString("Optional COFF Header\n");
1045f754f88fSGreg Clayton   s->Printf("  magic                   = 0x%4.4x\n", header.magic);
1046b9c1b51eSKate Stone   s->Printf("  major_linker_version    = 0x%2.2x\n",
1047b9c1b51eSKate Stone             header.major_linker_version);
1048b9c1b51eSKate Stone   s->Printf("  minor_linker_version    = 0x%2.2x\n",
1049b9c1b51eSKate Stone             header.minor_linker_version);
1050f754f88fSGreg Clayton   s->Printf("  code_size               = 0x%8.8x\n", header.code_size);
1051f754f88fSGreg Clayton   s->Printf("  data_size               = 0x%8.8x\n", header.data_size);
1052f754f88fSGreg Clayton   s->Printf("  bss_size                = 0x%8.8x\n", header.bss_size);
1053f754f88fSGreg Clayton   s->Printf("  entry                   = 0x%8.8x\n", header.entry);
1054f754f88fSGreg Clayton   s->Printf("  code_offset             = 0x%8.8x\n", header.code_offset);
1055f754f88fSGreg Clayton   s->Printf("  data_offset             = 0x%8.8x\n", header.data_offset);
1056b9c1b51eSKate Stone   s->Printf("  image_base              = 0x%16.16" PRIx64 "\n",
1057b9c1b51eSKate Stone             header.image_base);
1058f754f88fSGreg Clayton   s->Printf("  sect_alignment          = 0x%8.8x\n", header.sect_alignment);
1059f754f88fSGreg Clayton   s->Printf("  file_alignment          = 0x%8.8x\n", header.file_alignment);
1060b9c1b51eSKate Stone   s->Printf("  major_os_system_version = 0x%4.4x\n",
1061b9c1b51eSKate Stone             header.major_os_system_version);
1062b9c1b51eSKate Stone   s->Printf("  minor_os_system_version = 0x%4.4x\n",
1063b9c1b51eSKate Stone             header.minor_os_system_version);
1064b9c1b51eSKate Stone   s->Printf("  major_image_version     = 0x%4.4x\n",
1065b9c1b51eSKate Stone             header.major_image_version);
1066b9c1b51eSKate Stone   s->Printf("  minor_image_version     = 0x%4.4x\n",
1067b9c1b51eSKate Stone             header.minor_image_version);
1068b9c1b51eSKate Stone   s->Printf("  major_subsystem_version = 0x%4.4x\n",
1069b9c1b51eSKate Stone             header.major_subsystem_version);
1070b9c1b51eSKate Stone   s->Printf("  minor_subsystem_version = 0x%4.4x\n",
1071b9c1b51eSKate Stone             header.minor_subsystem_version);
1072f754f88fSGreg Clayton   s->Printf("  reserved1               = 0x%8.8x\n", header.reserved1);
1073f754f88fSGreg Clayton   s->Printf("  image_size              = 0x%8.8x\n", header.image_size);
1074f754f88fSGreg Clayton   s->Printf("  header_size             = 0x%8.8x\n", header.header_size);
107528469ca3SGreg Clayton   s->Printf("  checksum                = 0x%8.8x\n", header.checksum);
1076f754f88fSGreg Clayton   s->Printf("  subsystem               = 0x%4.4x\n", header.subsystem);
1077f754f88fSGreg Clayton   s->Printf("  dll_flags               = 0x%4.4x\n", header.dll_flags);
1078b9c1b51eSKate Stone   s->Printf("  stack_reserve_size      = 0x%16.16" PRIx64 "\n",
1079b9c1b51eSKate Stone             header.stack_reserve_size);
1080b9c1b51eSKate Stone   s->Printf("  stack_commit_size       = 0x%16.16" PRIx64 "\n",
1081b9c1b51eSKate Stone             header.stack_commit_size);
1082b9c1b51eSKate Stone   s->Printf("  heap_reserve_size       = 0x%16.16" PRIx64 "\n",
1083b9c1b51eSKate Stone             header.heap_reserve_size);
1084b9c1b51eSKate Stone   s->Printf("  heap_commit_size        = 0x%16.16" PRIx64 "\n",
1085b9c1b51eSKate Stone             header.heap_commit_size);
1086f754f88fSGreg Clayton   s->Printf("  loader_flags            = 0x%8.8x\n", header.loader_flags);
1087b9c1b51eSKate Stone   s->Printf("  num_data_dir_entries    = 0x%8.8x\n",
1088b9c1b51eSKate Stone             (uint32_t)header.data_dirs.size());
1089f754f88fSGreg Clayton   uint32_t i;
1090b9c1b51eSKate Stone   for (i = 0; i < header.data_dirs.size(); i++) {
1091b9c1b51eSKate Stone     s->Printf("  data_dirs[%2u] vmaddr = 0x%8.8x, vmsize = 0x%8.8x\n", i,
1092b9c1b51eSKate Stone               header.data_dirs[i].vmaddr, header.data_dirs[i].vmsize);
1093f754f88fSGreg Clayton   }
1094f754f88fSGreg Clayton }
1095f754f88fSGreg Clayton // DumpSectionHeader
1096f754f88fSGreg Clayton //
1097f754f88fSGreg Clayton // Dump a single ELF section header to the specified output stream
1098b9c1b51eSKate Stone void ObjectFilePECOFF::DumpSectionHeader(Stream *s,
1099b9c1b51eSKate Stone                                          const section_header_t &sh) {
1100adcd0268SBenjamin Kramer   std::string name = std::string(GetSectionName(sh));
1101b9c1b51eSKate 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 "
1102b9c1b51eSKate Stone             "0x%4.4x 0x%8.8x\n",
1103b9c1b51eSKate Stone             name.c_str(), sh.vmaddr, sh.vmsize, sh.offset, sh.size, sh.reloff,
1104b9c1b51eSKate Stone             sh.lineoff, sh.nreloc, sh.nline, sh.flags);
1105f754f88fSGreg Clayton }
1106f754f88fSGreg Clayton 
1107f754f88fSGreg Clayton // DumpSectionHeaders
1108f754f88fSGreg Clayton //
1109f754f88fSGreg Clayton // Dump all of the ELF section header to the specified output stream
1110b9c1b51eSKate Stone void ObjectFilePECOFF::DumpSectionHeaders(Stream *s) {
1111f754f88fSGreg Clayton 
1112f754f88fSGreg Clayton   s->PutCString("Section Headers\n");
1113b9c1b51eSKate Stone   s->PutCString("IDX  name             vm addr    vm size    file off   file "
1114b9c1b51eSKate Stone                 "size  reloc off  line off   nreloc nline  flags\n");
1115b9c1b51eSKate Stone   s->PutCString("==== ---------------- ---------- ---------- ---------- "
1116b9c1b51eSKate Stone                 "---------- ---------- ---------- ------ ------ ----------\n");
1117f754f88fSGreg Clayton 
1118f754f88fSGreg Clayton   uint32_t idx = 0;
1119f754f88fSGreg Clayton   SectionHeaderCollIter pos, end = m_sect_headers.end();
1120f754f88fSGreg Clayton 
1121b9c1b51eSKate Stone   for (pos = m_sect_headers.begin(); pos != end; ++pos, ++idx) {
1122f754f88fSGreg Clayton     s->Printf("[%2u] ", idx);
1123f754f88fSGreg Clayton     ObjectFilePECOFF::DumpSectionHeader(s, *pos);
1124f754f88fSGreg Clayton   }
1125f754f88fSGreg Clayton }
1126f754f88fSGreg Clayton 
1127037ed1beSAaron Smith // DumpDependentModules
1128037ed1beSAaron Smith //
1129037ed1beSAaron Smith // Dump all of the dependent modules to the specified output stream
1130037ed1beSAaron Smith void ObjectFilePECOFF::DumpDependentModules(lldb_private::Stream *s) {
1131037ed1beSAaron Smith   auto num_modules = ParseDependentModules();
1132037ed1beSAaron Smith   if (num_modules > 0) {
1133037ed1beSAaron Smith     s->PutCString("Dependent Modules\n");
1134037ed1beSAaron Smith     for (unsigned i = 0; i < num_modules; ++i) {
1135037ed1beSAaron Smith       auto spec = m_deps_filespec->GetFileSpecAtIndex(i);
1136037ed1beSAaron Smith       s->Printf("  %s\n", spec.GetFilename().GetCString());
1137037ed1beSAaron Smith     }
1138037ed1beSAaron Smith   }
1139037ed1beSAaron Smith }
1140037ed1beSAaron Smith 
1141fb3b3bd1SZachary Turner bool ObjectFilePECOFF::IsWindowsSubsystem() {
1142fb3b3bd1SZachary Turner   switch (m_coff_header_opt.subsystem) {
1143fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE:
1144fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI:
1145fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI:
1146fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE_WINDOWS:
1147fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
1148fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_XBOX:
1149fb3b3bd1SZachary Turner   case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION:
1150fb3b3bd1SZachary Turner     return true;
1151fb3b3bd1SZachary Turner   default:
1152fb3b3bd1SZachary Turner     return false;
1153fb3b3bd1SZachary Turner   }
1154fb3b3bd1SZachary Turner }
1155fb3b3bd1SZachary Turner 
1156f760f5aeSPavel Labath ArchSpec ObjectFilePECOFF::GetArchitecture() {
1157237ad974SCharles Davis   uint16_t machine = m_coff_header.machine;
1158b9c1b51eSKate Stone   switch (machine) {
1159f760f5aeSPavel Labath   default:
1160f760f5aeSPavel Labath     break;
1161237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_AMD64:
1162237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_I386:
1163237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_POWERPC:
1164237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_POWERPCFP:
1165237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_ARM:
11661108cb36SSaleem Abdulrasool   case llvm::COFF::IMAGE_FILE_MACHINE_ARMNT:
1167237ad974SCharles Davis   case llvm::COFF::IMAGE_FILE_MACHINE_THUMB:
1168638f072fSMartin Storsjo   case llvm::COFF::IMAGE_FILE_MACHINE_ARM64:
1169f760f5aeSPavel Labath     ArchSpec arch;
1170fb3b3bd1SZachary Turner     arch.SetArchitecture(eArchTypeCOFF, machine, LLDB_INVALID_CPUTYPE,
1171fb3b3bd1SZachary Turner                          IsWindowsSubsystem() ? llvm::Triple::Win32
1172fb3b3bd1SZachary Turner                                               : llvm::Triple::UnknownOS);
1173f760f5aeSPavel Labath     return arch;
1174237ad974SCharles Davis   }
1175f760f5aeSPavel Labath   return ArchSpec();
1176f754f88fSGreg Clayton }
1177f754f88fSGreg Clayton 
1178b9c1b51eSKate Stone ObjectFile::Type ObjectFilePECOFF::CalculateType() {
1179b9c1b51eSKate Stone   if (m_coff_header.machine != 0) {
1180237ad974SCharles Davis     if ((m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0)
1181f754f88fSGreg Clayton       return eTypeExecutable;
1182f754f88fSGreg Clayton     else
1183f754f88fSGreg Clayton       return eTypeSharedLibrary;
1184f754f88fSGreg Clayton   }
1185f754f88fSGreg Clayton   return eTypeExecutable;
1186f754f88fSGreg Clayton }
1187f754f88fSGreg Clayton 
1188b9c1b51eSKate Stone ObjectFile::Strata ObjectFilePECOFF::CalculateStrata() { return eStrataUser; }
1189