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