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: 81 static ConstString GetSettingName() { 82 return ConstString(ObjectFilePECOFF::GetPluginNameStatic()); 83 } 84 85 PluginProperties() { 86 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName()); 87 m_collection_sp->Initialize(g_objectfilepecoff_properties); 88 } 89 90 llvm::Triple::EnvironmentType ABI() const { 91 return (llvm::Triple::EnvironmentType) 92 m_collection_sp->GetPropertyAtIndexAsEnumeration( 93 nullptr, ePropertyABI, llvm::Triple::UnknownEnvironment); 94 } 95 96 OptionValueDictionary *ModuleABIMap() const { 97 return m_collection_sp->GetPropertyAtIndexAsOptionValueDictionary( 98 nullptr, ePropertyModuleABIMap); 99 } 100 }; 101 102 static PluginProperties &GetGlobalPluginProperties() { 103 static PluginProperties g_settings; 104 return g_settings; 105 } 106 107 } // namespace 108 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 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 178 void ObjectFilePECOFF::Initialize() { 179 PluginManager::RegisterPlugin(GetPluginNameStatic(), 180 GetPluginDescriptionStatic(), CreateInstance, 181 CreateMemoryInstance, GetModuleSpecifications, 182 SaveCore, DebuggerInitialize); 183 } 184 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 196 void ObjectFilePECOFF::Terminate() { 197 PluginManager::UnregisterPlugin(CreateInstance); 198 } 199 200 llvm::StringRef ObjectFilePECOFF::GetPluginDescriptionStatic() { 201 return "Portable Executable and Common Object File Format object file reader " 202 "(32 and 64 bit)"; 203 } 204 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 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 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 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 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 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 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 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_sect_headers(), 418 m_entry_point_address(), m_deps_filespec() { 419 ::memset(&m_dos_header, 0, sizeof(m_dos_header)); 420 ::memset(&m_coff_header, 0, sizeof(m_coff_header)); 421 } 422 423 ObjectFilePECOFF::ObjectFilePECOFF(const lldb::ModuleSP &module_sp, 424 WritableDataBufferSP header_data_sp, 425 const lldb::ProcessSP &process_sp, 426 addr_t header_addr) 427 : ObjectFile(module_sp, process_sp, header_addr, header_data_sp), 428 m_dos_header(), m_coff_header(), m_sect_headers(), 429 m_entry_point_address(), m_deps_filespec() { 430 ::memset(&m_dos_header, 0, sizeof(m_dos_header)); 431 ::memset(&m_coff_header, 0, sizeof(m_coff_header)); 432 } 433 434 ObjectFilePECOFF::~ObjectFilePECOFF() = default; 435 436 bool ObjectFilePECOFF::ParseHeader() { 437 ModuleSP module_sp(GetModule()); 438 if (module_sp) { 439 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); 440 m_sect_headers.clear(); 441 m_data.SetByteOrder(eByteOrderLittle); 442 lldb::offset_t offset = 0; 443 444 if (ParseDOSHeader(m_data, m_dos_header)) { 445 offset = m_dos_header.e_lfanew; 446 uint32_t pe_signature = m_data.GetU32(&offset); 447 if (pe_signature != IMAGE_NT_SIGNATURE) 448 return false; 449 if (ParseCOFFHeader(m_data, &offset, m_coff_header)) { 450 if (m_coff_header.hdrsize > 0) 451 ParseCOFFOptionalHeader(&offset); 452 ParseSectionHeaders(offset); 453 } 454 m_data.SetAddressByteSize(GetAddressByteSize()); 455 return true; 456 } 457 } 458 return false; 459 } 460 461 bool ObjectFilePECOFF::SetLoadAddress(Target &target, addr_t value, 462 bool value_is_offset) { 463 bool changed = false; 464 ModuleSP module_sp = GetModule(); 465 if (module_sp) { 466 size_t num_loaded_sections = 0; 467 SectionList *section_list = GetSectionList(); 468 if (section_list) { 469 if (!value_is_offset) { 470 value -= m_image_base; 471 } 472 473 const size_t num_sections = section_list->GetSize(); 474 size_t sect_idx = 0; 475 476 for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) { 477 // Iterate through the object file sections to find all of the sections 478 // that have SHF_ALLOC in their flag bits. 479 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx)); 480 if (section_sp && !section_sp->IsThreadSpecific()) { 481 if (target.GetSectionLoadList().SetSectionLoadAddress( 482 section_sp, section_sp->GetFileAddress() + value)) 483 ++num_loaded_sections; 484 } 485 } 486 changed = num_loaded_sections > 0; 487 } 488 } 489 return changed; 490 } 491 492 ByteOrder ObjectFilePECOFF::GetByteOrder() const { return eByteOrderLittle; } 493 494 bool ObjectFilePECOFF::IsExecutable() const { 495 return (m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0; 496 } 497 498 uint32_t ObjectFilePECOFF::GetAddressByteSize() const { 499 if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32_PLUS) 500 return 8; 501 else if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32) 502 return 4; 503 return 4; 504 } 505 506 // NeedsEndianSwap 507 // 508 // Return true if an endian swap needs to occur when extracting data from this 509 // file. 510 bool ObjectFilePECOFF::NeedsEndianSwap() const { 511 #if defined(__LITTLE_ENDIAN__) 512 return false; 513 #else 514 return true; 515 #endif 516 } 517 // ParseDOSHeader 518 bool ObjectFilePECOFF::ParseDOSHeader(DataExtractor &data, 519 dos_header_t &dos_header) { 520 bool success = false; 521 lldb::offset_t offset = 0; 522 success = data.ValidOffsetForDataOfSize(0, sizeof(dos_header)); 523 524 if (success) { 525 dos_header.e_magic = data.GetU16(&offset); // Magic number 526 success = dos_header.e_magic == IMAGE_DOS_SIGNATURE; 527 528 if (success) { 529 dos_header.e_cblp = data.GetU16(&offset); // Bytes on last page of file 530 dos_header.e_cp = data.GetU16(&offset); // Pages in file 531 dos_header.e_crlc = data.GetU16(&offset); // Relocations 532 dos_header.e_cparhdr = 533 data.GetU16(&offset); // Size of header in paragraphs 534 dos_header.e_minalloc = 535 data.GetU16(&offset); // Minimum extra paragraphs needed 536 dos_header.e_maxalloc = 537 data.GetU16(&offset); // Maximum extra paragraphs needed 538 dos_header.e_ss = data.GetU16(&offset); // Initial (relative) SS value 539 dos_header.e_sp = data.GetU16(&offset); // Initial SP value 540 dos_header.e_csum = data.GetU16(&offset); // Checksum 541 dos_header.e_ip = data.GetU16(&offset); // Initial IP value 542 dos_header.e_cs = data.GetU16(&offset); // Initial (relative) CS value 543 dos_header.e_lfarlc = 544 data.GetU16(&offset); // File address of relocation table 545 dos_header.e_ovno = data.GetU16(&offset); // Overlay number 546 547 dos_header.e_res[0] = data.GetU16(&offset); // Reserved words 548 dos_header.e_res[1] = data.GetU16(&offset); // Reserved words 549 dos_header.e_res[2] = data.GetU16(&offset); // Reserved words 550 dos_header.e_res[3] = data.GetU16(&offset); // Reserved words 551 552 dos_header.e_oemid = 553 data.GetU16(&offset); // OEM identifier (for e_oeminfo) 554 dos_header.e_oeminfo = 555 data.GetU16(&offset); // OEM information; e_oemid specific 556 dos_header.e_res2[0] = data.GetU16(&offset); // Reserved words 557 dos_header.e_res2[1] = data.GetU16(&offset); // Reserved words 558 dos_header.e_res2[2] = data.GetU16(&offset); // Reserved words 559 dos_header.e_res2[3] = data.GetU16(&offset); // Reserved words 560 dos_header.e_res2[4] = data.GetU16(&offset); // Reserved words 561 dos_header.e_res2[5] = data.GetU16(&offset); // Reserved words 562 dos_header.e_res2[6] = data.GetU16(&offset); // Reserved words 563 dos_header.e_res2[7] = data.GetU16(&offset); // Reserved words 564 dos_header.e_res2[8] = data.GetU16(&offset); // Reserved words 565 dos_header.e_res2[9] = data.GetU16(&offset); // Reserved words 566 567 dos_header.e_lfanew = 568 data.GetU32(&offset); // File address of new exe header 569 } 570 } 571 if (!success) 572 memset(&dos_header, 0, sizeof(dos_header)); 573 return success; 574 } 575 576 // ParserCOFFHeader 577 bool ObjectFilePECOFF::ParseCOFFHeader(DataExtractor &data, 578 lldb::offset_t *offset_ptr, 579 coff_header_t &coff_header) { 580 bool success = 581 data.ValidOffsetForDataOfSize(*offset_ptr, sizeof(coff_header)); 582 if (success) { 583 coff_header.machine = data.GetU16(offset_ptr); 584 coff_header.nsects = data.GetU16(offset_ptr); 585 coff_header.modtime = data.GetU32(offset_ptr); 586 coff_header.symoff = data.GetU32(offset_ptr); 587 coff_header.nsyms = data.GetU32(offset_ptr); 588 coff_header.hdrsize = data.GetU16(offset_ptr); 589 coff_header.flags = data.GetU16(offset_ptr); 590 } 591 if (!success) 592 memset(&coff_header, 0, sizeof(coff_header)); 593 return success; 594 } 595 596 bool ObjectFilePECOFF::ParseCOFFOptionalHeader(lldb::offset_t *offset_ptr) { 597 bool success = false; 598 const lldb::offset_t end_offset = *offset_ptr + m_coff_header.hdrsize; 599 if (*offset_ptr < end_offset) { 600 success = true; 601 m_coff_header_opt.magic = m_data.GetU16(offset_ptr); 602 m_coff_header_opt.major_linker_version = m_data.GetU8(offset_ptr); 603 m_coff_header_opt.minor_linker_version = m_data.GetU8(offset_ptr); 604 m_coff_header_opt.code_size = m_data.GetU32(offset_ptr); 605 m_coff_header_opt.data_size = m_data.GetU32(offset_ptr); 606 m_coff_header_opt.bss_size = m_data.GetU32(offset_ptr); 607 m_coff_header_opt.entry = m_data.GetU32(offset_ptr); 608 m_coff_header_opt.code_offset = m_data.GetU32(offset_ptr); 609 610 const uint32_t addr_byte_size = GetAddressByteSize(); 611 612 if (*offset_ptr < end_offset) { 613 if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32) { 614 // PE32 only 615 m_coff_header_opt.data_offset = m_data.GetU32(offset_ptr); 616 } else 617 m_coff_header_opt.data_offset = 0; 618 619 if (*offset_ptr < end_offset) { 620 m_coff_header_opt.image_base = 621 m_data.GetMaxU64(offset_ptr, addr_byte_size); 622 m_coff_header_opt.sect_alignment = m_data.GetU32(offset_ptr); 623 m_coff_header_opt.file_alignment = m_data.GetU32(offset_ptr); 624 m_coff_header_opt.major_os_system_version = m_data.GetU16(offset_ptr); 625 m_coff_header_opt.minor_os_system_version = m_data.GetU16(offset_ptr); 626 m_coff_header_opt.major_image_version = m_data.GetU16(offset_ptr); 627 m_coff_header_opt.minor_image_version = m_data.GetU16(offset_ptr); 628 m_coff_header_opt.major_subsystem_version = m_data.GetU16(offset_ptr); 629 m_coff_header_opt.minor_subsystem_version = m_data.GetU16(offset_ptr); 630 m_coff_header_opt.reserved1 = m_data.GetU32(offset_ptr); 631 m_coff_header_opt.image_size = m_data.GetU32(offset_ptr); 632 m_coff_header_opt.header_size = m_data.GetU32(offset_ptr); 633 m_coff_header_opt.checksum = m_data.GetU32(offset_ptr); 634 m_coff_header_opt.subsystem = m_data.GetU16(offset_ptr); 635 m_coff_header_opt.dll_flags = m_data.GetU16(offset_ptr); 636 m_coff_header_opt.stack_reserve_size = 637 m_data.GetMaxU64(offset_ptr, addr_byte_size); 638 m_coff_header_opt.stack_commit_size = 639 m_data.GetMaxU64(offset_ptr, addr_byte_size); 640 m_coff_header_opt.heap_reserve_size = 641 m_data.GetMaxU64(offset_ptr, addr_byte_size); 642 m_coff_header_opt.heap_commit_size = 643 m_data.GetMaxU64(offset_ptr, addr_byte_size); 644 m_coff_header_opt.loader_flags = m_data.GetU32(offset_ptr); 645 uint32_t num_data_dir_entries = m_data.GetU32(offset_ptr); 646 m_coff_header_opt.data_dirs.clear(); 647 m_coff_header_opt.data_dirs.resize(num_data_dir_entries); 648 uint32_t i; 649 for (i = 0; i < num_data_dir_entries; i++) { 650 m_coff_header_opt.data_dirs[i].vmaddr = m_data.GetU32(offset_ptr); 651 m_coff_header_opt.data_dirs[i].vmsize = m_data.GetU32(offset_ptr); 652 } 653 654 m_image_base = m_coff_header_opt.image_base; 655 } 656 } 657 } 658 // Make sure we are on track for section data which follows 659 *offset_ptr = end_offset; 660 return success; 661 } 662 663 uint32_t ObjectFilePECOFF::GetRVA(const Address &addr) const { 664 return addr.GetFileAddress() - m_image_base; 665 } 666 667 Address ObjectFilePECOFF::GetAddress(uint32_t rva) { 668 SectionList *sect_list = GetSectionList(); 669 if (!sect_list) 670 return Address(GetFileAddress(rva)); 671 672 return Address(GetFileAddress(rva), sect_list); 673 } 674 675 lldb::addr_t ObjectFilePECOFF::GetFileAddress(uint32_t rva) const { 676 return m_image_base + rva; 677 } 678 679 DataExtractor ObjectFilePECOFF::ReadImageData(uint32_t offset, size_t size) { 680 if (!size) 681 return {}; 682 683 if (m_data.ValidOffsetForDataOfSize(offset, size)) 684 return DataExtractor(m_data, offset, size); 685 686 ProcessSP process_sp(m_process_wp.lock()); 687 DataExtractor data; 688 if (process_sp) { 689 auto data_up = std::make_unique<DataBufferHeap>(size, 0); 690 Status readmem_error; 691 size_t bytes_read = 692 process_sp->ReadMemory(m_image_base + offset, data_up->GetBytes(), 693 data_up->GetByteSize(), readmem_error); 694 if (bytes_read == size) { 695 DataBufferSP buffer_sp(data_up.release()); 696 data.SetData(buffer_sp, 0, buffer_sp->GetByteSize()); 697 } 698 } 699 return data; 700 } 701 702 DataExtractor ObjectFilePECOFF::ReadImageDataByRVA(uint32_t rva, size_t size) { 703 Address addr = GetAddress(rva); 704 SectionSP sect = addr.GetSection(); 705 if (!sect) 706 return {}; 707 rva = sect->GetFileOffset() + addr.GetOffset(); 708 709 return ReadImageData(rva, size); 710 } 711 712 // ParseSectionHeaders 713 bool ObjectFilePECOFF::ParseSectionHeaders( 714 uint32_t section_header_data_offset) { 715 const uint32_t nsects = m_coff_header.nsects; 716 m_sect_headers.clear(); 717 718 if (nsects > 0) { 719 const size_t section_header_byte_size = nsects * sizeof(section_header_t); 720 DataExtractor section_header_data = 721 ReadImageData(section_header_data_offset, section_header_byte_size); 722 723 lldb::offset_t offset = 0; 724 if (section_header_data.ValidOffsetForDataOfSize( 725 offset, section_header_byte_size)) { 726 m_sect_headers.resize(nsects); 727 728 for (uint32_t idx = 0; idx < nsects; ++idx) { 729 const void *name_data = section_header_data.GetData(&offset, 8); 730 if (name_data) { 731 memcpy(m_sect_headers[idx].name, name_data, 8); 732 m_sect_headers[idx].vmsize = section_header_data.GetU32(&offset); 733 m_sect_headers[idx].vmaddr = section_header_data.GetU32(&offset); 734 m_sect_headers[idx].size = section_header_data.GetU32(&offset); 735 m_sect_headers[idx].offset = section_header_data.GetU32(&offset); 736 m_sect_headers[idx].reloff = section_header_data.GetU32(&offset); 737 m_sect_headers[idx].lineoff = section_header_data.GetU32(&offset); 738 m_sect_headers[idx].nreloc = section_header_data.GetU16(&offset); 739 m_sect_headers[idx].nline = section_header_data.GetU16(&offset); 740 m_sect_headers[idx].flags = section_header_data.GetU32(&offset); 741 } 742 } 743 } 744 } 745 746 return !m_sect_headers.empty(); 747 } 748 749 llvm::StringRef ObjectFilePECOFF::GetSectionName(const section_header_t §) { 750 llvm::StringRef hdr_name(sect.name, llvm::array_lengthof(sect.name)); 751 hdr_name = hdr_name.split('\0').first; 752 if (hdr_name.consume_front("/")) { 753 lldb::offset_t stroff; 754 if (!to_integer(hdr_name, stroff, 10)) 755 return ""; 756 lldb::offset_t string_file_offset = 757 m_coff_header.symoff + (m_coff_header.nsyms * 18) + stroff; 758 if (const char *name = m_data.GetCStr(&string_file_offset)) 759 return name; 760 return ""; 761 } 762 return hdr_name; 763 } 764 765 void ObjectFilePECOFF::ParseSymtab(Symtab &symtab) { 766 SectionList *sect_list = GetSectionList(); 767 const uint32_t num_syms = m_coff_header.nsyms; 768 if (m_file && num_syms > 0 && m_coff_header.symoff > 0) { 769 const uint32_t symbol_size = 18; 770 const size_t symbol_data_size = num_syms * symbol_size; 771 // Include the 4-byte string table size at the end of the symbols 772 DataExtractor symtab_data = 773 ReadImageData(m_coff_header.symoff, symbol_data_size + 4); 774 lldb::offset_t offset = symbol_data_size; 775 const uint32_t strtab_size = symtab_data.GetU32(&offset); 776 if (strtab_size > 0) { 777 DataExtractor strtab_data = ReadImageData( 778 m_coff_header.symoff + symbol_data_size, strtab_size); 779 780 offset = 0; 781 std::string symbol_name; 782 Symbol *symbols = symtab.Resize(num_syms); 783 for (uint32_t i = 0; i < num_syms; ++i) { 784 coff_symbol_t symbol; 785 const uint32_t symbol_offset = offset; 786 const char *symbol_name_cstr = nullptr; 787 // If the first 4 bytes of the symbol string are zero, then they 788 // are followed by a 4-byte string table offset. Else these 789 // 8 bytes contain the symbol name 790 if (symtab_data.GetU32(&offset) == 0) { 791 // Long string that doesn't fit into the symbol table name, so 792 // now we must read the 4 byte string table offset 793 uint32_t strtab_offset = symtab_data.GetU32(&offset); 794 symbol_name_cstr = strtab_data.PeekCStr(strtab_offset); 795 symbol_name.assign(symbol_name_cstr); 796 } else { 797 // Short string that fits into the symbol table name which is 8 798 // bytes 799 offset += sizeof(symbol.name) - 4; // Skip remaining 800 symbol_name_cstr = symtab_data.PeekCStr(symbol_offset); 801 if (symbol_name_cstr == nullptr) 802 break; 803 symbol_name.assign(symbol_name_cstr, sizeof(symbol.name)); 804 } 805 symbol.value = symtab_data.GetU32(&offset); 806 symbol.sect = symtab_data.GetU16(&offset); 807 symbol.type = symtab_data.GetU16(&offset); 808 symbol.storage = symtab_data.GetU8(&offset); 809 symbol.naux = symtab_data.GetU8(&offset); 810 symbols[i].GetMangled().SetValue(ConstString(symbol_name.c_str())); 811 if ((int16_t)symbol.sect >= 1) { 812 Address symbol_addr(sect_list->FindSectionByID(symbol.sect), 813 symbol.value); 814 symbols[i].GetAddressRef() = symbol_addr; 815 symbols[i].SetType(MapSymbolType(symbol.type)); 816 } 817 818 if (symbol.naux > 0) { 819 i += symbol.naux; 820 offset += symbol.naux * symbol_size; 821 } 822 } 823 } 824 } 825 826 // Read export header 827 if (coff_data_dir_export_table < m_coff_header_opt.data_dirs.size() && 828 m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmsize > 0 && 829 m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr > 0) { 830 export_directory_entry export_table; 831 uint32_t data_start = 832 m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr; 833 834 DataExtractor symtab_data = ReadImageDataByRVA( 835 data_start, m_coff_header_opt.data_dirs[0].vmsize); 836 lldb::offset_t offset = 0; 837 838 // Read export_table header 839 export_table.characteristics = symtab_data.GetU32(&offset); 840 export_table.time_date_stamp = symtab_data.GetU32(&offset); 841 export_table.major_version = symtab_data.GetU16(&offset); 842 export_table.minor_version = symtab_data.GetU16(&offset); 843 export_table.name = symtab_data.GetU32(&offset); 844 export_table.base = symtab_data.GetU32(&offset); 845 export_table.number_of_functions = symtab_data.GetU32(&offset); 846 export_table.number_of_names = symtab_data.GetU32(&offset); 847 export_table.address_of_functions = symtab_data.GetU32(&offset); 848 export_table.address_of_names = symtab_data.GetU32(&offset); 849 export_table.address_of_name_ordinals = symtab_data.GetU32(&offset); 850 851 bool has_ordinal = export_table.address_of_name_ordinals != 0; 852 853 lldb::offset_t name_offset = export_table.address_of_names - data_start; 854 lldb::offset_t name_ordinal_offset = 855 export_table.address_of_name_ordinals - data_start; 856 857 Symbol *symbols = symtab.Resize(export_table.number_of_names); 858 859 std::string symbol_name; 860 861 // Read each export table entry 862 for (size_t i = 0; i < export_table.number_of_names; ++i) { 863 uint32_t name_ordinal = 864 has_ordinal ? symtab_data.GetU16(&name_ordinal_offset) : i; 865 uint32_t name_address = symtab_data.GetU32(&name_offset); 866 867 const char *symbol_name_cstr = 868 symtab_data.PeekCStr(name_address - data_start); 869 symbol_name.assign(symbol_name_cstr); 870 871 lldb::offset_t function_offset = export_table.address_of_functions - 872 data_start + 873 sizeof(uint32_t) * name_ordinal; 874 uint32_t function_rva = symtab_data.GetU32(&function_offset); 875 876 Address symbol_addr(m_coff_header_opt.image_base + function_rva, 877 sect_list); 878 symbols[i].GetMangled().SetValue(ConstString(symbol_name.c_str())); 879 symbols[i].GetAddressRef() = symbol_addr; 880 symbols[i].SetType(lldb::eSymbolTypeCode); 881 symbols[i].SetDebug(true); 882 } 883 } 884 } 885 886 std::unique_ptr<CallFrameInfo> ObjectFilePECOFF::CreateCallFrameInfo() { 887 if (coff_data_dir_exception_table >= m_coff_header_opt.data_dirs.size()) 888 return {}; 889 890 data_directory data_dir_exception = 891 m_coff_header_opt.data_dirs[coff_data_dir_exception_table]; 892 if (!data_dir_exception.vmaddr) 893 return {}; 894 895 if (m_coff_header.machine != llvm::COFF::IMAGE_FILE_MACHINE_AMD64) 896 return {}; 897 898 return std::make_unique<PECallFrameInfo>(*this, data_dir_exception.vmaddr, 899 data_dir_exception.vmsize); 900 } 901 902 bool ObjectFilePECOFF::IsStripped() { 903 // TODO: determine this for COFF 904 return false; 905 } 906 907 SectionType ObjectFilePECOFF::GetSectionType(llvm::StringRef sect_name, 908 const section_header_t §) { 909 ConstString const_sect_name(sect_name); 910 static ConstString g_code_sect_name(".code"); 911 static ConstString g_CODE_sect_name("CODE"); 912 static ConstString g_data_sect_name(".data"); 913 static ConstString g_DATA_sect_name("DATA"); 914 static ConstString g_bss_sect_name(".bss"); 915 static ConstString g_BSS_sect_name("BSS"); 916 917 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_CODE && 918 ((const_sect_name == g_code_sect_name) || 919 (const_sect_name == g_CODE_sect_name))) { 920 return eSectionTypeCode; 921 } 922 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA && 923 ((const_sect_name == g_data_sect_name) || 924 (const_sect_name == g_DATA_sect_name))) { 925 if (sect.size == 0 && sect.offset == 0) 926 return eSectionTypeZeroFill; 927 else 928 return eSectionTypeData; 929 } 930 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA && 931 ((const_sect_name == g_bss_sect_name) || 932 (const_sect_name == g_BSS_sect_name))) { 933 if (sect.size == 0) 934 return eSectionTypeZeroFill; 935 else 936 return eSectionTypeData; 937 } 938 939 SectionType section_type = 940 llvm::StringSwitch<SectionType>(sect_name) 941 .Case(".debug", eSectionTypeDebug) 942 .Case(".stabstr", eSectionTypeDataCString) 943 .Case(".reloc", eSectionTypeOther) 944 .Case(".debug_abbrev", eSectionTypeDWARFDebugAbbrev) 945 .Case(".debug_aranges", eSectionTypeDWARFDebugAranges) 946 .Case(".debug_frame", eSectionTypeDWARFDebugFrame) 947 .Case(".debug_info", eSectionTypeDWARFDebugInfo) 948 .Case(".debug_line", eSectionTypeDWARFDebugLine) 949 .Case(".debug_loc", eSectionTypeDWARFDebugLoc) 950 .Case(".debug_loclists", eSectionTypeDWARFDebugLocLists) 951 .Case(".debug_macinfo", eSectionTypeDWARFDebugMacInfo) 952 .Case(".debug_names", eSectionTypeDWARFDebugNames) 953 .Case(".debug_pubnames", eSectionTypeDWARFDebugPubNames) 954 .Case(".debug_pubtypes", eSectionTypeDWARFDebugPubTypes) 955 .Case(".debug_ranges", eSectionTypeDWARFDebugRanges) 956 .Case(".debug_str", eSectionTypeDWARFDebugStr) 957 .Case(".debug_types", eSectionTypeDWARFDebugTypes) 958 // .eh_frame can be truncated to 8 chars. 959 .Cases(".eh_frame", ".eh_fram", eSectionTypeEHFrame) 960 .Case(".gosymtab", eSectionTypeGoSymtab) 961 .Default(eSectionTypeInvalid); 962 if (section_type != eSectionTypeInvalid) 963 return section_type; 964 965 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_CODE) 966 return eSectionTypeCode; 967 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA) 968 return eSectionTypeData; 969 if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) { 970 if (sect.size == 0) 971 return eSectionTypeZeroFill; 972 else 973 return eSectionTypeData; 974 } 975 return eSectionTypeOther; 976 } 977 978 void ObjectFilePECOFF::CreateSections(SectionList &unified_section_list) { 979 if (m_sections_up) 980 return; 981 m_sections_up = std::make_unique<SectionList>(); 982 ModuleSP module_sp(GetModule()); 983 if (module_sp) { 984 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); 985 986 SectionSP header_sp = std::make_shared<Section>( 987 module_sp, this, ~user_id_t(0), ConstString("PECOFF header"), 988 eSectionTypeOther, m_coff_header_opt.image_base, 989 m_coff_header_opt.header_size, 990 /*file_offset*/ 0, m_coff_header_opt.header_size, 991 m_coff_header_opt.sect_alignment, 992 /*flags*/ 0); 993 header_sp->SetPermissions(ePermissionsReadable); 994 m_sections_up->AddSection(header_sp); 995 unified_section_list.AddSection(header_sp); 996 997 const uint32_t nsects = m_sect_headers.size(); 998 ModuleSP module_sp(GetModule()); 999 for (uint32_t idx = 0; idx < nsects; ++idx) { 1000 llvm::StringRef sect_name = GetSectionName(m_sect_headers[idx]); 1001 ConstString const_sect_name(sect_name); 1002 SectionType section_type = GetSectionType(sect_name, m_sect_headers[idx]); 1003 1004 SectionSP section_sp(new Section( 1005 module_sp, // Module to which this section belongs 1006 this, // Object file to which this section belongs 1007 idx + 1, // Section ID is the 1 based section index. 1008 const_sect_name, // Name of this section 1009 section_type, 1010 m_coff_header_opt.image_base + 1011 m_sect_headers[idx].vmaddr, // File VM address == addresses as 1012 // they are found in the object file 1013 m_sect_headers[idx].vmsize, // VM size in bytes of this section 1014 m_sect_headers[idx] 1015 .offset, // Offset to the data for this section in the file 1016 m_sect_headers[idx] 1017 .size, // Size in bytes of this section as found in the file 1018 m_coff_header_opt.sect_alignment, // Section alignment 1019 m_sect_headers[idx].flags)); // Flags for this section 1020 1021 uint32_t permissions = 0; 1022 if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_EXECUTE) 1023 permissions |= ePermissionsExecutable; 1024 if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_READ) 1025 permissions |= ePermissionsReadable; 1026 if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_WRITE) 1027 permissions |= ePermissionsWritable; 1028 section_sp->SetPermissions(permissions); 1029 1030 m_sections_up->AddSection(section_sp); 1031 unified_section_list.AddSection(section_sp); 1032 } 1033 } 1034 } 1035 1036 UUID ObjectFilePECOFF::GetUUID() { 1037 if (m_uuid.IsValid()) 1038 return m_uuid; 1039 1040 if (!CreateBinary()) 1041 return UUID(); 1042 1043 m_uuid = GetCoffUUID(*m_binary); 1044 return m_uuid; 1045 } 1046 1047 llvm::Optional<FileSpec> ObjectFilePECOFF::GetDebugLink() { 1048 std::string gnu_debuglink_file; 1049 uint32_t gnu_debuglink_crc; 1050 if (GetDebugLinkContents(*m_binary, gnu_debuglink_file, gnu_debuglink_crc)) 1051 return FileSpec(gnu_debuglink_file); 1052 return llvm::None; 1053 } 1054 1055 uint32_t ObjectFilePECOFF::ParseDependentModules() { 1056 ModuleSP module_sp(GetModule()); 1057 if (!module_sp) 1058 return 0; 1059 1060 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); 1061 if (m_deps_filespec) 1062 return m_deps_filespec->GetSize(); 1063 1064 // Cache coff binary if it is not done yet. 1065 if (!CreateBinary()) 1066 return 0; 1067 1068 Log *log = GetLog(LLDBLog::Object); 1069 LLDB_LOG(log, "this = {0}, module = {1} ({2}), file = {3}, binary = {4}", 1070 this, GetModule().get(), GetModule()->GetSpecificationDescription(), 1071 m_file.GetPath(), m_binary.get()); 1072 1073 m_deps_filespec = FileSpecList(); 1074 1075 for (const auto &entry : m_binary->import_directories()) { 1076 llvm::StringRef dll_name; 1077 // Report a bogus entry. 1078 if (llvm::Error e = entry.getName(dll_name)) { 1079 LLDB_LOGF(log, 1080 "ObjectFilePECOFF::ParseDependentModules() - failed to get " 1081 "import directory entry name: %s", 1082 llvm::toString(std::move(e)).c_str()); 1083 continue; 1084 } 1085 1086 // At this moment we only have the base name of the DLL. The full path can 1087 // only be seen after the dynamic loading. Our best guess is Try to get it 1088 // with the help of the object file's directory. 1089 llvm::SmallString<128> dll_fullpath; 1090 FileSpec dll_specs(dll_name); 1091 dll_specs.GetDirectory().SetString(m_file.GetDirectory().GetCString()); 1092 1093 if (!llvm::sys::fs::real_path(dll_specs.GetPath(), dll_fullpath)) 1094 m_deps_filespec->EmplaceBack(dll_fullpath); 1095 else { 1096 // Known DLLs or DLL not found in the object file directory. 1097 m_deps_filespec->EmplaceBack(dll_name); 1098 } 1099 } 1100 return m_deps_filespec->GetSize(); 1101 } 1102 1103 uint32_t ObjectFilePECOFF::GetDependentModules(FileSpecList &files) { 1104 auto num_modules = ParseDependentModules(); 1105 auto original_size = files.GetSize(); 1106 1107 for (unsigned i = 0; i < num_modules; ++i) 1108 files.AppendIfUnique(m_deps_filespec->GetFileSpecAtIndex(i)); 1109 1110 return files.GetSize() - original_size; 1111 } 1112 1113 lldb_private::Address ObjectFilePECOFF::GetEntryPointAddress() { 1114 if (m_entry_point_address.IsValid()) 1115 return m_entry_point_address; 1116 1117 if (!ParseHeader() || !IsExecutable()) 1118 return m_entry_point_address; 1119 1120 SectionList *section_list = GetSectionList(); 1121 addr_t file_addr = m_coff_header_opt.entry + m_coff_header_opt.image_base; 1122 1123 if (!section_list) 1124 m_entry_point_address.SetOffset(file_addr); 1125 else 1126 m_entry_point_address.ResolveAddressUsingFileSections(file_addr, 1127 section_list); 1128 return m_entry_point_address; 1129 } 1130 1131 Address ObjectFilePECOFF::GetBaseAddress() { 1132 return Address(GetSectionList()->GetSectionAtIndex(0), 0); 1133 } 1134 1135 // Dump 1136 // 1137 // Dump the specifics of the runtime file container (such as any headers 1138 // segments, sections, etc). 1139 void ObjectFilePECOFF::Dump(Stream *s) { 1140 ModuleSP module_sp(GetModule()); 1141 if (module_sp) { 1142 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); 1143 s->Printf("%p: ", static_cast<void *>(this)); 1144 s->Indent(); 1145 s->PutCString("ObjectFilePECOFF"); 1146 1147 ArchSpec header_arch = GetArchitecture(); 1148 1149 *s << ", file = '" << m_file 1150 << "', arch = " << header_arch.GetArchitectureName() << "\n"; 1151 1152 SectionList *sections = GetSectionList(); 1153 if (sections) 1154 sections->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true, 1155 UINT32_MAX); 1156 1157 if (m_symtab_up) 1158 m_symtab_up->Dump(s, nullptr, eSortOrderNone); 1159 1160 if (m_dos_header.e_magic) 1161 DumpDOSHeader(s, m_dos_header); 1162 if (m_coff_header.machine) { 1163 DumpCOFFHeader(s, m_coff_header); 1164 if (m_coff_header.hdrsize) 1165 DumpOptCOFFHeader(s, m_coff_header_opt); 1166 } 1167 s->EOL(); 1168 DumpSectionHeaders(s); 1169 s->EOL(); 1170 1171 DumpDependentModules(s); 1172 s->EOL(); 1173 } 1174 } 1175 1176 // DumpDOSHeader 1177 // 1178 // Dump the MS-DOS header to the specified output stream 1179 void ObjectFilePECOFF::DumpDOSHeader(Stream *s, const dos_header_t &header) { 1180 s->PutCString("MSDOS Header\n"); 1181 s->Printf(" e_magic = 0x%4.4x\n", header.e_magic); 1182 s->Printf(" e_cblp = 0x%4.4x\n", header.e_cblp); 1183 s->Printf(" e_cp = 0x%4.4x\n", header.e_cp); 1184 s->Printf(" e_crlc = 0x%4.4x\n", header.e_crlc); 1185 s->Printf(" e_cparhdr = 0x%4.4x\n", header.e_cparhdr); 1186 s->Printf(" e_minalloc = 0x%4.4x\n", header.e_minalloc); 1187 s->Printf(" e_maxalloc = 0x%4.4x\n", header.e_maxalloc); 1188 s->Printf(" e_ss = 0x%4.4x\n", header.e_ss); 1189 s->Printf(" e_sp = 0x%4.4x\n", header.e_sp); 1190 s->Printf(" e_csum = 0x%4.4x\n", header.e_csum); 1191 s->Printf(" e_ip = 0x%4.4x\n", header.e_ip); 1192 s->Printf(" e_cs = 0x%4.4x\n", header.e_cs); 1193 s->Printf(" e_lfarlc = 0x%4.4x\n", header.e_lfarlc); 1194 s->Printf(" e_ovno = 0x%4.4x\n", header.e_ovno); 1195 s->Printf(" e_res[4] = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n", 1196 header.e_res[0], header.e_res[1], header.e_res[2], header.e_res[3]); 1197 s->Printf(" e_oemid = 0x%4.4x\n", header.e_oemid); 1198 s->Printf(" e_oeminfo = 0x%4.4x\n", header.e_oeminfo); 1199 s->Printf(" e_res2[10] = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, " 1200 "0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n", 1201 header.e_res2[0], header.e_res2[1], header.e_res2[2], 1202 header.e_res2[3], header.e_res2[4], header.e_res2[5], 1203 header.e_res2[6], header.e_res2[7], header.e_res2[8], 1204 header.e_res2[9]); 1205 s->Printf(" e_lfanew = 0x%8.8x\n", header.e_lfanew); 1206 } 1207 1208 // DumpCOFFHeader 1209 // 1210 // Dump the COFF header to the specified output stream 1211 void ObjectFilePECOFF::DumpCOFFHeader(Stream *s, const coff_header_t &header) { 1212 s->PutCString("COFF Header\n"); 1213 s->Printf(" machine = 0x%4.4x\n", header.machine); 1214 s->Printf(" nsects = 0x%4.4x\n", header.nsects); 1215 s->Printf(" modtime = 0x%8.8x\n", header.modtime); 1216 s->Printf(" symoff = 0x%8.8x\n", header.symoff); 1217 s->Printf(" nsyms = 0x%8.8x\n", header.nsyms); 1218 s->Printf(" hdrsize = 0x%4.4x\n", header.hdrsize); 1219 } 1220 1221 // DumpOptCOFFHeader 1222 // 1223 // Dump the optional COFF header to the specified output stream 1224 void ObjectFilePECOFF::DumpOptCOFFHeader(Stream *s, 1225 const coff_opt_header_t &header) { 1226 s->PutCString("Optional COFF Header\n"); 1227 s->Printf(" magic = 0x%4.4x\n", header.magic); 1228 s->Printf(" major_linker_version = 0x%2.2x\n", 1229 header.major_linker_version); 1230 s->Printf(" minor_linker_version = 0x%2.2x\n", 1231 header.minor_linker_version); 1232 s->Printf(" code_size = 0x%8.8x\n", header.code_size); 1233 s->Printf(" data_size = 0x%8.8x\n", header.data_size); 1234 s->Printf(" bss_size = 0x%8.8x\n", header.bss_size); 1235 s->Printf(" entry = 0x%8.8x\n", header.entry); 1236 s->Printf(" code_offset = 0x%8.8x\n", header.code_offset); 1237 s->Printf(" data_offset = 0x%8.8x\n", header.data_offset); 1238 s->Printf(" image_base = 0x%16.16" PRIx64 "\n", 1239 header.image_base); 1240 s->Printf(" sect_alignment = 0x%8.8x\n", header.sect_alignment); 1241 s->Printf(" file_alignment = 0x%8.8x\n", header.file_alignment); 1242 s->Printf(" major_os_system_version = 0x%4.4x\n", 1243 header.major_os_system_version); 1244 s->Printf(" minor_os_system_version = 0x%4.4x\n", 1245 header.minor_os_system_version); 1246 s->Printf(" major_image_version = 0x%4.4x\n", 1247 header.major_image_version); 1248 s->Printf(" minor_image_version = 0x%4.4x\n", 1249 header.minor_image_version); 1250 s->Printf(" major_subsystem_version = 0x%4.4x\n", 1251 header.major_subsystem_version); 1252 s->Printf(" minor_subsystem_version = 0x%4.4x\n", 1253 header.minor_subsystem_version); 1254 s->Printf(" reserved1 = 0x%8.8x\n", header.reserved1); 1255 s->Printf(" image_size = 0x%8.8x\n", header.image_size); 1256 s->Printf(" header_size = 0x%8.8x\n", header.header_size); 1257 s->Printf(" checksum = 0x%8.8x\n", header.checksum); 1258 s->Printf(" subsystem = 0x%4.4x\n", header.subsystem); 1259 s->Printf(" dll_flags = 0x%4.4x\n", header.dll_flags); 1260 s->Printf(" stack_reserve_size = 0x%16.16" PRIx64 "\n", 1261 header.stack_reserve_size); 1262 s->Printf(" stack_commit_size = 0x%16.16" PRIx64 "\n", 1263 header.stack_commit_size); 1264 s->Printf(" heap_reserve_size = 0x%16.16" PRIx64 "\n", 1265 header.heap_reserve_size); 1266 s->Printf(" heap_commit_size = 0x%16.16" PRIx64 "\n", 1267 header.heap_commit_size); 1268 s->Printf(" loader_flags = 0x%8.8x\n", header.loader_flags); 1269 s->Printf(" num_data_dir_entries = 0x%8.8x\n", 1270 (uint32_t)header.data_dirs.size()); 1271 uint32_t i; 1272 for (i = 0; i < header.data_dirs.size(); i++) { 1273 s->Printf(" data_dirs[%2u] vmaddr = 0x%8.8x, vmsize = 0x%8.8x\n", i, 1274 header.data_dirs[i].vmaddr, header.data_dirs[i].vmsize); 1275 } 1276 } 1277 // DumpSectionHeader 1278 // 1279 // Dump a single ELF section header to the specified output stream 1280 void ObjectFilePECOFF::DumpSectionHeader(Stream *s, 1281 const section_header_t &sh) { 1282 std::string name = std::string(GetSectionName(sh)); 1283 s->Printf("%-16s 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%4.4x " 1284 "0x%4.4x 0x%8.8x\n", 1285 name.c_str(), sh.vmaddr, sh.vmsize, sh.offset, sh.size, sh.reloff, 1286 sh.lineoff, sh.nreloc, sh.nline, sh.flags); 1287 } 1288 1289 // DumpSectionHeaders 1290 // 1291 // Dump all of the ELF section header to the specified output stream 1292 void ObjectFilePECOFF::DumpSectionHeaders(Stream *s) { 1293 1294 s->PutCString("Section Headers\n"); 1295 s->PutCString("IDX name vm addr vm size file off file " 1296 "size reloc off line off nreloc nline flags\n"); 1297 s->PutCString("==== ---------------- ---------- ---------- ---------- " 1298 "---------- ---------- ---------- ------ ------ ----------\n"); 1299 1300 uint32_t idx = 0; 1301 SectionHeaderCollIter pos, end = m_sect_headers.end(); 1302 1303 for (pos = m_sect_headers.begin(); pos != end; ++pos, ++idx) { 1304 s->Printf("[%2u] ", idx); 1305 ObjectFilePECOFF::DumpSectionHeader(s, *pos); 1306 } 1307 } 1308 1309 // DumpDependentModules 1310 // 1311 // Dump all of the dependent modules to the specified output stream 1312 void ObjectFilePECOFF::DumpDependentModules(lldb_private::Stream *s) { 1313 auto num_modules = ParseDependentModules(); 1314 if (num_modules > 0) { 1315 s->PutCString("Dependent Modules\n"); 1316 for (unsigned i = 0; i < num_modules; ++i) { 1317 auto spec = m_deps_filespec->GetFileSpecAtIndex(i); 1318 s->Printf(" %s\n", spec.GetFilename().GetCString()); 1319 } 1320 } 1321 } 1322 1323 bool ObjectFilePECOFF::IsWindowsSubsystem() { 1324 switch (m_coff_header_opt.subsystem) { 1325 case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE: 1326 case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI: 1327 case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI: 1328 case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE_WINDOWS: 1329 case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CE_GUI: 1330 case llvm::COFF::IMAGE_SUBSYSTEM_XBOX: 1331 case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION: 1332 return true; 1333 default: 1334 return false; 1335 } 1336 } 1337 1338 ArchSpec ObjectFilePECOFF::GetArchitecture() { 1339 uint16_t machine = m_coff_header.machine; 1340 switch (machine) { 1341 default: 1342 break; 1343 case llvm::COFF::IMAGE_FILE_MACHINE_AMD64: 1344 case llvm::COFF::IMAGE_FILE_MACHINE_I386: 1345 case llvm::COFF::IMAGE_FILE_MACHINE_POWERPC: 1346 case llvm::COFF::IMAGE_FILE_MACHINE_POWERPCFP: 1347 case llvm::COFF::IMAGE_FILE_MACHINE_ARM: 1348 case llvm::COFF::IMAGE_FILE_MACHINE_ARMNT: 1349 case llvm::COFF::IMAGE_FILE_MACHINE_THUMB: 1350 case llvm::COFF::IMAGE_FILE_MACHINE_ARM64: 1351 ArchSpec arch; 1352 arch.SetArchitecture(eArchTypeCOFF, machine, LLDB_INVALID_CPUTYPE, 1353 IsWindowsSubsystem() ? llvm::Triple::Win32 1354 : llvm::Triple::UnknownOS); 1355 return arch; 1356 } 1357 return ArchSpec(); 1358 } 1359 1360 ObjectFile::Type ObjectFilePECOFF::CalculateType() { 1361 if (m_coff_header.machine != 0) { 1362 if ((m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0) 1363 return eTypeExecutable; 1364 else 1365 return eTypeSharedLibrary; 1366 } 1367 return eTypeExecutable; 1368 } 1369 1370 ObjectFile::Strata ObjectFilePECOFF::CalculateStrata() { return eStrataUser; } 1371