1 //===-- ObjectFilePECOFF.cpp ----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "ObjectFilePECOFF.h"
10 #include "PECallFrameInfo.h"
11 #include "WindowsMiniDump.h"
12
13 #include "lldb/Core/FileSpecList.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/ModuleSpec.h"
16 #include "lldb/Core/PluginManager.h"
17 #include "lldb/Core/Section.h"
18 #include "lldb/Core/StreamFile.h"
19 #include "lldb/Interpreter/OptionValueDictionary.h"
20 #include "lldb/Interpreter/OptionValueProperties.h"
21 #include "lldb/Symbol/ObjectFile.h"
22 #include "lldb/Target/Process.h"
23 #include "lldb/Target/SectionLoadList.h"
24 #include "lldb/Target/Target.h"
25 #include "lldb/Utility/ArchSpec.h"
26 #include "lldb/Utility/DataBufferHeap.h"
27 #include "lldb/Utility/FileSpec.h"
28 #include "lldb/Utility/LLDBLog.h"
29 #include "lldb/Utility/Log.h"
30 #include "lldb/Utility/StreamString.h"
31 #include "lldb/Utility/Timer.h"
32 #include "lldb/Utility/UUID.h"
33 #include "llvm/BinaryFormat/COFF.h"
34
35 #include "llvm/Object/COFFImportFile.h"
36 #include "llvm/Support/CRC.h"
37 #include "llvm/Support/Error.h"
38 #include "llvm/Support/Host.h"
39 #include "llvm/Support/MemoryBuffer.h"
40
41 #define IMAGE_DOS_SIGNATURE 0x5A4D // MZ
42 #define IMAGE_NT_SIGNATURE 0x00004550 // PE00
43 #define OPT_HEADER_MAGIC_PE32 0x010b
44 #define OPT_HEADER_MAGIC_PE32_PLUS 0x020b
45
46 using namespace lldb;
47 using namespace lldb_private;
48
49 LLDB_PLUGIN_DEFINE(ObjectFilePECOFF)
50
51 namespace {
52
53 static constexpr OptionEnumValueElement g_abi_enums[] = {
54 {
55 llvm::Triple::UnknownEnvironment,
56 "default",
57 "Use default target (if it is Windows) or MSVC",
58 },
59 {
60 llvm::Triple::MSVC,
61 "msvc",
62 "MSVC ABI",
63 },
64 {
65 llvm::Triple::GNU,
66 "gnu",
67 "MinGW / Itanium ABI",
68 },
69 };
70
71 #define LLDB_PROPERTIES_objectfilepecoff
72 #include "ObjectFilePECOFFProperties.inc"
73
74 enum {
75 #define LLDB_PROPERTIES_objectfilepecoff
76 #include "ObjectFilePECOFFPropertiesEnum.inc"
77 };
78
79 class PluginProperties : public Properties {
80 public:
GetSettingName()81 static ConstString GetSettingName() {
82 return ConstString(ObjectFilePECOFF::GetPluginNameStatic());
83 }
84
PluginProperties()85 PluginProperties() {
86 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
87 m_collection_sp->Initialize(g_objectfilepecoff_properties);
88 }
89
ABI() const90 llvm::Triple::EnvironmentType ABI() const {
91 return (llvm::Triple::EnvironmentType)
92 m_collection_sp->GetPropertyAtIndexAsEnumeration(
93 nullptr, ePropertyABI, llvm::Triple::UnknownEnvironment);
94 }
95
ModuleABIMap() const96 OptionValueDictionary *ModuleABIMap() const {
97 return m_collection_sp->GetPropertyAtIndexAsOptionValueDictionary(
98 nullptr, ePropertyModuleABIMap);
99 }
100 };
101
GetGlobalPluginProperties()102 static PluginProperties &GetGlobalPluginProperties() {
103 static PluginProperties g_settings;
104 return g_settings;
105 }
106
107 } // namespace
108
GetDebugLinkContents(const llvm::object::COFFObjectFile & coff_obj,std::string & gnu_debuglink_file,uint32_t & gnu_debuglink_crc)109 static bool GetDebugLinkContents(const llvm::object::COFFObjectFile &coff_obj,
110 std::string &gnu_debuglink_file,
111 uint32_t &gnu_debuglink_crc) {
112 static ConstString g_sect_name_gnu_debuglink(".gnu_debuglink");
113 for (const auto §ion : coff_obj.sections()) {
114 auto name = section.getName();
115 if (!name) {
116 llvm::consumeError(name.takeError());
117 continue;
118 }
119 if (*name == g_sect_name_gnu_debuglink.GetStringRef()) {
120 auto content = section.getContents();
121 if (!content) {
122 llvm::consumeError(content.takeError());
123 return false;
124 }
125 DataExtractor data(
126 content->data(), content->size(),
127 coff_obj.isLittleEndian() ? eByteOrderLittle : eByteOrderBig, 4);
128 lldb::offset_t gnu_debuglink_offset = 0;
129 gnu_debuglink_file = data.GetCStr(&gnu_debuglink_offset);
130 // Align to the next 4-byte offset
131 gnu_debuglink_offset = llvm::alignTo(gnu_debuglink_offset, 4);
132 data.GetU32(&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
133 return true;
134 }
135 }
136 return false;
137 }
138
GetCoffUUID(llvm::object::COFFObjectFile & coff_obj)139 static UUID GetCoffUUID(llvm::object::COFFObjectFile &coff_obj) {
140 const llvm::codeview::DebugInfo *pdb_info = nullptr;
141 llvm::StringRef pdb_file;
142
143 // First, prefer to use the PDB build id. LLD generates this even for mingw
144 // targets without PDB output, and it does not get stripped either.
145 if (!coff_obj.getDebugPDBInfo(pdb_info, pdb_file) && pdb_info) {
146 if (pdb_info->PDB70.CVSignature == llvm::OMF::Signature::PDB70) {
147 UUID::CvRecordPdb70 info;
148 memcpy(&info.Uuid, pdb_info->PDB70.Signature, sizeof(info.Uuid));
149 info.Age = pdb_info->PDB70.Age;
150 return UUID::fromCvRecord(info);
151 }
152 }
153
154 std::string gnu_debuglink_file;
155 uint32_t gnu_debuglink_crc;
156
157 // The GNU linker normally does not write a PDB build id (unless requested
158 // with the --build-id option), so we should fall back to using the crc
159 // from .gnu_debuglink if it exists, just like how ObjectFileELF does it.
160 if (!GetDebugLinkContents(coff_obj, gnu_debuglink_file, gnu_debuglink_crc)) {
161 // If there is no .gnu_debuglink section, then this may be an object
162 // containing DWARF debug info for .gnu_debuglink, so calculate the crc of
163 // the object itself.
164 auto raw_data = coff_obj.getData();
165 LLDB_SCOPED_TIMERF(
166 "Calculating module crc32 %s with size %" PRIu64 " KiB",
167 FileSpec(coff_obj.getFileName()).GetLastPathComponent().AsCString(),
168 static_cast<lldb::offset_t>(raw_data.size()) / 1024);
169 gnu_debuglink_crc = llvm::crc32(0, llvm::arrayRefFromStringRef(raw_data));
170 }
171 // Use 4 bytes of crc from the .gnu_debuglink section.
172 llvm::support::ulittle32_t data(gnu_debuglink_crc);
173 return UUID::fromData(&data, sizeof(data));
174 }
175
176 char ObjectFilePECOFF::ID;
177
Initialize()178 void ObjectFilePECOFF::Initialize() {
179 PluginManager::RegisterPlugin(GetPluginNameStatic(),
180 GetPluginDescriptionStatic(), CreateInstance,
181 CreateMemoryInstance, GetModuleSpecifications,
182 SaveCore, DebuggerInitialize);
183 }
184
DebuggerInitialize(Debugger & debugger)185 void ObjectFilePECOFF::DebuggerInitialize(Debugger &debugger) {
186 if (!PluginManager::GetSettingForObjectFilePlugin(
187 debugger, PluginProperties::GetSettingName())) {
188 const bool is_global_setting = true;
189 PluginManager::CreateSettingForObjectFilePlugin(
190 debugger, GetGlobalPluginProperties().GetValueProperties(),
191 ConstString("Properties for the PE/COFF object-file plug-in."),
192 is_global_setting);
193 }
194 }
195
Terminate()196 void ObjectFilePECOFF::Terminate() {
197 PluginManager::UnregisterPlugin(CreateInstance);
198 }
199
GetPluginDescriptionStatic()200 llvm::StringRef ObjectFilePECOFF::GetPluginDescriptionStatic() {
201 return "Portable Executable and Common Object File Format object file reader "
202 "(32 and 64 bit)";
203 }
204
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)205 ObjectFile *ObjectFilePECOFF::CreateInstance(
206 const lldb::ModuleSP &module_sp, DataBufferSP data_sp,
207 lldb::offset_t data_offset, const lldb_private::FileSpec *file_p,
208 lldb::offset_t file_offset, lldb::offset_t length) {
209 FileSpec file = file_p ? *file_p : FileSpec();
210 if (!data_sp) {
211 data_sp = MapFileData(file, length, file_offset);
212 if (!data_sp)
213 return nullptr;
214 data_offset = 0;
215 }
216
217 if (!ObjectFilePECOFF::MagicBytesMatch(data_sp))
218 return nullptr;
219
220 // Update the data to contain the entire file if it doesn't already
221 if (data_sp->GetByteSize() < length) {
222 data_sp = MapFileData(file, length, file_offset);
223 if (!data_sp)
224 return nullptr;
225 }
226
227 auto objfile_up = std::make_unique<ObjectFilePECOFF>(
228 module_sp, data_sp, data_offset, file_p, file_offset, length);
229 if (!objfile_up || !objfile_up->ParseHeader())
230 return nullptr;
231
232 // Cache coff binary.
233 if (!objfile_up->CreateBinary())
234 return nullptr;
235 return objfile_up.release();
236 }
237
CreateMemoryInstance(const lldb::ModuleSP & module_sp,lldb::WritableDataBufferSP data_sp,const lldb::ProcessSP & process_sp,lldb::addr_t header_addr)238 ObjectFile *ObjectFilePECOFF::CreateMemoryInstance(
239 const lldb::ModuleSP &module_sp, lldb::WritableDataBufferSP data_sp,
240 const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) {
241 if (!data_sp || !ObjectFilePECOFF::MagicBytesMatch(data_sp))
242 return nullptr;
243 auto objfile_up = std::make_unique<ObjectFilePECOFF>(
244 module_sp, data_sp, process_sp, header_addr);
245 if (objfile_up.get() && objfile_up->ParseHeader()) {
246 return objfile_up.release();
247 }
248 return nullptr;
249 }
250
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)251 size_t ObjectFilePECOFF::GetModuleSpecifications(
252 const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
253 lldb::offset_t data_offset, lldb::offset_t file_offset,
254 lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
255 const size_t initial_count = specs.GetSize();
256 if (!data_sp || !ObjectFilePECOFF::MagicBytesMatch(data_sp))
257 return initial_count;
258
259 Log *log = GetLog(LLDBLog::Object);
260
261 if (data_sp->GetByteSize() < length)
262 if (DataBufferSP full_sp = MapFileData(file, -1, file_offset))
263 data_sp = std::move(full_sp);
264 auto binary = llvm::object::createBinary(llvm::MemoryBufferRef(
265 toStringRef(data_sp->GetData()), file.GetFilename().GetStringRef()));
266
267 if (!binary) {
268 LLDB_LOG_ERROR(log, binary.takeError(),
269 "Failed to create binary for file ({1}): {0}", file);
270 return initial_count;
271 }
272
273 auto *COFFObj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary->get());
274 if (!COFFObj)
275 return initial_count;
276
277 ModuleSpec module_spec(file);
278 ArchSpec &spec = module_spec.GetArchitecture();
279 lldb_private::UUID &uuid = module_spec.GetUUID();
280 if (!uuid.IsValid())
281 uuid = GetCoffUUID(*COFFObj);
282
283 static llvm::Triple::EnvironmentType default_env = [] {
284 auto def_target = llvm::Triple(
285 llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple()));
286 if (def_target.getOS() == llvm::Triple::Win32 &&
287 def_target.getEnvironment() != llvm::Triple::UnknownEnvironment)
288 return def_target.getEnvironment();
289 return llvm::Triple::MSVC;
290 }();
291
292 // Check for a module-specific override.
293 OptionValueSP module_env_option;
294 const auto *map = GetGlobalPluginProperties().ModuleABIMap();
295 if (map->GetNumValues() > 0) {
296 // Step 1: Try with the exact file name.
297 auto name = file.GetLastPathComponent();
298 module_env_option = map->GetValueForKey(name);
299 if (!module_env_option) {
300 // Step 2: Try with the file name in lowercase.
301 auto name_lower = name.GetStringRef().lower();
302 module_env_option =
303 map->GetValueForKey(ConstString(llvm::StringRef(name_lower)));
304 }
305 if (!module_env_option) {
306 // Step 3: Try with the file name with ".debug" suffix stripped.
307 auto name_stripped = name.GetStringRef();
308 if (name_stripped.consume_back_insensitive(".debug")) {
309 module_env_option = map->GetValueForKey(ConstString(name_stripped));
310 if (!module_env_option) {
311 // Step 4: Try with the file name in lowercase with ".debug" suffix
312 // stripped.
313 auto name_lower = name_stripped.lower();
314 module_env_option =
315 map->GetValueForKey(ConstString(llvm::StringRef(name_lower)));
316 }
317 }
318 }
319 }
320 llvm::Triple::EnvironmentType env;
321 if (module_env_option)
322 env =
323 (llvm::Triple::EnvironmentType)module_env_option->GetEnumerationValue();
324 else
325 env = GetGlobalPluginProperties().ABI();
326
327 if (env == llvm::Triple::UnknownEnvironment)
328 env = default_env;
329
330 switch (COFFObj->getMachine()) {
331 case MachineAmd64:
332 spec.SetTriple("x86_64-pc-windows");
333 spec.GetTriple().setEnvironment(env);
334 specs.Append(module_spec);
335 break;
336 case MachineX86:
337 spec.SetTriple("i386-pc-windows");
338 spec.GetTriple().setEnvironment(env);
339 specs.Append(module_spec);
340 break;
341 case MachineArmNt:
342 spec.SetTriple("armv7-pc-windows");
343 spec.GetTriple().setEnvironment(env);
344 specs.Append(module_spec);
345 break;
346 case MachineArm64:
347 spec.SetTriple("aarch64-pc-windows");
348 spec.GetTriple().setEnvironment(env);
349 specs.Append(module_spec);
350 break;
351 default:
352 break;
353 }
354
355 return specs.GetSize() - initial_count;
356 }
357
SaveCore(const lldb::ProcessSP & process_sp,const lldb_private::FileSpec & outfile,lldb::SaveCoreStyle & core_style,lldb_private::Status & error)358 bool ObjectFilePECOFF::SaveCore(const lldb::ProcessSP &process_sp,
359 const lldb_private::FileSpec &outfile,
360 lldb::SaveCoreStyle &core_style,
361 lldb_private::Status &error) {
362 core_style = eSaveCoreFull;
363 return SaveMiniDump(process_sp, outfile, error);
364 }
365
MagicBytesMatch(DataBufferSP data_sp)366 bool ObjectFilePECOFF::MagicBytesMatch(DataBufferSP data_sp) {
367 DataExtractor data(data_sp, eByteOrderLittle, 4);
368 lldb::offset_t offset = 0;
369 uint16_t magic = data.GetU16(&offset);
370 return magic == IMAGE_DOS_SIGNATURE;
371 }
372
MapSymbolType(uint16_t coff_symbol_type)373 lldb::SymbolType ObjectFilePECOFF::MapSymbolType(uint16_t coff_symbol_type) {
374 // TODO: We need to complete this mapping of COFF symbol types to LLDB ones.
375 // For now, here's a hack to make sure our function have types.
376 const auto complex_type =
377 coff_symbol_type >> llvm::COFF::SCT_COMPLEX_TYPE_SHIFT;
378 if (complex_type == llvm::COFF::IMAGE_SYM_DTYPE_FUNCTION) {
379 return lldb::eSymbolTypeCode;
380 }
381 return lldb::eSymbolTypeInvalid;
382 }
383
CreateBinary()384 bool ObjectFilePECOFF::CreateBinary() {
385 if (m_binary)
386 return true;
387
388 Log *log = GetLog(LLDBLog::Object);
389
390 auto binary = llvm::object::createBinary(llvm::MemoryBufferRef(
391 toStringRef(m_data.GetData()), m_file.GetFilename().GetStringRef()));
392 if (!binary) {
393 LLDB_LOG_ERROR(log, binary.takeError(),
394 "Failed to create binary for file ({1}): {0}", m_file);
395 return false;
396 }
397
398 // Make sure we only handle COFF format.
399 m_binary =
400 llvm::unique_dyn_cast<llvm::object::COFFObjectFile>(std::move(*binary));
401 if (!m_binary)
402 return false;
403
404 LLDB_LOG(log, "this = {0}, module = {1} ({2}), file = {3}, binary = {4}",
405 this, GetModule().get(), GetModule()->GetSpecificationDescription(),
406 m_file.GetPath(), m_binary.get());
407 return true;
408 }
409
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)410 ObjectFilePECOFF::ObjectFilePECOFF(const lldb::ModuleSP &module_sp,
411 DataBufferSP data_sp,
412 lldb::offset_t data_offset,
413 const FileSpec *file,
414 lldb::offset_t file_offset,
415 lldb::offset_t length)
416 : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
417 m_dos_header(), m_coff_header(), m_coff_header_opt(), m_sect_headers(),
418 m_image_base(LLDB_INVALID_ADDRESS), m_entry_point_address(),
419 m_deps_filespec() {}
420
ObjectFilePECOFF(const lldb::ModuleSP & module_sp,WritableDataBufferSP header_data_sp,const lldb::ProcessSP & process_sp,addr_t header_addr)421 ObjectFilePECOFF::ObjectFilePECOFF(const lldb::ModuleSP &module_sp,
422 WritableDataBufferSP header_data_sp,
423 const lldb::ProcessSP &process_sp,
424 addr_t header_addr)
425 : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
426 m_dos_header(), m_coff_header(), m_coff_header_opt(), m_sect_headers(),
427 m_image_base(LLDB_INVALID_ADDRESS), m_entry_point_address(),
428 m_deps_filespec() {}
429
430 ObjectFilePECOFF::~ObjectFilePECOFF() = default;
431
ParseHeader()432 bool ObjectFilePECOFF::ParseHeader() {
433 ModuleSP module_sp(GetModule());
434 if (module_sp) {
435 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
436 m_sect_headers.clear();
437 m_data.SetByteOrder(eByteOrderLittle);
438 lldb::offset_t offset = 0;
439
440 if (ParseDOSHeader(m_data, m_dos_header)) {
441 offset = m_dos_header.e_lfanew;
442 uint32_t pe_signature = m_data.GetU32(&offset);
443 if (pe_signature != IMAGE_NT_SIGNATURE)
444 return false;
445 if (ParseCOFFHeader(m_data, &offset, m_coff_header)) {
446 if (m_coff_header.hdrsize > 0)
447 ParseCOFFOptionalHeader(&offset);
448 ParseSectionHeaders(offset);
449 }
450 m_data.SetAddressByteSize(GetAddressByteSize());
451 return true;
452 }
453 }
454 return false;
455 }
456
SetLoadAddress(Target & target,addr_t value,bool value_is_offset)457 bool ObjectFilePECOFF::SetLoadAddress(Target &target, addr_t value,
458 bool value_is_offset) {
459 bool changed = false;
460 ModuleSP module_sp = GetModule();
461 if (module_sp) {
462 size_t num_loaded_sections = 0;
463 SectionList *section_list = GetSectionList();
464 if (section_list) {
465 if (!value_is_offset) {
466 value -= m_image_base;
467 }
468
469 const size_t num_sections = section_list->GetSize();
470 size_t sect_idx = 0;
471
472 for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
473 // Iterate through the object file sections to find all of the sections
474 // that have SHF_ALLOC in their flag bits.
475 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
476 if (section_sp && !section_sp->IsThreadSpecific()) {
477 if (target.GetSectionLoadList().SetSectionLoadAddress(
478 section_sp, section_sp->GetFileAddress() + value))
479 ++num_loaded_sections;
480 }
481 }
482 changed = num_loaded_sections > 0;
483 }
484 }
485 return changed;
486 }
487
GetByteOrder() const488 ByteOrder ObjectFilePECOFF::GetByteOrder() const { return eByteOrderLittle; }
489
IsExecutable() const490 bool ObjectFilePECOFF::IsExecutable() const {
491 return (m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0;
492 }
493
GetAddressByteSize() const494 uint32_t ObjectFilePECOFF::GetAddressByteSize() const {
495 if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32_PLUS)
496 return 8;
497 else if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32)
498 return 4;
499 return 4;
500 }
501
502 // NeedsEndianSwap
503 //
504 // Return true if an endian swap needs to occur when extracting data from this
505 // file.
NeedsEndianSwap() const506 bool ObjectFilePECOFF::NeedsEndianSwap() const {
507 #if defined(__LITTLE_ENDIAN__)
508 return false;
509 #else
510 return true;
511 #endif
512 }
513 // ParseDOSHeader
ParseDOSHeader(DataExtractor & data,dos_header_t & dos_header)514 bool ObjectFilePECOFF::ParseDOSHeader(DataExtractor &data,
515 dos_header_t &dos_header) {
516 bool success = false;
517 lldb::offset_t offset = 0;
518 success = data.ValidOffsetForDataOfSize(0, sizeof(dos_header));
519
520 if (success) {
521 dos_header.e_magic = data.GetU16(&offset); // Magic number
522 success = dos_header.e_magic == IMAGE_DOS_SIGNATURE;
523
524 if (success) {
525 dos_header.e_cblp = data.GetU16(&offset); // Bytes on last page of file
526 dos_header.e_cp = data.GetU16(&offset); // Pages in file
527 dos_header.e_crlc = data.GetU16(&offset); // Relocations
528 dos_header.e_cparhdr =
529 data.GetU16(&offset); // Size of header in paragraphs
530 dos_header.e_minalloc =
531 data.GetU16(&offset); // Minimum extra paragraphs needed
532 dos_header.e_maxalloc =
533 data.GetU16(&offset); // Maximum extra paragraphs needed
534 dos_header.e_ss = data.GetU16(&offset); // Initial (relative) SS value
535 dos_header.e_sp = data.GetU16(&offset); // Initial SP value
536 dos_header.e_csum = data.GetU16(&offset); // Checksum
537 dos_header.e_ip = data.GetU16(&offset); // Initial IP value
538 dos_header.e_cs = data.GetU16(&offset); // Initial (relative) CS value
539 dos_header.e_lfarlc =
540 data.GetU16(&offset); // File address of relocation table
541 dos_header.e_ovno = data.GetU16(&offset); // Overlay number
542
543 dos_header.e_res[0] = data.GetU16(&offset); // Reserved words
544 dos_header.e_res[1] = data.GetU16(&offset); // Reserved words
545 dos_header.e_res[2] = data.GetU16(&offset); // Reserved words
546 dos_header.e_res[3] = data.GetU16(&offset); // Reserved words
547
548 dos_header.e_oemid =
549 data.GetU16(&offset); // OEM identifier (for e_oeminfo)
550 dos_header.e_oeminfo =
551 data.GetU16(&offset); // OEM information; e_oemid specific
552 dos_header.e_res2[0] = data.GetU16(&offset); // Reserved words
553 dos_header.e_res2[1] = data.GetU16(&offset); // Reserved words
554 dos_header.e_res2[2] = data.GetU16(&offset); // Reserved words
555 dos_header.e_res2[3] = data.GetU16(&offset); // Reserved words
556 dos_header.e_res2[4] = data.GetU16(&offset); // Reserved words
557 dos_header.e_res2[5] = data.GetU16(&offset); // Reserved words
558 dos_header.e_res2[6] = data.GetU16(&offset); // Reserved words
559 dos_header.e_res2[7] = data.GetU16(&offset); // Reserved words
560 dos_header.e_res2[8] = data.GetU16(&offset); // Reserved words
561 dos_header.e_res2[9] = data.GetU16(&offset); // Reserved words
562
563 dos_header.e_lfanew =
564 data.GetU32(&offset); // File address of new exe header
565 }
566 }
567 if (!success)
568 memset(&dos_header, 0, sizeof(dos_header));
569 return success;
570 }
571
572 // ParserCOFFHeader
ParseCOFFHeader(DataExtractor & data,lldb::offset_t * offset_ptr,coff_header_t & coff_header)573 bool ObjectFilePECOFF::ParseCOFFHeader(DataExtractor &data,
574 lldb::offset_t *offset_ptr,
575 coff_header_t &coff_header) {
576 bool success =
577 data.ValidOffsetForDataOfSize(*offset_ptr, sizeof(coff_header));
578 if (success) {
579 coff_header.machine = data.GetU16(offset_ptr);
580 coff_header.nsects = data.GetU16(offset_ptr);
581 coff_header.modtime = data.GetU32(offset_ptr);
582 coff_header.symoff = data.GetU32(offset_ptr);
583 coff_header.nsyms = data.GetU32(offset_ptr);
584 coff_header.hdrsize = data.GetU16(offset_ptr);
585 coff_header.flags = data.GetU16(offset_ptr);
586 }
587 if (!success)
588 memset(&coff_header, 0, sizeof(coff_header));
589 return success;
590 }
591
ParseCOFFOptionalHeader(lldb::offset_t * offset_ptr)592 bool ObjectFilePECOFF::ParseCOFFOptionalHeader(lldb::offset_t *offset_ptr) {
593 bool success = false;
594 const lldb::offset_t end_offset = *offset_ptr + m_coff_header.hdrsize;
595 if (*offset_ptr < end_offset) {
596 success = true;
597 m_coff_header_opt.magic = m_data.GetU16(offset_ptr);
598 m_coff_header_opt.major_linker_version = m_data.GetU8(offset_ptr);
599 m_coff_header_opt.minor_linker_version = m_data.GetU8(offset_ptr);
600 m_coff_header_opt.code_size = m_data.GetU32(offset_ptr);
601 m_coff_header_opt.data_size = m_data.GetU32(offset_ptr);
602 m_coff_header_opt.bss_size = m_data.GetU32(offset_ptr);
603 m_coff_header_opt.entry = m_data.GetU32(offset_ptr);
604 m_coff_header_opt.code_offset = m_data.GetU32(offset_ptr);
605
606 const uint32_t addr_byte_size = GetAddressByteSize();
607
608 if (*offset_ptr < end_offset) {
609 if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32) {
610 // PE32 only
611 m_coff_header_opt.data_offset = m_data.GetU32(offset_ptr);
612 } else
613 m_coff_header_opt.data_offset = 0;
614
615 if (*offset_ptr < end_offset) {
616 m_coff_header_opt.image_base =
617 m_data.GetMaxU64(offset_ptr, addr_byte_size);
618 m_coff_header_opt.sect_alignment = m_data.GetU32(offset_ptr);
619 m_coff_header_opt.file_alignment = m_data.GetU32(offset_ptr);
620 m_coff_header_opt.major_os_system_version = m_data.GetU16(offset_ptr);
621 m_coff_header_opt.minor_os_system_version = m_data.GetU16(offset_ptr);
622 m_coff_header_opt.major_image_version = m_data.GetU16(offset_ptr);
623 m_coff_header_opt.minor_image_version = m_data.GetU16(offset_ptr);
624 m_coff_header_opt.major_subsystem_version = m_data.GetU16(offset_ptr);
625 m_coff_header_opt.minor_subsystem_version = m_data.GetU16(offset_ptr);
626 m_coff_header_opt.reserved1 = m_data.GetU32(offset_ptr);
627 m_coff_header_opt.image_size = m_data.GetU32(offset_ptr);
628 m_coff_header_opt.header_size = m_data.GetU32(offset_ptr);
629 m_coff_header_opt.checksum = m_data.GetU32(offset_ptr);
630 m_coff_header_opt.subsystem = m_data.GetU16(offset_ptr);
631 m_coff_header_opt.dll_flags = m_data.GetU16(offset_ptr);
632 m_coff_header_opt.stack_reserve_size =
633 m_data.GetMaxU64(offset_ptr, addr_byte_size);
634 m_coff_header_opt.stack_commit_size =
635 m_data.GetMaxU64(offset_ptr, addr_byte_size);
636 m_coff_header_opt.heap_reserve_size =
637 m_data.GetMaxU64(offset_ptr, addr_byte_size);
638 m_coff_header_opt.heap_commit_size =
639 m_data.GetMaxU64(offset_ptr, addr_byte_size);
640 m_coff_header_opt.loader_flags = m_data.GetU32(offset_ptr);
641 uint32_t num_data_dir_entries = m_data.GetU32(offset_ptr);
642 m_coff_header_opt.data_dirs.clear();
643 m_coff_header_opt.data_dirs.resize(num_data_dir_entries);
644 uint32_t i;
645 for (i = 0; i < num_data_dir_entries; i++) {
646 m_coff_header_opt.data_dirs[i].vmaddr = m_data.GetU32(offset_ptr);
647 m_coff_header_opt.data_dirs[i].vmsize = m_data.GetU32(offset_ptr);
648 }
649
650 m_image_base = m_coff_header_opt.image_base;
651 }
652 }
653 }
654 // Make sure we are on track for section data which follows
655 *offset_ptr = end_offset;
656 return success;
657 }
658
GetRVA(const Address & addr) const659 uint32_t ObjectFilePECOFF::GetRVA(const Address &addr) const {
660 return addr.GetFileAddress() - m_image_base;
661 }
662
GetAddress(uint32_t rva)663 Address ObjectFilePECOFF::GetAddress(uint32_t rva) {
664 SectionList *sect_list = GetSectionList();
665 if (!sect_list)
666 return Address(GetFileAddress(rva));
667
668 return Address(GetFileAddress(rva), sect_list);
669 }
670
GetFileAddress(uint32_t rva) const671 lldb::addr_t ObjectFilePECOFF::GetFileAddress(uint32_t rva) const {
672 return m_image_base + rva;
673 }
674
ReadImageData(uint32_t offset,size_t size)675 DataExtractor ObjectFilePECOFF::ReadImageData(uint32_t offset, size_t size) {
676 if (!size)
677 return {};
678
679 if (m_data.ValidOffsetForDataOfSize(offset, size))
680 return DataExtractor(m_data, offset, size);
681
682 ProcessSP process_sp(m_process_wp.lock());
683 DataExtractor data;
684 if (process_sp) {
685 auto data_up = std::make_unique<DataBufferHeap>(size, 0);
686 Status readmem_error;
687 size_t bytes_read =
688 process_sp->ReadMemory(m_image_base + offset, data_up->GetBytes(),
689 data_up->GetByteSize(), readmem_error);
690 if (bytes_read == size) {
691 DataBufferSP buffer_sp(data_up.release());
692 data.SetData(buffer_sp, 0, buffer_sp->GetByteSize());
693 }
694 }
695 return data;
696 }
697
ReadImageDataByRVA(uint32_t rva,size_t size)698 DataExtractor ObjectFilePECOFF::ReadImageDataByRVA(uint32_t rva, size_t size) {
699 Address addr = GetAddress(rva);
700 SectionSP sect = addr.GetSection();
701 if (!sect)
702 return {};
703 rva = sect->GetFileOffset() + addr.GetOffset();
704
705 return ReadImageData(rva, size);
706 }
707
708 // ParseSectionHeaders
ParseSectionHeaders(uint32_t section_header_data_offset)709 bool ObjectFilePECOFF::ParseSectionHeaders(
710 uint32_t section_header_data_offset) {
711 const uint32_t nsects = m_coff_header.nsects;
712 m_sect_headers.clear();
713
714 if (nsects > 0) {
715 const size_t section_header_byte_size = nsects * sizeof(section_header_t);
716 DataExtractor section_header_data =
717 ReadImageData(section_header_data_offset, section_header_byte_size);
718
719 lldb::offset_t offset = 0;
720 if (section_header_data.ValidOffsetForDataOfSize(
721 offset, section_header_byte_size)) {
722 m_sect_headers.resize(nsects);
723
724 for (uint32_t idx = 0; idx < nsects; ++idx) {
725 const void *name_data = section_header_data.GetData(&offset, 8);
726 if (name_data) {
727 memcpy(m_sect_headers[idx].name, name_data, 8);
728 m_sect_headers[idx].vmsize = section_header_data.GetU32(&offset);
729 m_sect_headers[idx].vmaddr = section_header_data.GetU32(&offset);
730 m_sect_headers[idx].size = section_header_data.GetU32(&offset);
731 m_sect_headers[idx].offset = section_header_data.GetU32(&offset);
732 m_sect_headers[idx].reloff = section_header_data.GetU32(&offset);
733 m_sect_headers[idx].lineoff = section_header_data.GetU32(&offset);
734 m_sect_headers[idx].nreloc = section_header_data.GetU16(&offset);
735 m_sect_headers[idx].nline = section_header_data.GetU16(&offset);
736 m_sect_headers[idx].flags = section_header_data.GetU32(&offset);
737 }
738 }
739 }
740 }
741
742 return !m_sect_headers.empty();
743 }
744
GetSectionName(const section_header_t & sect)745 llvm::StringRef ObjectFilePECOFF::GetSectionName(const section_header_t §) {
746 llvm::StringRef hdr_name(sect.name, llvm::array_lengthof(sect.name));
747 hdr_name = hdr_name.split('\0').first;
748 if (hdr_name.consume_front("/")) {
749 lldb::offset_t stroff;
750 if (!to_integer(hdr_name, stroff, 10))
751 return "";
752 lldb::offset_t string_file_offset =
753 m_coff_header.symoff + (m_coff_header.nsyms * 18) + stroff;
754 if (const char *name = m_data.GetCStr(&string_file_offset))
755 return name;
756 return "";
757 }
758 return hdr_name;
759 }
760
ParseSymtab(Symtab & symtab)761 void ObjectFilePECOFF::ParseSymtab(Symtab &symtab) {
762 SectionList *sect_list = GetSectionList();
763 const uint32_t num_syms = m_coff_header.nsyms;
764 if (m_file && num_syms > 0 && m_coff_header.symoff > 0) {
765 const uint32_t symbol_size = 18;
766 const size_t symbol_data_size = num_syms * symbol_size;
767 // Include the 4-byte string table size at the end of the symbols
768 DataExtractor symtab_data =
769 ReadImageData(m_coff_header.symoff, symbol_data_size + 4);
770 lldb::offset_t offset = symbol_data_size;
771 const uint32_t strtab_size = symtab_data.GetU32(&offset);
772 if (strtab_size > 0) {
773 DataExtractor strtab_data = ReadImageData(
774 m_coff_header.symoff + symbol_data_size, strtab_size);
775
776 offset = 0;
777 std::string symbol_name;
778 Symbol *symbols = symtab.Resize(num_syms);
779 for (uint32_t i = 0; i < num_syms; ++i) {
780 coff_symbol_t symbol;
781 const uint32_t symbol_offset = offset;
782 const char *symbol_name_cstr = nullptr;
783 // If the first 4 bytes of the symbol string are zero, then they
784 // are followed by a 4-byte string table offset. Else these
785 // 8 bytes contain the symbol name
786 if (symtab_data.GetU32(&offset) == 0) {
787 // Long string that doesn't fit into the symbol table name, so
788 // now we must read the 4 byte string table offset
789 uint32_t strtab_offset = symtab_data.GetU32(&offset);
790 symbol_name_cstr = strtab_data.PeekCStr(strtab_offset);
791 symbol_name.assign(symbol_name_cstr);
792 } else {
793 // Short string that fits into the symbol table name which is 8
794 // bytes
795 offset += sizeof(symbol.name) - 4; // Skip remaining
796 symbol_name_cstr = symtab_data.PeekCStr(symbol_offset);
797 if (symbol_name_cstr == nullptr)
798 break;
799 symbol_name.assign(symbol_name_cstr, sizeof(symbol.name));
800 }
801 symbol.value = symtab_data.GetU32(&offset);
802 symbol.sect = symtab_data.GetU16(&offset);
803 symbol.type = symtab_data.GetU16(&offset);
804 symbol.storage = symtab_data.GetU8(&offset);
805 symbol.naux = symtab_data.GetU8(&offset);
806 symbols[i].GetMangled().SetValue(ConstString(symbol_name.c_str()));
807 if ((int16_t)symbol.sect >= 1) {
808 Address symbol_addr(sect_list->FindSectionByID(symbol.sect),
809 symbol.value);
810 symbols[i].GetAddressRef() = symbol_addr;
811 symbols[i].SetType(MapSymbolType(symbol.type));
812 }
813
814 if (symbol.naux > 0) {
815 i += symbol.naux;
816 offset += symbol.naux * symbol_size;
817 }
818 }
819 }
820 }
821
822 // Read export header
823 if (coff_data_dir_export_table < m_coff_header_opt.data_dirs.size() &&
824 m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmsize > 0 &&
825 m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr > 0) {
826 export_directory_entry export_table;
827 uint32_t data_start =
828 m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr;
829
830 DataExtractor symtab_data = ReadImageDataByRVA(
831 data_start, m_coff_header_opt.data_dirs[0].vmsize);
832 lldb::offset_t offset = 0;
833
834 // Read export_table header
835 export_table.characteristics = symtab_data.GetU32(&offset);
836 export_table.time_date_stamp = symtab_data.GetU32(&offset);
837 export_table.major_version = symtab_data.GetU16(&offset);
838 export_table.minor_version = symtab_data.GetU16(&offset);
839 export_table.name = symtab_data.GetU32(&offset);
840 export_table.base = symtab_data.GetU32(&offset);
841 export_table.number_of_functions = symtab_data.GetU32(&offset);
842 export_table.number_of_names = symtab_data.GetU32(&offset);
843 export_table.address_of_functions = symtab_data.GetU32(&offset);
844 export_table.address_of_names = symtab_data.GetU32(&offset);
845 export_table.address_of_name_ordinals = symtab_data.GetU32(&offset);
846
847 bool has_ordinal = export_table.address_of_name_ordinals != 0;
848
849 lldb::offset_t name_offset = export_table.address_of_names - data_start;
850 lldb::offset_t name_ordinal_offset =
851 export_table.address_of_name_ordinals - data_start;
852
853 Symbol *symbols = symtab.Resize(export_table.number_of_names);
854
855 std::string symbol_name;
856
857 // Read each export table entry
858 for (size_t i = 0; i < export_table.number_of_names; ++i) {
859 uint32_t name_ordinal =
860 has_ordinal ? symtab_data.GetU16(&name_ordinal_offset) : i;
861 uint32_t name_address = symtab_data.GetU32(&name_offset);
862
863 const char *symbol_name_cstr =
864 symtab_data.PeekCStr(name_address - data_start);
865 symbol_name.assign(symbol_name_cstr);
866
867 lldb::offset_t function_offset = export_table.address_of_functions -
868 data_start +
869 sizeof(uint32_t) * name_ordinal;
870 uint32_t function_rva = symtab_data.GetU32(&function_offset);
871
872 Address symbol_addr(m_coff_header_opt.image_base + function_rva,
873 sect_list);
874 symbols[i].GetMangled().SetValue(ConstString(symbol_name.c_str()));
875 symbols[i].GetAddressRef() = symbol_addr;
876 symbols[i].SetType(lldb::eSymbolTypeCode);
877 symbols[i].SetDebug(true);
878 }
879 }
880 }
881
CreateCallFrameInfo()882 std::unique_ptr<CallFrameInfo> ObjectFilePECOFF::CreateCallFrameInfo() {
883 if (coff_data_dir_exception_table >= m_coff_header_opt.data_dirs.size())
884 return {};
885
886 data_directory data_dir_exception =
887 m_coff_header_opt.data_dirs[coff_data_dir_exception_table];
888 if (!data_dir_exception.vmaddr)
889 return {};
890
891 if (m_coff_header.machine != llvm::COFF::IMAGE_FILE_MACHINE_AMD64)
892 return {};
893
894 return std::make_unique<PECallFrameInfo>(*this, data_dir_exception.vmaddr,
895 data_dir_exception.vmsize);
896 }
897
IsStripped()898 bool ObjectFilePECOFF::IsStripped() {
899 // TODO: determine this for COFF
900 return false;
901 }
902
GetSectionType(llvm::StringRef sect_name,const section_header_t & sect)903 SectionType ObjectFilePECOFF::GetSectionType(llvm::StringRef sect_name,
904 const section_header_t §) {
905 ConstString const_sect_name(sect_name);
906 static ConstString g_code_sect_name(".code");
907 static ConstString g_CODE_sect_name("CODE");
908 static ConstString g_data_sect_name(".data");
909 static ConstString g_DATA_sect_name("DATA");
910 static ConstString g_bss_sect_name(".bss");
911 static ConstString g_BSS_sect_name("BSS");
912
913 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_CODE &&
914 ((const_sect_name == g_code_sect_name) ||
915 (const_sect_name == g_CODE_sect_name))) {
916 return eSectionTypeCode;
917 }
918 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA &&
919 ((const_sect_name == g_data_sect_name) ||
920 (const_sect_name == g_DATA_sect_name))) {
921 if (sect.size == 0 && sect.offset == 0)
922 return eSectionTypeZeroFill;
923 else
924 return eSectionTypeData;
925 }
926 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA &&
927 ((const_sect_name == g_bss_sect_name) ||
928 (const_sect_name == g_BSS_sect_name))) {
929 if (sect.size == 0)
930 return eSectionTypeZeroFill;
931 else
932 return eSectionTypeData;
933 }
934
935 SectionType section_type =
936 llvm::StringSwitch<SectionType>(sect_name)
937 .Case(".debug", eSectionTypeDebug)
938 .Case(".stabstr", eSectionTypeDataCString)
939 .Case(".reloc", eSectionTypeOther)
940 .Case(".debug_abbrev", eSectionTypeDWARFDebugAbbrev)
941 .Case(".debug_aranges", eSectionTypeDWARFDebugAranges)
942 .Case(".debug_frame", eSectionTypeDWARFDebugFrame)
943 .Case(".debug_info", eSectionTypeDWARFDebugInfo)
944 .Case(".debug_line", eSectionTypeDWARFDebugLine)
945 .Case(".debug_loc", eSectionTypeDWARFDebugLoc)
946 .Case(".debug_loclists", eSectionTypeDWARFDebugLocLists)
947 .Case(".debug_macinfo", eSectionTypeDWARFDebugMacInfo)
948 .Case(".debug_names", eSectionTypeDWARFDebugNames)
949 .Case(".debug_pubnames", eSectionTypeDWARFDebugPubNames)
950 .Case(".debug_pubtypes", eSectionTypeDWARFDebugPubTypes)
951 .Case(".debug_ranges", eSectionTypeDWARFDebugRanges)
952 .Case(".debug_str", eSectionTypeDWARFDebugStr)
953 .Case(".debug_types", eSectionTypeDWARFDebugTypes)
954 // .eh_frame can be truncated to 8 chars.
955 .Cases(".eh_frame", ".eh_fram", eSectionTypeEHFrame)
956 .Case(".gosymtab", eSectionTypeGoSymtab)
957 .Default(eSectionTypeInvalid);
958 if (section_type != eSectionTypeInvalid)
959 return section_type;
960
961 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_CODE)
962 return eSectionTypeCode;
963 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
964 return eSectionTypeData;
965 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) {
966 if (sect.size == 0)
967 return eSectionTypeZeroFill;
968 else
969 return eSectionTypeData;
970 }
971 return eSectionTypeOther;
972 }
973
CreateSections(SectionList & unified_section_list)974 void ObjectFilePECOFF::CreateSections(SectionList &unified_section_list) {
975 if (m_sections_up)
976 return;
977 m_sections_up = std::make_unique<SectionList>();
978 ModuleSP module_sp(GetModule());
979 if (module_sp) {
980 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
981
982 SectionSP header_sp = std::make_shared<Section>(
983 module_sp, this, ~user_id_t(0), ConstString("PECOFF header"),
984 eSectionTypeOther, m_coff_header_opt.image_base,
985 m_coff_header_opt.header_size,
986 /*file_offset*/ 0, m_coff_header_opt.header_size,
987 m_coff_header_opt.sect_alignment,
988 /*flags*/ 0);
989 header_sp->SetPermissions(ePermissionsReadable);
990 m_sections_up->AddSection(header_sp);
991 unified_section_list.AddSection(header_sp);
992
993 const uint32_t nsects = m_sect_headers.size();
994 ModuleSP module_sp(GetModule());
995 for (uint32_t idx = 0; idx < nsects; ++idx) {
996 llvm::StringRef sect_name = GetSectionName(m_sect_headers[idx]);
997 ConstString const_sect_name(sect_name);
998 SectionType section_type = GetSectionType(sect_name, m_sect_headers[idx]);
999
1000 SectionSP section_sp(new Section(
1001 module_sp, // Module to which this section belongs
1002 this, // Object file to which this section belongs
1003 idx + 1, // Section ID is the 1 based section index.
1004 const_sect_name, // Name of this section
1005 section_type,
1006 m_coff_header_opt.image_base +
1007 m_sect_headers[idx].vmaddr, // File VM address == addresses as
1008 // they are found in the object file
1009 m_sect_headers[idx].vmsize, // VM size in bytes of this section
1010 m_sect_headers[idx]
1011 .offset, // Offset to the data for this section in the file
1012 m_sect_headers[idx]
1013 .size, // Size in bytes of this section as found in the file
1014 m_coff_header_opt.sect_alignment, // Section alignment
1015 m_sect_headers[idx].flags)); // Flags for this section
1016
1017 uint32_t permissions = 0;
1018 if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_EXECUTE)
1019 permissions |= ePermissionsExecutable;
1020 if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_READ)
1021 permissions |= ePermissionsReadable;
1022 if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_WRITE)
1023 permissions |= ePermissionsWritable;
1024 section_sp->SetPermissions(permissions);
1025
1026 m_sections_up->AddSection(section_sp);
1027 unified_section_list.AddSection(section_sp);
1028 }
1029 }
1030 }
1031
GetUUID()1032 UUID ObjectFilePECOFF::GetUUID() {
1033 if (m_uuid.IsValid())
1034 return m_uuid;
1035
1036 if (!CreateBinary())
1037 return UUID();
1038
1039 m_uuid = GetCoffUUID(*m_binary);
1040 return m_uuid;
1041 }
1042
GetDebugLink()1043 llvm::Optional<FileSpec> ObjectFilePECOFF::GetDebugLink() {
1044 std::string gnu_debuglink_file;
1045 uint32_t gnu_debuglink_crc;
1046 if (GetDebugLinkContents(*m_binary, gnu_debuglink_file, gnu_debuglink_crc))
1047 return FileSpec(gnu_debuglink_file);
1048 return llvm::None;
1049 }
1050
ParseDependentModules()1051 uint32_t ObjectFilePECOFF::ParseDependentModules() {
1052 ModuleSP module_sp(GetModule());
1053 if (!module_sp)
1054 return 0;
1055
1056 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1057 if (m_deps_filespec)
1058 return m_deps_filespec->GetSize();
1059
1060 // Cache coff binary if it is not done yet.
1061 if (!CreateBinary())
1062 return 0;
1063
1064 Log *log = GetLog(LLDBLog::Object);
1065 LLDB_LOG(log, "this = {0}, module = {1} ({2}), file = {3}, binary = {4}",
1066 this, GetModule().get(), GetModule()->GetSpecificationDescription(),
1067 m_file.GetPath(), m_binary.get());
1068
1069 m_deps_filespec = FileSpecList();
1070
1071 for (const auto &entry : m_binary->import_directories()) {
1072 llvm::StringRef dll_name;
1073 // Report a bogus entry.
1074 if (llvm::Error e = entry.getName(dll_name)) {
1075 LLDB_LOGF(log,
1076 "ObjectFilePECOFF::ParseDependentModules() - failed to get "
1077 "import directory entry name: %s",
1078 llvm::toString(std::move(e)).c_str());
1079 continue;
1080 }
1081
1082 // At this moment we only have the base name of the DLL. The full path can
1083 // only be seen after the dynamic loading. Our best guess is Try to get it
1084 // with the help of the object file's directory.
1085 llvm::SmallString<128> dll_fullpath;
1086 FileSpec dll_specs(dll_name);
1087 dll_specs.GetDirectory().SetString(m_file.GetDirectory().GetCString());
1088
1089 if (!llvm::sys::fs::real_path(dll_specs.GetPath(), dll_fullpath))
1090 m_deps_filespec->EmplaceBack(dll_fullpath);
1091 else {
1092 // Known DLLs or DLL not found in the object file directory.
1093 m_deps_filespec->EmplaceBack(dll_name);
1094 }
1095 }
1096 return m_deps_filespec->GetSize();
1097 }
1098
GetDependentModules(FileSpecList & files)1099 uint32_t ObjectFilePECOFF::GetDependentModules(FileSpecList &files) {
1100 auto num_modules = ParseDependentModules();
1101 auto original_size = files.GetSize();
1102
1103 for (unsigned i = 0; i < num_modules; ++i)
1104 files.AppendIfUnique(m_deps_filespec->GetFileSpecAtIndex(i));
1105
1106 return files.GetSize() - original_size;
1107 }
1108
GetEntryPointAddress()1109 lldb_private::Address ObjectFilePECOFF::GetEntryPointAddress() {
1110 if (m_entry_point_address.IsValid())
1111 return m_entry_point_address;
1112
1113 if (!ParseHeader() || !IsExecutable())
1114 return m_entry_point_address;
1115
1116 SectionList *section_list = GetSectionList();
1117 addr_t file_addr = m_coff_header_opt.entry + m_coff_header_opt.image_base;
1118
1119 if (!section_list)
1120 m_entry_point_address.SetOffset(file_addr);
1121 else
1122 m_entry_point_address.ResolveAddressUsingFileSections(file_addr,
1123 section_list);
1124 return m_entry_point_address;
1125 }
1126
GetBaseAddress()1127 Address ObjectFilePECOFF::GetBaseAddress() {
1128 return Address(GetSectionList()->GetSectionAtIndex(0), 0);
1129 }
1130
1131 // Dump
1132 //
1133 // Dump the specifics of the runtime file container (such as any headers
1134 // segments, sections, etc).
Dump(Stream * s)1135 void ObjectFilePECOFF::Dump(Stream *s) {
1136 ModuleSP module_sp(GetModule());
1137 if (module_sp) {
1138 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1139 s->Printf("%p: ", static_cast<void *>(this));
1140 s->Indent();
1141 s->PutCString("ObjectFilePECOFF");
1142
1143 ArchSpec header_arch = GetArchitecture();
1144
1145 *s << ", file = '" << m_file
1146 << "', arch = " << header_arch.GetArchitectureName() << "\n";
1147
1148 SectionList *sections = GetSectionList();
1149 if (sections)
1150 sections->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true,
1151 UINT32_MAX);
1152
1153 if (m_symtab_up)
1154 m_symtab_up->Dump(s, nullptr, eSortOrderNone);
1155
1156 if (m_dos_header.e_magic)
1157 DumpDOSHeader(s, m_dos_header);
1158 if (m_coff_header.machine) {
1159 DumpCOFFHeader(s, m_coff_header);
1160 if (m_coff_header.hdrsize)
1161 DumpOptCOFFHeader(s, m_coff_header_opt);
1162 }
1163 s->EOL();
1164 DumpSectionHeaders(s);
1165 s->EOL();
1166
1167 DumpDependentModules(s);
1168 s->EOL();
1169 }
1170 }
1171
1172 // DumpDOSHeader
1173 //
1174 // Dump the MS-DOS header to the specified output stream
DumpDOSHeader(Stream * s,const dos_header_t & header)1175 void ObjectFilePECOFF::DumpDOSHeader(Stream *s, const dos_header_t &header) {
1176 s->PutCString("MSDOS Header\n");
1177 s->Printf(" e_magic = 0x%4.4x\n", header.e_magic);
1178 s->Printf(" e_cblp = 0x%4.4x\n", header.e_cblp);
1179 s->Printf(" e_cp = 0x%4.4x\n", header.e_cp);
1180 s->Printf(" e_crlc = 0x%4.4x\n", header.e_crlc);
1181 s->Printf(" e_cparhdr = 0x%4.4x\n", header.e_cparhdr);
1182 s->Printf(" e_minalloc = 0x%4.4x\n", header.e_minalloc);
1183 s->Printf(" e_maxalloc = 0x%4.4x\n", header.e_maxalloc);
1184 s->Printf(" e_ss = 0x%4.4x\n", header.e_ss);
1185 s->Printf(" e_sp = 0x%4.4x\n", header.e_sp);
1186 s->Printf(" e_csum = 0x%4.4x\n", header.e_csum);
1187 s->Printf(" e_ip = 0x%4.4x\n", header.e_ip);
1188 s->Printf(" e_cs = 0x%4.4x\n", header.e_cs);
1189 s->Printf(" e_lfarlc = 0x%4.4x\n", header.e_lfarlc);
1190 s->Printf(" e_ovno = 0x%4.4x\n", header.e_ovno);
1191 s->Printf(" e_res[4] = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
1192 header.e_res[0], header.e_res[1], header.e_res[2], header.e_res[3]);
1193 s->Printf(" e_oemid = 0x%4.4x\n", header.e_oemid);
1194 s->Printf(" e_oeminfo = 0x%4.4x\n", header.e_oeminfo);
1195 s->Printf(" e_res2[10] = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, "
1196 "0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
1197 header.e_res2[0], header.e_res2[1], header.e_res2[2],
1198 header.e_res2[3], header.e_res2[4], header.e_res2[5],
1199 header.e_res2[6], header.e_res2[7], header.e_res2[8],
1200 header.e_res2[9]);
1201 s->Printf(" e_lfanew = 0x%8.8x\n", header.e_lfanew);
1202 }
1203
1204 // DumpCOFFHeader
1205 //
1206 // Dump the COFF header to the specified output stream
DumpCOFFHeader(Stream * s,const coff_header_t & header)1207 void ObjectFilePECOFF::DumpCOFFHeader(Stream *s, const coff_header_t &header) {
1208 s->PutCString("COFF Header\n");
1209 s->Printf(" machine = 0x%4.4x\n", header.machine);
1210 s->Printf(" nsects = 0x%4.4x\n", header.nsects);
1211 s->Printf(" modtime = 0x%8.8x\n", header.modtime);
1212 s->Printf(" symoff = 0x%8.8x\n", header.symoff);
1213 s->Printf(" nsyms = 0x%8.8x\n", header.nsyms);
1214 s->Printf(" hdrsize = 0x%4.4x\n", header.hdrsize);
1215 }
1216
1217 // DumpOptCOFFHeader
1218 //
1219 // Dump the optional COFF header to the specified output stream
DumpOptCOFFHeader(Stream * s,const coff_opt_header_t & header)1220 void ObjectFilePECOFF::DumpOptCOFFHeader(Stream *s,
1221 const coff_opt_header_t &header) {
1222 s->PutCString("Optional COFF Header\n");
1223 s->Printf(" magic = 0x%4.4x\n", header.magic);
1224 s->Printf(" major_linker_version = 0x%2.2x\n",
1225 header.major_linker_version);
1226 s->Printf(" minor_linker_version = 0x%2.2x\n",
1227 header.minor_linker_version);
1228 s->Printf(" code_size = 0x%8.8x\n", header.code_size);
1229 s->Printf(" data_size = 0x%8.8x\n", header.data_size);
1230 s->Printf(" bss_size = 0x%8.8x\n", header.bss_size);
1231 s->Printf(" entry = 0x%8.8x\n", header.entry);
1232 s->Printf(" code_offset = 0x%8.8x\n", header.code_offset);
1233 s->Printf(" data_offset = 0x%8.8x\n", header.data_offset);
1234 s->Printf(" image_base = 0x%16.16" PRIx64 "\n",
1235 header.image_base);
1236 s->Printf(" sect_alignment = 0x%8.8x\n", header.sect_alignment);
1237 s->Printf(" file_alignment = 0x%8.8x\n", header.file_alignment);
1238 s->Printf(" major_os_system_version = 0x%4.4x\n",
1239 header.major_os_system_version);
1240 s->Printf(" minor_os_system_version = 0x%4.4x\n",
1241 header.minor_os_system_version);
1242 s->Printf(" major_image_version = 0x%4.4x\n",
1243 header.major_image_version);
1244 s->Printf(" minor_image_version = 0x%4.4x\n",
1245 header.minor_image_version);
1246 s->Printf(" major_subsystem_version = 0x%4.4x\n",
1247 header.major_subsystem_version);
1248 s->Printf(" minor_subsystem_version = 0x%4.4x\n",
1249 header.minor_subsystem_version);
1250 s->Printf(" reserved1 = 0x%8.8x\n", header.reserved1);
1251 s->Printf(" image_size = 0x%8.8x\n", header.image_size);
1252 s->Printf(" header_size = 0x%8.8x\n", header.header_size);
1253 s->Printf(" checksum = 0x%8.8x\n", header.checksum);
1254 s->Printf(" subsystem = 0x%4.4x\n", header.subsystem);
1255 s->Printf(" dll_flags = 0x%4.4x\n", header.dll_flags);
1256 s->Printf(" stack_reserve_size = 0x%16.16" PRIx64 "\n",
1257 header.stack_reserve_size);
1258 s->Printf(" stack_commit_size = 0x%16.16" PRIx64 "\n",
1259 header.stack_commit_size);
1260 s->Printf(" heap_reserve_size = 0x%16.16" PRIx64 "\n",
1261 header.heap_reserve_size);
1262 s->Printf(" heap_commit_size = 0x%16.16" PRIx64 "\n",
1263 header.heap_commit_size);
1264 s->Printf(" loader_flags = 0x%8.8x\n", header.loader_flags);
1265 s->Printf(" num_data_dir_entries = 0x%8.8x\n",
1266 (uint32_t)header.data_dirs.size());
1267 uint32_t i;
1268 for (i = 0; i < header.data_dirs.size(); i++) {
1269 s->Printf(" data_dirs[%2u] vmaddr = 0x%8.8x, vmsize = 0x%8.8x\n", i,
1270 header.data_dirs[i].vmaddr, header.data_dirs[i].vmsize);
1271 }
1272 }
1273 // DumpSectionHeader
1274 //
1275 // Dump a single ELF section header to the specified output stream
DumpSectionHeader(Stream * s,const section_header_t & sh)1276 void ObjectFilePECOFF::DumpSectionHeader(Stream *s,
1277 const section_header_t &sh) {
1278 std::string name = std::string(GetSectionName(sh));
1279 s->Printf("%-16s 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%4.4x "
1280 "0x%4.4x 0x%8.8x\n",
1281 name.c_str(), sh.vmaddr, sh.vmsize, sh.offset, sh.size, sh.reloff,
1282 sh.lineoff, sh.nreloc, sh.nline, sh.flags);
1283 }
1284
1285 // DumpSectionHeaders
1286 //
1287 // Dump all of the ELF section header to the specified output stream
DumpSectionHeaders(Stream * s)1288 void ObjectFilePECOFF::DumpSectionHeaders(Stream *s) {
1289
1290 s->PutCString("Section Headers\n");
1291 s->PutCString("IDX name vm addr vm size file off file "
1292 "size reloc off line off nreloc nline flags\n");
1293 s->PutCString("==== ---------------- ---------- ---------- ---------- "
1294 "---------- ---------- ---------- ------ ------ ----------\n");
1295
1296 uint32_t idx = 0;
1297 SectionHeaderCollIter pos, end = m_sect_headers.end();
1298
1299 for (pos = m_sect_headers.begin(); pos != end; ++pos, ++idx) {
1300 s->Printf("[%2u] ", idx);
1301 ObjectFilePECOFF::DumpSectionHeader(s, *pos);
1302 }
1303 }
1304
1305 // DumpDependentModules
1306 //
1307 // Dump all of the dependent modules to the specified output stream
DumpDependentModules(lldb_private::Stream * s)1308 void ObjectFilePECOFF::DumpDependentModules(lldb_private::Stream *s) {
1309 auto num_modules = ParseDependentModules();
1310 if (num_modules > 0) {
1311 s->PutCString("Dependent Modules\n");
1312 for (unsigned i = 0; i < num_modules; ++i) {
1313 auto spec = m_deps_filespec->GetFileSpecAtIndex(i);
1314 s->Printf(" %s\n", spec.GetFilename().GetCString());
1315 }
1316 }
1317 }
1318
IsWindowsSubsystem()1319 bool ObjectFilePECOFF::IsWindowsSubsystem() {
1320 switch (m_coff_header_opt.subsystem) {
1321 case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE:
1322 case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI:
1323 case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI:
1324 case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE_WINDOWS:
1325 case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
1326 case llvm::COFF::IMAGE_SUBSYSTEM_XBOX:
1327 case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION:
1328 return true;
1329 default:
1330 return false;
1331 }
1332 }
1333
GetArchitecture()1334 ArchSpec ObjectFilePECOFF::GetArchitecture() {
1335 uint16_t machine = m_coff_header.machine;
1336 switch (machine) {
1337 default:
1338 break;
1339 case llvm::COFF::IMAGE_FILE_MACHINE_AMD64:
1340 case llvm::COFF::IMAGE_FILE_MACHINE_I386:
1341 case llvm::COFF::IMAGE_FILE_MACHINE_POWERPC:
1342 case llvm::COFF::IMAGE_FILE_MACHINE_POWERPCFP:
1343 case llvm::COFF::IMAGE_FILE_MACHINE_ARM:
1344 case llvm::COFF::IMAGE_FILE_MACHINE_ARMNT:
1345 case llvm::COFF::IMAGE_FILE_MACHINE_THUMB:
1346 case llvm::COFF::IMAGE_FILE_MACHINE_ARM64:
1347 ArchSpec arch;
1348 arch.SetArchitecture(eArchTypeCOFF, machine, LLDB_INVALID_CPUTYPE,
1349 IsWindowsSubsystem() ? llvm::Triple::Win32
1350 : llvm::Triple::UnknownOS);
1351 return arch;
1352 }
1353 return ArchSpec();
1354 }
1355
CalculateType()1356 ObjectFile::Type ObjectFilePECOFF::CalculateType() {
1357 if (m_coff_header.machine != 0) {
1358 if ((m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0)
1359 return eTypeExecutable;
1360 else
1361 return eTypeSharedLibrary;
1362 }
1363 return eTypeExecutable;
1364 }
1365
CalculateStrata()1366 ObjectFile::Strata ObjectFilePECOFF::CalculateStrata() { return eStrataUser; }
1367