LLDB mainline
ObjectFilePECOFF.cpp
Go to the documentation of this file.
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
14#include "lldb/Core/Module.h"
17#include "lldb/Core/Section.h"
22#include "lldb/Target/Process.h"
24#include "lldb/Target/Target.h"
29#include "lldb/Utility/Log.h"
31#include "lldb/Utility/Timer.h"
32#include "lldb/Utility/UUID.h"
33
34#include "llvm/BinaryFormat/COFF.h"
35#include "llvm/Object/COFFImportFile.h"
36#include "llvm/Support/CRC.h"
37#include "llvm/Support/Error.h"
38#include "llvm/Support/FormatAdapters.h"
39#include "llvm/Support/Host.h"
40#include "llvm/Support/MemoryBuffer.h"
41#include <optional>
42
43#define IMAGE_DOS_SIGNATURE 0x5A4D // MZ
44#define IMAGE_NT_SIGNATURE 0x00004550 // PE00
45#define OPT_HEADER_MAGIC_PE32 0x010b
46#define OPT_HEADER_MAGIC_PE32_PLUS 0x020b
47
48using namespace lldb;
49using namespace lldb_private;
50
52
53namespace {
54
55static constexpr OptionEnumValueElement g_abi_enums[] = {
56 {
57 llvm::Triple::UnknownEnvironment,
58 "default",
59 "Use default target (if it is Windows) or MSVC",
60 },
61 {
62 llvm::Triple::MSVC,
63 "msvc",
64 "MSVC ABI",
65 },
66 {
67 llvm::Triple::GNU,
68 "gnu",
69 "MinGW / Itanium ABI",
70 },
71};
72
73#define LLDB_PROPERTIES_objectfilepecoff
74#include "ObjectFilePECOFFProperties.inc"
75
76enum {
77#define LLDB_PROPERTIES_objectfilepecoff
78#include "ObjectFilePECOFFPropertiesEnum.inc"
79};
80
81class PluginProperties : public Properties {
82public:
83 static ConstString GetSettingName() {
85 }
86
87 PluginProperties() {
88 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
89 m_collection_sp->Initialize(g_objectfilepecoff_properties);
90 }
91
92 llvm::Triple::EnvironmentType ABI() const {
93 return (llvm::Triple::EnvironmentType)
94 m_collection_sp->GetPropertyAtIndexAsEnumeration(
95 nullptr, ePropertyABI, llvm::Triple::UnknownEnvironment);
96 }
97
98 OptionValueDictionary *ModuleABIMap() const {
99 return m_collection_sp->GetPropertyAtIndexAsOptionValueDictionary(
100 nullptr, ePropertyModuleABIMap);
101 }
102};
103
104} // namespace
105
106static PluginProperties &GetGlobalPluginProperties() {
107 static PluginProperties g_settings;
108 return g_settings;
109}
110
111static bool GetDebugLinkContents(const llvm::object::COFFObjectFile &coff_obj,
112 std::string &gnu_debuglink_file,
113 uint32_t &gnu_debuglink_crc) {
114 static ConstString g_sect_name_gnu_debuglink(".gnu_debuglink");
115 for (const auto &section : coff_obj.sections()) {
116 auto name = section.getName();
117 if (!name) {
118 llvm::consumeError(name.takeError());
119 continue;
120 }
121 if (*name == g_sect_name_gnu_debuglink.GetStringRef()) {
122 auto content = section.getContents();
123 if (!content) {
124 llvm::consumeError(content.takeError());
125 return false;
126 }
127 DataExtractor data(
128 content->data(), content->size(),
129 coff_obj.isLittleEndian() ? eByteOrderLittle : eByteOrderBig, 4);
130 lldb::offset_t gnu_debuglink_offset = 0;
131 gnu_debuglink_file = data.GetCStr(&gnu_debuglink_offset);
132 // Align to the next 4-byte offset
133 gnu_debuglink_offset = llvm::alignTo(gnu_debuglink_offset, 4);
134 data.GetU32(&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
135 return true;
136 }
137 }
138 return false;
139}
140
141static UUID GetCoffUUID(llvm::object::COFFObjectFile &coff_obj) {
142 const llvm::codeview::DebugInfo *pdb_info = nullptr;
143 llvm::StringRef pdb_file;
144
145 // First, prefer to use the PDB build id. LLD generates this even for mingw
146 // targets without PDB output, and it does not get stripped either.
147 if (!coff_obj.getDebugPDBInfo(pdb_info, pdb_file) && pdb_info) {
148 if (pdb_info->PDB70.CVSignature == llvm::OMF::Signature::PDB70) {
150 memcpy(&info.Uuid, pdb_info->PDB70.Signature, sizeof(info.Uuid));
151 info.Age = pdb_info->PDB70.Age;
152 return UUID(info);
153 }
154 }
155
156 std::string gnu_debuglink_file;
157 uint32_t gnu_debuglink_crc;
158
159 // The GNU linker normally does not write a PDB build id (unless requested
160 // with the --build-id option), so we should fall back to using the crc
161 // from .gnu_debuglink if it exists, just like how ObjectFileELF does it.
162 if (!GetDebugLinkContents(coff_obj, gnu_debuglink_file, gnu_debuglink_crc)) {
163 // If there is no .gnu_debuglink section, then this may be an object
164 // containing DWARF debug info for .gnu_debuglink, so calculate the crc of
165 // the object itself.
166 auto raw_data = coff_obj.getData();
168 "Calculating module crc32 %s with size %" PRIu64 " KiB",
169 FileSpec(coff_obj.getFileName()).GetLastPathComponent().AsCString(),
170 static_cast<lldb::offset_t>(raw_data.size()) / 1024);
171 gnu_debuglink_crc = llvm::crc32(0, llvm::arrayRefFromStringRef(raw_data));
172 }
173 // Use 4 bytes of crc from the .gnu_debuglink section.
174 llvm::support::ulittle32_t data(gnu_debuglink_crc);
175 return UUID(&data, sizeof(data));
176}
177
179
185}
186
189 debugger, PluginProperties::GetSettingName())) {
190 const bool is_global_setting = true;
192 debugger, GetGlobalPluginProperties().GetValueProperties(),
193 ConstString("Properties for the PE/COFF object-file plug-in."),
194 is_global_setting);
195 }
196}
197
200}
201
203 return "Portable Executable and Common Object File Format object file reader "
204 "(32 and 64 bit)";
205}
206
208 const lldb::ModuleSP &module_sp, DataBufferSP data_sp,
209 lldb::offset_t data_offset, const lldb_private::FileSpec *file_p,
210 lldb::offset_t file_offset, lldb::offset_t length) {
211 FileSpec file = file_p ? *file_p : FileSpec();
212 if (!data_sp) {
213 data_sp = MapFileData(file, length, file_offset);
214 if (!data_sp)
215 return nullptr;
216 data_offset = 0;
217 }
218
220 return nullptr;
221
222 // Update the data to contain the entire file if it doesn't already
223 if (data_sp->GetByteSize() < length) {
224 data_sp = MapFileData(file, length, file_offset);
225 if (!data_sp)
226 return nullptr;
227 }
228
229 auto objfile_up = std::make_unique<ObjectFilePECOFF>(
230 module_sp, data_sp, data_offset, file_p, file_offset, length);
231 if (!objfile_up || !objfile_up->ParseHeader())
232 return nullptr;
233
234 // Cache coff binary.
235 if (!objfile_up->CreateBinary())
236 return nullptr;
237 return objfile_up.release();
238}
239
241 const lldb::ModuleSP &module_sp, lldb::WritableDataBufferSP data_sp,
242 const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) {
243 if (!data_sp || !ObjectFilePECOFF::MagicBytesMatch(data_sp))
244 return nullptr;
245 auto objfile_up = std::make_unique<ObjectFilePECOFF>(
246 module_sp, data_sp, process_sp, header_addr);
247 if (objfile_up.get() && objfile_up->ParseHeader()) {
248 return objfile_up.release();
249 }
250 return nullptr;
251}
252
254 const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
255 lldb::offset_t data_offset, lldb::offset_t file_offset,
257 const size_t initial_count = specs.GetSize();
258 if (!data_sp || !ObjectFilePECOFF::MagicBytesMatch(data_sp))
259 return initial_count;
260
261 Log *log = GetLog(LLDBLog::Object);
262
263 if (data_sp->GetByteSize() < length)
264 if (DataBufferSP full_sp = MapFileData(file, -1, file_offset))
265 data_sp = std::move(full_sp);
266 auto binary = llvm::object::createBinary(llvm::MemoryBufferRef(
267 toStringRef(data_sp->GetData()), file.GetFilename().GetStringRef()));
268
269 if (!binary) {
270 LLDB_LOG_ERROR(log, binary.takeError(),
271 "Failed to create binary for file ({1}): {0}", file);
272 return initial_count;
273 }
274
275 auto *COFFObj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary->get());
276 if (!COFFObj)
277 return initial_count;
278
279 ModuleSpec module_spec(file);
280 ArchSpec &spec = module_spec.GetArchitecture();
281 lldb_private::UUID &uuid = module_spec.GetUUID();
282 if (!uuid.IsValid())
283 uuid = GetCoffUUID(*COFFObj);
284
285 static llvm::Triple::EnvironmentType default_env = [] {
286 auto def_target = llvm::Triple(
287 llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple()));
288 if (def_target.getOS() == llvm::Triple::Win32 &&
289 def_target.getEnvironment() != llvm::Triple::UnknownEnvironment)
290 return def_target.getEnvironment();
291 return llvm::Triple::MSVC;
292 }();
293
294 // Check for a module-specific override.
295 OptionValueSP module_env_option;
296 const auto *map = GetGlobalPluginProperties().ModuleABIMap();
297 if (map->GetNumValues() > 0) {
298 // Step 1: Try with the exact file name.
299 auto name = file.GetLastPathComponent();
300 module_env_option = map->GetValueForKey(name);
301 if (!module_env_option) {
302 // Step 2: Try with the file name in lowercase.
303 auto name_lower = name.GetStringRef().lower();
304 module_env_option =
305 map->GetValueForKey(ConstString(llvm::StringRef(name_lower)));
306 }
307 if (!module_env_option) {
308 // Step 3: Try with the file name with ".debug" suffix stripped.
309 auto name_stripped = name.GetStringRef();
310 if (name_stripped.consume_back_insensitive(".debug")) {
311 module_env_option = map->GetValueForKey(ConstString(name_stripped));
312 if (!module_env_option) {
313 // Step 4: Try with the file name in lowercase with ".debug" suffix
314 // stripped.
315 auto name_lower = name_stripped.lower();
316 module_env_option =
317 map->GetValueForKey(ConstString(llvm::StringRef(name_lower)));
318 }
319 }
320 }
321 }
322 llvm::Triple::EnvironmentType env;
323 if (module_env_option)
324 env =
325 (llvm::Triple::EnvironmentType)module_env_option->GetEnumerationValue();
326 else
327 env = GetGlobalPluginProperties().ABI();
328
329 if (env == llvm::Triple::UnknownEnvironment)
330 env = default_env;
331
332 switch (COFFObj->getMachine()) {
333 case MachineAmd64:
334 spec.SetTriple("x86_64-pc-windows");
335 spec.GetTriple().setEnvironment(env);
336 specs.Append(module_spec);
337 break;
338 case MachineX86:
339 spec.SetTriple("i386-pc-windows");
340 spec.GetTriple().setEnvironment(env);
341 specs.Append(module_spec);
342 break;
343 case MachineArmNt:
344 spec.SetTriple("armv7-pc-windows");
345 spec.GetTriple().setEnvironment(env);
346 specs.Append(module_spec);
347 break;
348 case MachineArm64:
349 spec.SetTriple("aarch64-pc-windows");
350 spec.GetTriple().setEnvironment(env);
351 specs.Append(module_spec);
352 break;
353 default:
354 break;
355 }
356
357 return specs.GetSize() - initial_count;
358}
359
360bool ObjectFilePECOFF::SaveCore(const lldb::ProcessSP &process_sp,
361 const lldb_private::FileSpec &outfile,
362 lldb::SaveCoreStyle &core_style,
364 core_style = eSaveCoreFull;
365 return SaveMiniDump(process_sp, outfile, error);
366}
367
368bool ObjectFilePECOFF::MagicBytesMatch(DataBufferSP data_sp) {
369 DataExtractor data(data_sp, eByteOrderLittle, 4);
370 lldb::offset_t offset = 0;
371 uint16_t magic = data.GetU16(&offset);
372 return magic == IMAGE_DOS_SIGNATURE;
373}
374
376 // TODO: We need to complete this mapping of COFF symbol types to LLDB ones.
377 // For now, here's a hack to make sure our function have types.
378 const auto complex_type =
379 coff_symbol_type >> llvm::COFF::SCT_COMPLEX_TYPE_SHIFT;
380 if (complex_type == llvm::COFF::IMAGE_SYM_DTYPE_FUNCTION) {
382 }
383 const auto base_type = coff_symbol_type & 0xff;
384 if (base_type == llvm::COFF::IMAGE_SYM_TYPE_NULL &&
385 complex_type == llvm::COFF::IMAGE_SYM_DTYPE_NULL) {
386 // Unknown type. LLD and GNU ld uses this for variables on MinGW, so
387 // consider these symbols to be data to enable printing.
389 }
391}
392
394 if (m_binary)
395 return true;
396
397 Log *log = GetLog(LLDBLog::Object);
398
399 auto binary = llvm::object::createBinary(llvm::MemoryBufferRef(
400 toStringRef(m_data.GetData()), m_file.GetFilename().GetStringRef()));
401 if (!binary) {
402 LLDB_LOG_ERROR(log, binary.takeError(),
403 "Failed to create binary for file ({1}): {0}", m_file);
404 return false;
405 }
406
407 // Make sure we only handle COFF format.
408 m_binary =
409 llvm::unique_dyn_cast<llvm::object::COFFObjectFile>(std::move(*binary));
410 if (!m_binary)
411 return false;
412
413 LLDB_LOG(log, "this = {0}, module = {1} ({2}), file = {3}, binary = {4}",
414 this, GetModule().get(), GetModule()->GetSpecificationDescription(),
415 m_file.GetPath(), m_binary.get());
416 return true;
417}
418
419ObjectFilePECOFF::ObjectFilePECOFF(const lldb::ModuleSP &module_sp,
420 DataBufferSP data_sp,
421 lldb::offset_t data_offset,
422 const FileSpec *file,
423 lldb::offset_t file_offset,
424 lldb::offset_t length)
425 : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
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
430ObjectFilePECOFF::ObjectFilePECOFF(const lldb::ModuleSP &module_sp,
431 WritableDataBufferSP header_data_sp,
432 const lldb::ProcessSP &process_sp,
433 addr_t header_addr)
434 : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
435 m_dos_header(), m_coff_header(), m_coff_header_opt(), m_sect_headers(),
436 m_image_base(LLDB_INVALID_ADDRESS), m_entry_point_address(),
437 m_deps_filespec() {}
438
440
442 ModuleSP module_sp(GetModule());
443 if (module_sp) {
444 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
445 m_sect_headers.clear();
447 lldb::offset_t offset = 0;
448
450 offset = m_dos_header.e_lfanew;
451 uint32_t pe_signature = m_data.GetU32(&offset);
452 if (pe_signature != IMAGE_NT_SIGNATURE)
453 return false;
454 if (ParseCOFFHeader(m_data, &offset, m_coff_header)) {
455 if (m_coff_header.hdrsize > 0)
457 ParseSectionHeaders(offset);
458 }
460 return true;
461 }
462 }
463 return false;
464}
465
467 bool value_is_offset) {
468 bool changed = false;
469 ModuleSP module_sp = GetModule();
470 if (module_sp) {
471 size_t num_loaded_sections = 0;
472 SectionList *section_list = GetSectionList();
473 if (section_list) {
474 if (!value_is_offset) {
475 value -= m_image_base;
476 }
477
478 const size_t num_sections = section_list->GetSize();
479 size_t sect_idx = 0;
480
481 for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
482 // Iterate through the object file sections to find all of the sections
483 // that have SHF_ALLOC in their flag bits.
484 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
485 if (section_sp && !section_sp->IsThreadSpecific()) {
487 section_sp, section_sp->GetFileAddress() + value))
488 ++num_loaded_sections;
489 }
490 }
491 changed = num_loaded_sections > 0;
492 }
493 }
494 return changed;
495}
496
498
500 return (m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0;
501}
502
505 return 8;
507 return 4;
508 return 4;
509}
510
511// NeedsEndianSwap
512//
513// Return true if an endian swap needs to occur when extracting data from this
514// file.
516#if defined(__LITTLE_ENDIAN__)
517 return false;
518#else
519 return true;
520#endif
521}
522// ParseDOSHeader
525 bool success = false;
526 lldb::offset_t offset = 0;
527 success = data.ValidOffsetForDataOfSize(0, sizeof(dos_header));
528
529 if (success) {
530 dos_header.e_magic = data.GetU16(&offset); // Magic number
532
533 if (success) {
534 dos_header.e_cblp = data.GetU16(&offset); // Bytes on last page of file
535 dos_header.e_cp = data.GetU16(&offset); // Pages in file
536 dos_header.e_crlc = data.GetU16(&offset); // Relocations
538 data.GetU16(&offset); // Size of header in paragraphs
540 data.GetU16(&offset); // Minimum extra paragraphs needed
542 data.GetU16(&offset); // Maximum extra paragraphs needed
543 dos_header.e_ss = data.GetU16(&offset); // Initial (relative) SS value
544 dos_header.e_sp = data.GetU16(&offset); // Initial SP value
545 dos_header.e_csum = data.GetU16(&offset); // Checksum
546 dos_header.e_ip = data.GetU16(&offset); // Initial IP value
547 dos_header.e_cs = data.GetU16(&offset); // Initial (relative) CS value
549 data.GetU16(&offset); // File address of relocation table
550 dos_header.e_ovno = data.GetU16(&offset); // Overlay number
551
552 dos_header.e_res[0] = data.GetU16(&offset); // Reserved words
553 dos_header.e_res[1] = data.GetU16(&offset); // Reserved words
554 dos_header.e_res[2] = data.GetU16(&offset); // Reserved words
555 dos_header.e_res[3] = data.GetU16(&offset); // Reserved words
556
558 data.GetU16(&offset); // OEM identifier (for e_oeminfo)
560 data.GetU16(&offset); // OEM information; e_oemid specific
561 dos_header.e_res2[0] = data.GetU16(&offset); // Reserved words
562 dos_header.e_res2[1] = data.GetU16(&offset); // Reserved words
563 dos_header.e_res2[2] = data.GetU16(&offset); // Reserved words
564 dos_header.e_res2[3] = data.GetU16(&offset); // Reserved words
565 dos_header.e_res2[4] = data.GetU16(&offset); // Reserved words
566 dos_header.e_res2[5] = data.GetU16(&offset); // Reserved words
567 dos_header.e_res2[6] = data.GetU16(&offset); // Reserved words
568 dos_header.e_res2[7] = data.GetU16(&offset); // Reserved words
569 dos_header.e_res2[8] = data.GetU16(&offset); // Reserved words
570 dos_header.e_res2[9] = data.GetU16(&offset); // Reserved words
571
573 data.GetU32(&offset); // File address of new exe header
574 }
575 }
576 if (!success)
577 memset(&dos_header, 0, sizeof(dos_header));
578 return success;
579}
580
581// ParserCOFFHeader
583 lldb::offset_t *offset_ptr,
585 bool success =
586 data.ValidOffsetForDataOfSize(*offset_ptr, sizeof(coff_header));
587 if (success) {
588 coff_header.machine = data.GetU16(offset_ptr);
589 coff_header.nsects = data.GetU16(offset_ptr);
590 coff_header.modtime = data.GetU32(offset_ptr);
591 coff_header.symoff = data.GetU32(offset_ptr);
592 coff_header.nsyms = data.GetU32(offset_ptr);
593 coff_header.hdrsize = data.GetU16(offset_ptr);
594 coff_header.flags = data.GetU16(offset_ptr);
595 }
596 if (!success)
597 memset(&coff_header, 0, sizeof(coff_header));
598 return success;
599}
600
602 bool success = false;
603 const lldb::offset_t end_offset = *offset_ptr + m_coff_header.hdrsize;
604 if (*offset_ptr < end_offset) {
605 success = true;
606 m_coff_header_opt.magic = m_data.GetU16(offset_ptr);
612 m_coff_header_opt.entry = m_data.GetU32(offset_ptr);
614
615 const uint32_t addr_byte_size = GetAddressByteSize();
616
617 if (*offset_ptr < end_offset) {
619 // PE32 only
621 } else
623
624 if (*offset_ptr < end_offset) {
626 m_data.GetMaxU64(offset_ptr, addr_byte_size);
642 m_data.GetMaxU64(offset_ptr, addr_byte_size);
644 m_data.GetMaxU64(offset_ptr, addr_byte_size);
646 m_data.GetMaxU64(offset_ptr, addr_byte_size);
648 m_data.GetMaxU64(offset_ptr, addr_byte_size);
650 uint32_t num_data_dir_entries = m_data.GetU32(offset_ptr);
652 m_coff_header_opt.data_dirs.resize(num_data_dir_entries);
653 uint32_t i;
654 for (i = 0; i < num_data_dir_entries; i++) {
655 m_coff_header_opt.data_dirs[i].vmaddr = m_data.GetU32(offset_ptr);
656 m_coff_header_opt.data_dirs[i].vmsize = m_data.GetU32(offset_ptr);
657 }
658
660 }
661 }
662 }
663 // Make sure we are on track for section data which follows
664 *offset_ptr = end_offset;
665 return success;
666}
667
669 return addr.GetFileAddress() - m_image_base;
670}
671
673 SectionList *sect_list = GetSectionList();
674 if (!sect_list)
675 return Address(GetFileAddress(rva));
676
677 return Address(GetFileAddress(rva), sect_list);
678}
679
681 return m_image_base + rva;
682}
683
685 if (!size)
686 return {};
687
688 if (m_data.ValidOffsetForDataOfSize(offset, size))
689 return DataExtractor(m_data, offset, size);
690
691 ProcessSP process_sp(m_process_wp.lock());
692 DataExtractor data;
693 if (process_sp) {
694 auto data_up = std::make_unique<DataBufferHeap>(size, 0);
695 Status readmem_error;
696 size_t bytes_read =
697 process_sp->ReadMemory(m_image_base + offset, data_up->GetBytes(),
698 data_up->GetByteSize(), readmem_error);
699 if (bytes_read == size) {
700 DataBufferSP buffer_sp(data_up.release());
701 data.SetData(buffer_sp, 0, buffer_sp->GetByteSize());
702 }
703 }
704 return data;
705}
706
708 Address addr = GetAddress(rva);
709 SectionSP sect = addr.GetSection();
710 if (!sect)
711 return {};
712 rva = sect->GetFileOffset() + addr.GetOffset();
713
714 return ReadImageData(rva, size);
715}
716
717// ParseSectionHeaders
719 uint32_t section_header_data_offset) {
720 const uint32_t nsects = m_coff_header.nsects;
721 m_sect_headers.clear();
722
723 if (nsects > 0) {
724 const size_t section_header_byte_size = nsects * sizeof(section_header_t);
725 DataExtractor section_header_data =
726 ReadImageData(section_header_data_offset, section_header_byte_size);
727
728 lldb::offset_t offset = 0;
729 if (section_header_data.ValidOffsetForDataOfSize(
730 offset, section_header_byte_size)) {
731 m_sect_headers.resize(nsects);
732
733 for (uint32_t idx = 0; idx < nsects; ++idx) {
734 const void *name_data = section_header_data.GetData(&offset, 8);
735 if (name_data) {
736 memcpy(m_sect_headers[idx].name, name_data, 8);
737 m_sect_headers[idx].vmsize = section_header_data.GetU32(&offset);
738 m_sect_headers[idx].vmaddr = section_header_data.GetU32(&offset);
739 m_sect_headers[idx].size = section_header_data.GetU32(&offset);
740 m_sect_headers[idx].offset = section_header_data.GetU32(&offset);
741 m_sect_headers[idx].reloff = section_header_data.GetU32(&offset);
742 m_sect_headers[idx].lineoff = section_header_data.GetU32(&offset);
743 m_sect_headers[idx].nreloc = section_header_data.GetU16(&offset);
744 m_sect_headers[idx].nline = section_header_data.GetU16(&offset);
745 m_sect_headers[idx].flags = section_header_data.GetU32(&offset);
746 }
747 }
748 }
749 }
750
751 return !m_sect_headers.empty();
752}
753
755 llvm::StringRef hdr_name(sect.name, std::size(sect.name));
756 hdr_name = hdr_name.split('\0').first;
757 if (hdr_name.consume_front("/")) {
758 lldb::offset_t stroff;
759 if (!to_integer(hdr_name, stroff, 10))
760 return "";
761 lldb::offset_t string_file_offset =
762 m_coff_header.symoff + (m_coff_header.nsyms * 18) + stroff;
763 if (const char *name = m_data.GetCStr(&string_file_offset))
764 return name;
765 return "";
766 }
767 return hdr_name;
768}
769
771 SectionList *sect_list = GetSectionList();
772 rva_symbol_list_t sorted_exports = AppendFromExportTable(sect_list, symtab);
773 AppendFromCOFFSymbolTable(sect_list, symtab, sorted_exports);
774}
775
776static bool RVASymbolListCompareRVA(const std::pair<uint32_t, uint32_t> &a,
777 const std::pair<uint32_t, uint32_t> &b) {
778 return a.first < b.first;
779}
780
782 SectionList *sect_list, Symtab &symtab,
783 const ObjectFilePECOFF::rva_symbol_list_t &sorted_exports) {
784 const uint32_t num_syms = m_binary->getNumberOfSymbols();
785 if (num_syms == 0)
786 return;
787 // Check that this is not a bigobj; we do not support bigobj.
788 if (m_binary->getSymbolTableEntrySize() !=
789 sizeof(llvm::object::coff_symbol16))
790 return;
791
792 Log *log = GetLog(LLDBLog::Object);
793 symtab.Reserve(symtab.GetNumSymbols() + num_syms);
794 for (const auto &sym_ref : m_binary->symbols()) {
795 const auto coff_sym_ref = m_binary->getCOFFSymbol(sym_ref);
796 auto name_or_error = sym_ref.getName();
797 if (auto err = name_or_error.takeError()) {
798 LLDB_LOG(log,
799 "ObjectFilePECOFF::AppendFromCOFFSymbolTable - failed to get "
800 "symbol table entry name: {0}",
801 llvm::fmt_consume(std::move(err)));
802 continue;
803 }
804 const llvm::StringRef sym_name = *name_or_error;
805 Symbol symbol;
806 symbol.GetMangled().SetValue(ConstString(sym_name));
807 int16_t section_number =
808 static_cast<int16_t>(coff_sym_ref.getSectionNumber());
809 if (section_number >= 1) {
810 symbol.GetAddressRef() = Address(
811 sect_list->FindSectionByID(section_number), coff_sym_ref.getValue());
812 const auto symbol_type = MapSymbolType(coff_sym_ref.getType());
813 symbol.SetType(symbol_type);
814
815 // Check for duplicate of exported symbols:
816 const uint32_t symbol_rva = symbol.GetAddressRef().GetFileAddress() -
818 const auto &first_match = std::lower_bound(
819 sorted_exports.begin(), sorted_exports.end(),
820 std::make_pair(symbol_rva, 0), RVASymbolListCompareRVA);
821 for (auto it = first_match;
822 it != sorted_exports.end() && it->first == symbol_rva; ++it) {
823 Symbol *exported = symtab.SymbolAtIndex(it->second);
824 if (symbol_type != lldb::eSymbolTypeInvalid)
825 exported->SetType(symbol_type);
826 if (exported->GetMangled() == symbol.GetMangled()) {
827 symbol.SetExternal(true);
828 // We don't want the symbol to be duplicated (e.g. when running
829 // `disas -n func`), but we also don't want to erase this entry (to
830 // preserve the original symbol order), so we mark it as additional.
832 } else {
833 // It is possible for a symbol to be exported in a different name
834 // from its original. In this case keep both entries so lookup using
835 // either names will work. If this symbol has an invalid type, replace
836 // it with the type from the export symbol.
837 if (symbol.GetType() == lldb::eSymbolTypeInvalid)
838 symbol.SetType(exported->GetType());
839 }
840 }
841 } else if (section_number == llvm::COFF::IMAGE_SYM_ABSOLUTE) {
842 symbol.GetAddressRef() = Address(coff_sym_ref.getValue());
844 }
845 symtab.AddSymbol(symbol);
846 }
847}
848
851 Symtab &symtab) {
852 const auto *export_table = m_binary->getExportTable();
853 if (!export_table)
854 return {};
855 const uint32_t num_syms = export_table->AddressTableEntries;
856 if (num_syms == 0)
857 return {};
858
859 Log *log = GetLog(LLDBLog::Object);
860 rva_symbol_list_t export_list;
861 symtab.Reserve(symtab.GetNumSymbols() + num_syms);
862 // Read each export table entry, ordered by ordinal instead of by name.
863 for (const auto &entry : m_binary->export_directories()) {
864 llvm::StringRef sym_name;
865 if (auto err = entry.getSymbolName(sym_name)) {
866 LLDB_LOG(log,
867 "ObjectFilePECOFF::AppendFromExportTable - failed to get export "
868 "table entry name: {0}",
869 llvm::fmt_consume(std::move(err)));
870 continue;
871 }
872 Symbol symbol;
873 // Note: symbol name may be empty if it is only exported by ordinal.
874 symbol.GetMangled().SetValue(ConstString(sym_name));
875
876 uint32_t ordinal;
877 llvm::cantFail(entry.getOrdinal(ordinal));
878 symbol.SetID(ordinal);
879
880 bool is_forwarder;
881 llvm::cantFail(entry.isForwarder(is_forwarder));
882 if (is_forwarder) {
883 // Forwarder exports are redirected by the loader transparently, but keep
884 // it in symtab and make a note using the symbol name.
885 llvm::StringRef forwarder_name;
886 if (auto err = entry.getForwardTo(forwarder_name)) {
887 LLDB_LOG(log,
888 "ObjectFilePECOFF::AppendFromExportTable - failed to get "
889 "forwarder name of forwarder export '{0}': {1}",
890 sym_name, llvm::fmt_consume(std::move(err)));
891 continue;
892 }
893 llvm::SmallString<256> new_name = {symbol.GetDisplayName().GetStringRef(),
894 " (forwarded to ", forwarder_name,
895 ")"};
896 symbol.GetMangled().SetDemangledName(ConstString(new_name.str()));
898 }
899
900 uint32_t function_rva;
901 if (auto err = entry.getExportRVA(function_rva)) {
902 LLDB_LOG(log,
903 "ObjectFilePECOFF::AppendFromExportTable - failed to get "
904 "address of export entry '{0}': {1}",
905 sym_name, llvm::fmt_consume(std::move(err)));
906 continue;
907 }
908 // Skip the symbol if it doesn't look valid.
909 if (function_rva == 0 && sym_name.empty())
910 continue;
911 symbol.GetAddressRef() =
912 Address(m_coff_header_opt.image_base + function_rva, sect_list);
913
914 // An exported symbol may be either code or data. Guess by checking whether
915 // the section containing the symbol is executable.
917 if (!is_forwarder)
918 if (auto section_sp = symbol.GetAddressRef().GetSection())
919 if (section_sp->GetPermissions() & ePermissionsExecutable)
921 symbol.SetExternal(true);
922 uint32_t idx = symtab.AddSymbol(symbol);
923 export_list.push_back(std::make_pair(function_rva, idx));
924 }
925 std::stable_sort(export_list.begin(), export_list.end(),
927 return export_list;
928}
929
930std::unique_ptr<CallFrameInfo> ObjectFilePECOFF::CreateCallFrameInfo() {
931 if (llvm::COFF::EXCEPTION_TABLE >= m_coff_header_opt.data_dirs.size())
932 return {};
933
934 data_directory data_dir_exception =
935 m_coff_header_opt.data_dirs[llvm::COFF::EXCEPTION_TABLE];
936 if (!data_dir_exception.vmaddr)
937 return {};
938
939 if (m_coff_header.machine != llvm::COFF::IMAGE_FILE_MACHINE_AMD64)
940 return {};
941
942 return std::make_unique<PECallFrameInfo>(*this, data_dir_exception.vmaddr,
943 data_dir_exception.vmsize);
944}
945
947 // TODO: determine this for COFF
948 return false;
949}
950
952 const section_header_t &sect) {
953 ConstString const_sect_name(sect_name);
954 static ConstString g_code_sect_name(".code");
955 static ConstString g_CODE_sect_name("CODE");
956 static ConstString g_data_sect_name(".data");
957 static ConstString g_DATA_sect_name("DATA");
958 static ConstString g_bss_sect_name(".bss");
959 static ConstString g_BSS_sect_name("BSS");
960
961 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_CODE &&
962 ((const_sect_name == g_code_sect_name) ||
963 (const_sect_name == g_CODE_sect_name))) {
964 return eSectionTypeCode;
965 }
966 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA &&
967 ((const_sect_name == g_data_sect_name) ||
968 (const_sect_name == g_DATA_sect_name))) {
969 if (sect.size == 0 && sect.offset == 0)
971 else
972 return eSectionTypeData;
973 }
974 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA &&
975 ((const_sect_name == g_bss_sect_name) ||
976 (const_sect_name == g_BSS_sect_name))) {
977 if (sect.size == 0)
979 else
980 return eSectionTypeData;
981 }
982
983 SectionType section_type =
984 llvm::StringSwitch<SectionType>(sect_name)
985 .Case(".debug", eSectionTypeDebug)
986 .Case(".stabstr", eSectionTypeDataCString)
987 .Case(".reloc", eSectionTypeOther)
988 .Case(".debug_abbrev", eSectionTypeDWARFDebugAbbrev)
989 .Case(".debug_aranges", eSectionTypeDWARFDebugAranges)
990 .Case(".debug_frame", eSectionTypeDWARFDebugFrame)
991 .Case(".debug_info", eSectionTypeDWARFDebugInfo)
992 .Case(".debug_line", eSectionTypeDWARFDebugLine)
993 .Case(".debug_loc", eSectionTypeDWARFDebugLoc)
994 .Case(".debug_loclists", eSectionTypeDWARFDebugLocLists)
995 .Case(".debug_macinfo", eSectionTypeDWARFDebugMacInfo)
996 .Case(".debug_names", eSectionTypeDWARFDebugNames)
997 .Case(".debug_pubnames", eSectionTypeDWARFDebugPubNames)
998 .Case(".debug_pubtypes", eSectionTypeDWARFDebugPubTypes)
999 .Case(".debug_ranges", eSectionTypeDWARFDebugRanges)
1000 .Case(".debug_str", eSectionTypeDWARFDebugStr)
1001 .Case(".debug_types", eSectionTypeDWARFDebugTypes)
1002 // .eh_frame can be truncated to 8 chars.
1003 .Cases(".eh_frame", ".eh_fram", eSectionTypeEHFrame)
1004 .Case(".gosymtab", eSectionTypeGoSymtab)
1005 .Default(eSectionTypeInvalid);
1006 if (section_type != eSectionTypeInvalid)
1007 return section_type;
1008
1009 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_CODE)
1010 return eSectionTypeCode;
1011 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
1012 return eSectionTypeData;
1013 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) {
1014 if (sect.size == 0)
1015 return eSectionTypeZeroFill;
1016 else
1017 return eSectionTypeData;
1018 }
1019 return eSectionTypeOther;
1020}
1021
1023 if (m_sections_up)
1024 return;
1025 m_sections_up = std::make_unique<SectionList>();
1026 ModuleSP module_sp(GetModule());
1027 if (module_sp) {
1028 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1029
1030 SectionSP header_sp = std::make_shared<Section>(
1031 module_sp, this, ~user_id_t(0), ConstString("PECOFF header"),
1034 /*file_offset*/ 0, m_coff_header_opt.header_size,
1036 /*flags*/ 0);
1037 header_sp->SetPermissions(ePermissionsReadable);
1038 m_sections_up->AddSection(header_sp);
1039 unified_section_list.AddSection(header_sp);
1040
1041 const uint32_t nsects = m_sect_headers.size();
1042 ModuleSP module_sp(GetModule());
1043 for (uint32_t idx = 0; idx < nsects; ++idx) {
1044 llvm::StringRef sect_name = GetSectionName(m_sect_headers[idx]);
1045 ConstString const_sect_name(sect_name);
1046 SectionType section_type = GetSectionType(sect_name, m_sect_headers[idx]);
1047
1048 SectionSP section_sp(new Section(
1049 module_sp, // Module to which this section belongs
1050 this, // Object file to which this section belongs
1051 idx + 1, // Section ID is the 1 based section index.
1052 const_sect_name, // Name of this section
1053 section_type,
1055 m_sect_headers[idx].vmaddr, // File VM address == addresses as
1056 // they are found in the object file
1057 m_sect_headers[idx].vmsize, // VM size in bytes of this section
1058 m_sect_headers[idx]
1059 .offset, // Offset to the data for this section in the file
1060 m_sect_headers[idx]
1061 .size, // Size in bytes of this section as found in the file
1062 m_coff_header_opt.sect_alignment, // Section alignment
1063 m_sect_headers[idx].flags)); // Flags for this section
1064
1065 uint32_t permissions = 0;
1066 if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_EXECUTE)
1067 permissions |= ePermissionsExecutable;
1068 if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_READ)
1069 permissions |= ePermissionsReadable;
1070 if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_WRITE)
1071 permissions |= ePermissionsWritable;
1072 section_sp->SetPermissions(permissions);
1073
1074 m_sections_up->AddSection(section_sp);
1075 unified_section_list.AddSection(section_sp);
1076 }
1077 }
1078}
1079
1081 if (m_uuid.IsValid())
1082 return m_uuid;
1083
1084 if (!CreateBinary())
1085 return UUID();
1086
1088 return m_uuid;
1089}
1090
1091std::optional<FileSpec> ObjectFilePECOFF::GetDebugLink() {
1092 std::string gnu_debuglink_file;
1093 uint32_t gnu_debuglink_crc;
1094 if (GetDebugLinkContents(*m_binary, gnu_debuglink_file, gnu_debuglink_crc))
1095 return FileSpec(gnu_debuglink_file);
1096 return std::nullopt;
1097}
1098
1100 ModuleSP module_sp(GetModule());
1101 if (!module_sp)
1102 return 0;
1103
1104 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1105 if (m_deps_filespec)
1106 return m_deps_filespec->GetSize();
1107
1108 // Cache coff binary if it is not done yet.
1109 if (!CreateBinary())
1110 return 0;
1111
1112 Log *log = GetLog(LLDBLog::Object);
1113 LLDB_LOG(log, "this = {0}, module = {1} ({2}), file = {3}, binary = {4}",
1114 this, GetModule().get(), GetModule()->GetSpecificationDescription(),
1115 m_file.GetPath(), m_binary.get());
1116
1117 m_deps_filespec = FileSpecList();
1118
1119 for (const auto &entry : m_binary->import_directories()) {
1120 llvm::StringRef dll_name;
1121 // Report a bogus entry.
1122 if (llvm::Error e = entry.getName(dll_name)) {
1123 LLDB_LOGF(log,
1124 "ObjectFilePECOFF::ParseDependentModules() - failed to get "
1125 "import directory entry name: %s",
1126 llvm::toString(std::move(e)).c_str());
1127 continue;
1128 }
1129
1130 // At this moment we only have the base name of the DLL. The full path can
1131 // only be seen after the dynamic loading. Our best guess is Try to get it
1132 // with the help of the object file's directory.
1133 llvm::SmallString<128> dll_fullpath;
1134 FileSpec dll_specs(dll_name);
1135 dll_specs.SetDirectory(m_file.GetDirectory());
1136
1137 if (!llvm::sys::fs::real_path(dll_specs.GetPath(), dll_fullpath))
1138 m_deps_filespec->EmplaceBack(dll_fullpath);
1139 else {
1140 // Known DLLs or DLL not found in the object file directory.
1141 m_deps_filespec->EmplaceBack(dll_name);
1142 }
1143 }
1144 return m_deps_filespec->GetSize();
1145}
1146
1148 auto num_modules = ParseDependentModules();
1149 auto original_size = files.GetSize();
1150
1151 for (unsigned i = 0; i < num_modules; ++i)
1152 files.AppendIfUnique(m_deps_filespec->GetFileSpecAtIndex(i));
1153
1154 return files.GetSize() - original_size;
1155}
1156
1159 return m_entry_point_address;
1160
1161 if (!ParseHeader() || !IsExecutable())
1162 return m_entry_point_address;
1163
1164 SectionList *section_list = GetSectionList();
1166
1167 if (!section_list)
1169 else
1171 section_list);
1172 return m_entry_point_address;
1173}
1174
1176 return Address(GetSectionList()->GetSectionAtIndex(0), 0);
1177}
1178
1179// Dump
1180//
1181// Dump the specifics of the runtime file container (such as any headers
1182// segments, sections, etc).
1184 ModuleSP module_sp(GetModule());
1185 if (module_sp) {
1186 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1187 s->Printf("%p: ", static_cast<void *>(this));
1188 s->Indent();
1189 s->PutCString("ObjectFilePECOFF");
1190
1191 ArchSpec header_arch = GetArchitecture();
1192
1193 *s << ", file = '" << m_file
1194 << "', arch = " << header_arch.GetArchitectureName() << "\n";
1195
1196 SectionList *sections = GetSectionList();
1197 if (sections)
1198 sections->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true,
1199 UINT32_MAX);
1200
1201 if (m_symtab_up)
1202 m_symtab_up->Dump(s, nullptr, eSortOrderNone);
1203
1206 if (m_coff_header.machine) {
1210 }
1211 s->EOL();
1213 s->EOL();
1214
1216 s->EOL();
1217 }
1218}
1219
1220// DumpDOSHeader
1221//
1222// Dump the MS-DOS header to the specified output stream
1224 s->PutCString("MSDOS Header\n");
1225 s->Printf(" e_magic = 0x%4.4x\n", header.e_magic);
1226 s->Printf(" e_cblp = 0x%4.4x\n", header.e_cblp);
1227 s->Printf(" e_cp = 0x%4.4x\n", header.e_cp);
1228 s->Printf(" e_crlc = 0x%4.4x\n", header.e_crlc);
1229 s->Printf(" e_cparhdr = 0x%4.4x\n", header.e_cparhdr);
1230 s->Printf(" e_minalloc = 0x%4.4x\n", header.e_minalloc);
1231 s->Printf(" e_maxalloc = 0x%4.4x\n", header.e_maxalloc);
1232 s->Printf(" e_ss = 0x%4.4x\n", header.e_ss);
1233 s->Printf(" e_sp = 0x%4.4x\n", header.e_sp);
1234 s->Printf(" e_csum = 0x%4.4x\n", header.e_csum);
1235 s->Printf(" e_ip = 0x%4.4x\n", header.e_ip);
1236 s->Printf(" e_cs = 0x%4.4x\n", header.e_cs);
1237 s->Printf(" e_lfarlc = 0x%4.4x\n", header.e_lfarlc);
1238 s->Printf(" e_ovno = 0x%4.4x\n", header.e_ovno);
1239 s->Printf(" e_res[4] = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
1240 header.e_res[0], header.e_res[1], header.e_res[2], header.e_res[3]);
1241 s->Printf(" e_oemid = 0x%4.4x\n", header.e_oemid);
1242 s->Printf(" e_oeminfo = 0x%4.4x\n", header.e_oeminfo);
1243 s->Printf(" e_res2[10] = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, "
1244 "0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
1245 header.e_res2[0], header.e_res2[1], header.e_res2[2],
1246 header.e_res2[3], header.e_res2[4], header.e_res2[5],
1247 header.e_res2[6], header.e_res2[7], header.e_res2[8],
1248 header.e_res2[9]);
1249 s->Printf(" e_lfanew = 0x%8.8x\n", header.e_lfanew);
1250}
1251
1252// DumpCOFFHeader
1253//
1254// Dump the COFF header to the specified output stream
1256 s->PutCString("COFF Header\n");
1257 s->Printf(" machine = 0x%4.4x\n", header.machine);
1258 s->Printf(" nsects = 0x%4.4x\n", header.nsects);
1259 s->Printf(" modtime = 0x%8.8x\n", header.modtime);
1260 s->Printf(" symoff = 0x%8.8x\n", header.symoff);
1261 s->Printf(" nsyms = 0x%8.8x\n", header.nsyms);
1262 s->Printf(" hdrsize = 0x%4.4x\n", header.hdrsize);
1263}
1264
1265// DumpOptCOFFHeader
1266//
1267// Dump the optional COFF header to the specified output stream
1269 const coff_opt_header_t &header) {
1270 s->PutCString("Optional COFF Header\n");
1271 s->Printf(" magic = 0x%4.4x\n", header.magic);
1272 s->Printf(" major_linker_version = 0x%2.2x\n",
1273 header.major_linker_version);
1274 s->Printf(" minor_linker_version = 0x%2.2x\n",
1275 header.minor_linker_version);
1276 s->Printf(" code_size = 0x%8.8x\n", header.code_size);
1277 s->Printf(" data_size = 0x%8.8x\n", header.data_size);
1278 s->Printf(" bss_size = 0x%8.8x\n", header.bss_size);
1279 s->Printf(" entry = 0x%8.8x\n", header.entry);
1280 s->Printf(" code_offset = 0x%8.8x\n", header.code_offset);
1281 s->Printf(" data_offset = 0x%8.8x\n", header.data_offset);
1282 s->Printf(" image_base = 0x%16.16" PRIx64 "\n",
1283 header.image_base);
1284 s->Printf(" sect_alignment = 0x%8.8x\n", header.sect_alignment);
1285 s->Printf(" file_alignment = 0x%8.8x\n", header.file_alignment);
1286 s->Printf(" major_os_system_version = 0x%4.4x\n",
1288 s->Printf(" minor_os_system_version = 0x%4.4x\n",
1290 s->Printf(" major_image_version = 0x%4.4x\n",
1291 header.major_image_version);
1292 s->Printf(" minor_image_version = 0x%4.4x\n",
1293 header.minor_image_version);
1294 s->Printf(" major_subsystem_version = 0x%4.4x\n",
1296 s->Printf(" minor_subsystem_version = 0x%4.4x\n",
1298 s->Printf(" reserved1 = 0x%8.8x\n", header.reserved1);
1299 s->Printf(" image_size = 0x%8.8x\n", header.image_size);
1300 s->Printf(" header_size = 0x%8.8x\n", header.header_size);
1301 s->Printf(" checksum = 0x%8.8x\n", header.checksum);
1302 s->Printf(" subsystem = 0x%4.4x\n", header.subsystem);
1303 s->Printf(" dll_flags = 0x%4.4x\n", header.dll_flags);
1304 s->Printf(" stack_reserve_size = 0x%16.16" PRIx64 "\n",
1305 header.stack_reserve_size);
1306 s->Printf(" stack_commit_size = 0x%16.16" PRIx64 "\n",
1307 header.stack_commit_size);
1308 s->Printf(" heap_reserve_size = 0x%16.16" PRIx64 "\n",
1309 header.heap_reserve_size);
1310 s->Printf(" heap_commit_size = 0x%16.16" PRIx64 "\n",
1311 header.heap_commit_size);
1312 s->Printf(" loader_flags = 0x%8.8x\n", header.loader_flags);
1313 s->Printf(" num_data_dir_entries = 0x%8.8x\n",
1314 (uint32_t)header.data_dirs.size());
1315 uint32_t i;
1316 for (i = 0; i < header.data_dirs.size(); i++) {
1317 s->Printf(" data_dirs[%2u] vmaddr = 0x%8.8x, vmsize = 0x%8.8x\n", i,
1318 header.data_dirs[i].vmaddr, header.data_dirs[i].vmsize);
1319 }
1320}
1321// DumpSectionHeader
1322//
1323// Dump a single ELF section header to the specified output stream
1325 const section_header_t &sh) {
1326 std::string name = std::string(GetSectionName(sh));
1327 s->Printf("%-16s 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%4.4x "
1328 "0x%4.4x 0x%8.8x\n",
1329 name.c_str(), sh.vmaddr, sh.vmsize, sh.offset, sh.size, sh.reloff,
1330 sh.lineoff, sh.nreloc, sh.nline, sh.flags);
1331}
1332
1333// DumpSectionHeaders
1334//
1335// Dump all of the ELF section header to the specified output stream
1337
1338 s->PutCString("Section Headers\n");
1339 s->PutCString("IDX name vm addr vm size file off file "
1340 "size reloc off line off nreloc nline flags\n");
1341 s->PutCString("==== ---------------- ---------- ---------- ---------- "
1342 "---------- ---------- ---------- ------ ------ ----------\n");
1343
1344 uint32_t idx = 0;
1345 SectionHeaderCollIter pos, end = m_sect_headers.end();
1346
1347 for (pos = m_sect_headers.begin(); pos != end; ++pos, ++idx) {
1348 s->Printf("[%2u] ", idx);
1350 }
1351}
1352
1353// DumpDependentModules
1354//
1355// Dump all of the dependent modules to the specified output stream
1357 auto num_modules = ParseDependentModules();
1358 if (num_modules > 0) {
1359 s->PutCString("Dependent Modules\n");
1360 for (unsigned i = 0; i < num_modules; ++i) {
1361 auto spec = m_deps_filespec->GetFileSpecAtIndex(i);
1362 s->Printf(" %s\n", spec.GetFilename().GetCString());
1363 }
1364 }
1365}
1366
1368 switch (m_coff_header_opt.subsystem) {
1369 case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE:
1370 case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI:
1371 case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI:
1372 case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE_WINDOWS:
1373 case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
1374 case llvm::COFF::IMAGE_SUBSYSTEM_XBOX:
1375 case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION:
1376 return true;
1377 default:
1378 return false;
1379 }
1380}
1381
1383 uint16_t machine = m_coff_header.machine;
1384 switch (machine) {
1385 default:
1386 break;
1387 case llvm::COFF::IMAGE_FILE_MACHINE_AMD64:
1388 case llvm::COFF::IMAGE_FILE_MACHINE_I386:
1389 case llvm::COFF::IMAGE_FILE_MACHINE_POWERPC:
1390 case llvm::COFF::IMAGE_FILE_MACHINE_POWERPCFP:
1391 case llvm::COFF::IMAGE_FILE_MACHINE_ARM:
1392 case llvm::COFF::IMAGE_FILE_MACHINE_ARMNT:
1393 case llvm::COFF::IMAGE_FILE_MACHINE_THUMB:
1394 case llvm::COFF::IMAGE_FILE_MACHINE_ARM64:
1395 ArchSpec arch;
1397 IsWindowsSubsystem() ? llvm::Triple::Win32
1398 : llvm::Triple::UnknownOS);
1399 return arch;
1400 }
1401 return ArchSpec();
1402}
1403
1405 if (m_coff_header.machine != 0) {
1406 if ((m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0)
1407 return eTypeExecutable;
1408 else
1409 return eTypeSharedLibrary;
1410 }
1411 return eTypeExecutable;
1412}
1413
static llvm::raw_ostream & error(Stream &strm)
static PluginProperties & GetGlobalPluginProperties()
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition: Log.h:337
#define LLDB_LOGF(log,...)
Definition: Log.h:344
#define LLDB_LOG_ERROR(log, error,...)
Definition: Log.h:360
static PluginProperties & GetGlobalPluginProperties()
#define OPT_HEADER_MAGIC_PE32
#define OPT_HEADER_MAGIC_PE32_PLUS
static bool RVASymbolListCompareRVA(const std::pair< uint32_t, uint32_t > &a, const std::pair< uint32_t, uint32_t > &b)
#define IMAGE_NT_SIGNATURE
static UUID GetCoffUUID(llvm::object::COFFObjectFile &coff_obj)
static bool GetDebugLinkContents(const llvm::object::COFFObjectFile &coff_obj, std::string &gnu_debuglink_file, uint32_t &gnu_debuglink_crc)
#define IMAGE_DOS_SIGNATURE
#define LLDB_PLUGIN_DEFINE(PluginName)
Definition: PluginManager.h:31
#define LLDB_SCOPED_TIMERF(...)
Definition: Timer.h:86
ObjectFile::Strata CalculateStrata() override
The object file should be able to calculate the strata of the object file.
static bool SaveCore(const lldb::ProcessSP &process_sp, const lldb_private::FileSpec &outfile, lldb::SaveCoreStyle &core_style, lldb_private::Status &error)
bool IsExecutable() const override
Tells whether this object file is capable of being the main executable for a process.
void DumpSectionHeaders(lldb_private::Stream *s)
std::unique_ptr< llvm::object::COFFObjectFile > m_binary
dos_header_t m_dos_header
lldb_private::DataExtractor ReadImageDataByRVA(uint32_t rva, size_t size)
llvm::StringRef GetSectionName(const section_header_t &sect)
lldb_private::Address GetEntryPointAddress() override
Returns the address of the Entry Point in this object file - if the object file doesn't have an entry...
std::optional< lldb_private::FileSpecList > m_deps_filespec
~ObjectFilePECOFF() override
static bool ParseDOSHeader(lldb_private::DataExtractor &data, dos_header_t &dos_header)
uint32_t GetDependentModules(lldb_private::FileSpecList &files) override
lldb_private::Address GetBaseAddress() override
Returns base address of this object file.
lldb::addr_t m_image_base
void DumpSectionHeader(lldb_private::Stream *s, const section_header_t &sh)
std::unique_ptr< lldb_private::CallFrameInfo > CreateCallFrameInfo() override
Creates a plugin-specific call frame info.
static void DebuggerInitialize(lldb_private::Debugger &debugger)
ObjectFilePECOFF(const lldb::ModuleSP &module_sp, lldb::DataBufferSP data_sp, lldb::offset_t data_offset, const lldb_private::FileSpec *file, lldb::offset_t file_offset, lldb::offset_t length)
ObjectFile::Type CalculateType() override
The object file should be able to calculate its type by looking at its file header and possibly the s...
lldb_private::ArchSpec GetArchitecture() override
Get the ArchSpec for this object file.
static void DumpCOFFHeader(lldb_private::Stream *s, const coff_header_t &header)
bool ParseHeader() override
Attempts to parse the object header.
struct ObjectFilePECOFF::section_header section_header_t
void DumpDependentModules(lldb_private::Stream *s)
lldb_private::UUID m_uuid
lldb_private::UUID GetUUID() override
Gets the UUID for this object file.
std::vector< std::pair< uint32_t, uint32_t > > rva_symbol_list_t
static llvm::StringRef GetPluginNameStatic()
bool SetLoadAddress(lldb_private::Target &target, lldb::addr_t value, bool value_is_offset) override
Sets the load address for an entire module, assuming a rigid slide of sections, if possible in the im...
SectionHeaderColl::iterator SectionHeaderCollIter
SectionHeaderColl m_sect_headers
static lldb_private::ObjectFile * CreateMemoryInstance(const lldb::ModuleSP &module_sp, lldb::WritableDataBufferSP data_sp, const lldb::ProcessSP &process_sp, lldb::addr_t header_addr)
static llvm::StringRef GetPluginDescriptionStatic()
coff_opt_header_t m_coff_header_opt
bool ParseCOFFOptionalHeader(lldb::offset_t *offset_ptr)
bool IsStripped() override
Detect if this object file has been stripped of local symbols.
uint32_t ParseDependentModules()
bool NeedsEndianSwap() const
lldb::addr_t GetFileAddress(uint32_t rva) const
void ParseSymtab(lldb_private::Symtab &symtab) override
Parse the symbol table into the provides symbol table object.
void CreateSections(lldb_private::SectionList &unified_section_list) override
void Dump(lldb_private::Stream *s) override
Dump a description of this object to a Stream.
rva_symbol_list_t AppendFromExportTable(lldb_private::SectionList *sect_list, lldb_private::Symtab &symtab)
coff_header_t m_coff_header
lldb_private::Address GetAddress(uint32_t rva)
static void Initialize()
lldb::ByteOrder GetByteOrder() const override
Gets whether endian swapping should occur when extracting data from this object file.
lldb_private::DataExtractor ReadImageData(uint32_t offset, size_t size)
void AppendFromCOFFSymbolTable(lldb_private::SectionList *sect_list, lldb_private::Symtab &symtab, const rva_symbol_list_t &sorted_exports)
std::optional< lldb_private::FileSpec > GetDebugLink()
Return the contents of the .gnu_debuglink section, if the object file contains it.
bool ParseSectionHeaders(uint32_t offset)
static lldb::SymbolType MapSymbolType(uint16_t coff_symbol_type)
uint32_t GetRVA(const lldb_private::Address &addr) const
uint32_t GetAddressByteSize() const override
Gets the address size in bytes for the current object file.
static void DumpOptCOFFHeader(lldb_private::Stream *s, const coff_opt_header_t &header)
static lldb::SectionType GetSectionType(llvm::StringRef sect_name, const section_header_t &sect)
static ObjectFile * CreateInstance(const lldb::ModuleSP &module_sp, lldb::DataBufferSP data_sp, lldb::offset_t data_offset, const lldb_private::FileSpec *file, lldb::offset_t offset, lldb::offset_t length)
static bool ParseCOFFHeader(lldb_private::DataExtractor &data, lldb::offset_t *offset_ptr, coff_header_t &coff_header)
static bool MagicBytesMatch(lldb::DataBufferSP data_sp)
static void Terminate()
lldb_private::Address m_entry_point_address
static void DumpDOSHeader(lldb_private::Stream *s, const dos_header_t &header)
static size_t 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)
A section + offset based address class.
Definition: Address.h:59
bool ResolveAddressUsingFileSections(lldb::addr_t addr, const SectionList *sections)
Resolve a file virtual address using a section list.
Definition: Address.cpp:248
lldb::SectionSP GetSection() const
Get const accessor for the section.
Definition: Address.h:429
lldb::addr_t GetFileAddress() const
Get the file address.
Definition: Address.cpp:291
lldb::addr_t GetOffset() const
Get the section relative offset value.
Definition: Address.h:319
bool IsValid() const
Check if the object state is valid.
Definition: Address.h:345
bool SetOffset(lldb::addr_t offset)
Set accessor for the offset.
Definition: Address.h:438
An architecture specification class.
Definition: ArchSpec.h:32
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition: ArchSpec.h:463
bool SetTriple(const llvm::Triple &triple)
Architecture triple setter.
Definition: ArchSpec.cpp:750
bool SetArchitecture(ArchitectureType arch_type, uint32_t cpu, uint32_t sub, uint32_t os=0)
Change the architecture object type, CPU type and OS type.
Definition: ArchSpec.cpp:854
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition: ArchSpec.cpp:547
A uniqued constant string class.
Definition: ConstString.h:39
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
Definition: ConstString.h:192
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
Definition: ConstString.h:201
An data extractor class.
Definition: DataExtractor.h:48
const char * GetCStr(lldb::offset_t *offset_ptr) const
Extract a C string from *offset_ptr.
bool ValidOffsetForDataOfSize(lldb::offset_t offset, lldb::offset_t length) const
Test the availability of length bytes of data from offset.
const void * GetData(lldb::offset_t *offset_ptr, lldb::offset_t length) const
Extract length bytes from *offset_ptr.
void SetByteOrder(lldb::ByteOrder byte_order)
Set the byte_order value.
uint32_t GetU32(lldb::offset_t *offset_ptr) const
Extract a uint32_t value from *offset_ptr.
uint16_t GetU16(lldb::offset_t *offset_ptr) const
Extract a uint16_t value from *offset_ptr.
lldb::offset_t SetData(const void *bytes, lldb::offset_t length, lldb::ByteOrder byte_order)
Set data with a buffer that is caller owned.
uint64_t GetMaxU64(lldb::offset_t *offset_ptr, size_t byte_size) const
Extract an unsigned integer of size byte_size from *offset_ptr.
void SetAddressByteSize(uint32_t addr_size)
Set the address byte size.
uint8_t GetU8(lldb::offset_t *offset_ptr) const
Extract a uint8_t value from *offset_ptr.
A class to manage flag bits.
Definition: Debugger.h:77
A file utility class.
Definition: FileSpec.h:56
void SetDirectory(ConstString directory)
Directory string set accessor.
Definition: FileSpec.cpp:334
const ConstString & GetFilename() const
Filename string const get accessor.
Definition: FileSpec.h:240
ConstString GetLastPathComponent() const
Definition: FileSpec.cpp:433
const ConstString & GetDirectory() const
Directory string const get accessor.
Definition: FileSpec.h:223
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition: FileSpec.cpp:366
lldb::ModuleSP GetModule() const
Get const accessor for the module pointer.
Definition: ModuleChild.cpp:24
void Append(const ModuleSpec &spec)
Definition: ModuleSpec.h:308
ArchSpec & GetArchitecture()
Definition: ModuleSpec.h:89
A plug-in interface definition class for object file parsers.
Definition: ObjectFile.h:62
DataExtractor m_data
The data for this object file so things can be parsed lazily.
Definition: ObjectFile.h:744
std::unique_ptr< lldb_private::SectionList > m_sections_up
Definition: ObjectFile.h:748
static lldb::DataBufferSP MapFileData(const FileSpec &file, uint64_t Size, uint64_t Offset)
Definition: ObjectFile.cpp:659
std::unique_ptr< lldb_private::Symtab > m_symtab_up
Definition: ObjectFile.h:749
@ eTypeExecutable
A normal executable.
Definition: ObjectFile.h:71
@ eTypeSharedLibrary
A shared library that can be used during execution.
Definition: ObjectFile.h:79
virtual SectionList * GetSectionList(bool update_module_section_list=true)
Gets the section list for the currently selected architecture (and object for archives).
Definition: ObjectFile.cpp:588
lldb::ProcessWP m_process_wp
Definition: ObjectFile.h:745
static lldb::OptionValuePropertiesSP GetSettingForObjectFilePlugin(Debugger &debugger, ConstString setting_name)
static bool CreateSettingForObjectFilePlugin(Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, ConstString description, bool is_global_property)
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
lldb::SectionSP FindSectionByID(lldb::user_id_t sect_id) const
Definition: Section.cpp:568
size_t GetSize() const
Definition: Section.h:74
size_t AddSection(const lldb::SectionSP &section_sp)
Definition: Section.cpp:469
void Dump(llvm::raw_ostream &s, unsigned indent, Target *target, bool show_header, uint32_t depth) const
Definition: Section.cpp:632
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition: Section.cpp:538
bool SetSectionLoadAddress(const lldb::SectionSP &section_sp, lldb::addr_t load_addr, bool warn_multiple=false)
An error handling class.
Definition: Status.h:44
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition: Stream.h:357
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition: Stream.cpp:130
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:107
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition: Stream.cpp:63
size_t EOL()
Output and End of Line character to the stream.
Definition: Stream.cpp:128
unsigned GetIndentLevel() const
Get the current indentation level.
Definition: Stream.cpp:160
void SetType(lldb::SymbolType type)
Definition: Symbol.h:155
Mangled & GetMangled()
Definition: Symbol.h:131
Address & GetAddressRef()
Definition: Symbol.h:57
lldb::SymbolType GetType() const
Definition: Symbol.h:153
void SetDemangledNameIsSynthesized(bool b)
Definition: Symbol.h:213
ConstString GetDisplayName() const
Definition: Symbol.cpp:121
void SetExternal(bool b)
Definition: Symbol.h:182
void SetID(uint32_t uid)
Definition: Symbol.h:129
Symbol * SymbolAtIndex(size_t idx)
Definition: Symtab.cpp:217
uint32_t AddSymbol(const Symbol &symbol)
Definition: Symtab.cpp:64
size_t GetNumSymbols() const
Definition: Symtab.cpp:77
void Reserve(size_t count)
Definition: Symtab.cpp:51
SectionLoadList & GetSectionLoadList()
Definition: Target.h:1101
bool IsValid() const
Definition: UUID.h:69
#define LLDB_INVALID_CPUTYPE
Definition: lldb-defines.h:95
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:74
#define UINT32_MAX
Definition: lldb-defines.h:19
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition: Log.h:309
bool SaveMiniDump(const lldb::ProcessSP &process_sp, const lldb_private::FileSpec &outfile, lldb_private::Status &error)
Definition: SBAddress.h:15
uint64_t offset_t
Definition: lldb-types.h:87
SymbolType
Symbol types.
@ eSymbolTypeInvalid
@ eSymbolTypeAbsolute
@ eSymbolTypeAdditional
When symbols take more than one entry, the extra entries get this type.
ByteOrder
Byte ordering definitions.
@ eByteOrderLittle
uint64_t user_id_t
Definition: lldb-types.h:84
uint64_t addr_t
Definition: lldb-types.h:83
@ eSectionTypeData
@ eSectionTypeInvalid
@ eSectionTypeDWARFDebugPubNames
@ eSectionTypeZeroFill
@ eSectionTypeDWARFDebugFrame
@ eSectionTypeDWARFDebugLocLists
DWARF v5 .debug_loclists.
@ eSectionTypeDWARFDebugTypes
DWARF .debug_types section.
@ eSectionTypeDWARFDebugMacInfo
@ eSectionTypeOther
@ eSectionTypeDWARFDebugNames
DWARF v5 .debug_names.
@ eSectionTypeEHFrame
@ eSectionTypeDWARFDebugInfo
@ eSectionTypeDWARFDebugRanges
@ eSectionTypeGoSymtab
@ eSectionTypeDWARFDebugLine
@ eSectionTypeDWARFDebugPubTypes
@ eSectionTypeDWARFDebugStr
@ eSectionTypeDWARFDebugLoc
@ eSectionTypeCode
@ eSectionTypeDebug
@ eSectionTypeDWARFDebugAranges
@ eSectionTypeDWARFDebugAbbrev
@ eSectionTypeDataCString
Inlined C string data.
std::vector< data_directory > data_dirs
struct lldb_private::UUID::CvRecordPdb70::@43 Uuid
llvm::support::ulittle32_t Age
Definition: UUID.h:46