1 //===-- LLVMSymbolize.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 // Implementation for LLVM symbolization library. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/DebugInfo/Symbolize/Symbolize.h" 14 15 #include "SymbolizableObjectFile.h" 16 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/BinaryFormat/COFF.h" 19 #include "llvm/Config/config.h" 20 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 21 #include "llvm/DebugInfo/PDB/PDB.h" 22 #include "llvm/DebugInfo/PDB/PDBContext.h" 23 #include "llvm/Debuginfod/Debuginfod.h" 24 #include "llvm/Demangle/Demangle.h" 25 #include "llvm/Object/COFF.h" 26 #include "llvm/Object/MachO.h" 27 #include "llvm/Object/MachOUniversal.h" 28 #include "llvm/Support/CRC.h" 29 #include "llvm/Support/Casting.h" 30 #include "llvm/Support/Compression.h" 31 #include "llvm/Support/DataExtractor.h" 32 #include "llvm/Support/Errc.h" 33 #include "llvm/Support/FileSystem.h" 34 #include "llvm/Support/MemoryBuffer.h" 35 #include "llvm/Support/Path.h" 36 #include <algorithm> 37 #include <cassert> 38 #include <cstring> 39 40 namespace llvm { 41 namespace symbolize { 42 43 template <typename T> 44 Expected<DILineInfo> 45 LLVMSymbolizer::symbolizeCodeCommon(const T &ModuleSpecifier, 46 object::SectionedAddress ModuleOffset) { 47 48 auto InfoOrErr = getOrCreateModuleInfo(ModuleSpecifier); 49 if (!InfoOrErr) 50 return InfoOrErr.takeError(); 51 52 SymbolizableModule *Info = *InfoOrErr; 53 54 // A null module means an error has already been reported. Return an empty 55 // result. 56 if (!Info) 57 return DILineInfo(); 58 59 // If the user is giving us relative addresses, add the preferred base of the 60 // object to the offset before we do the query. It's what DIContext expects. 61 if (Opts.RelativeAddresses) 62 ModuleOffset.Address += Info->getModulePreferredBase(); 63 64 DILineInfo LineInfo = Info->symbolizeCode( 65 ModuleOffset, DILineInfoSpecifier(Opts.PathStyle, Opts.PrintFunctions), 66 Opts.UseSymbolTable); 67 if (Opts.Demangle) 68 LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info); 69 return LineInfo; 70 } 71 72 Expected<DILineInfo> 73 LLVMSymbolizer::symbolizeCode(const ObjectFile &Obj, 74 object::SectionedAddress ModuleOffset) { 75 return symbolizeCodeCommon(Obj, ModuleOffset); 76 } 77 78 Expected<DILineInfo> 79 LLVMSymbolizer::symbolizeCode(const std::string &ModuleName, 80 object::SectionedAddress ModuleOffset) { 81 return symbolizeCodeCommon(ModuleName, ModuleOffset); 82 } 83 84 template <typename T> 85 Expected<DIInliningInfo> LLVMSymbolizer::symbolizeInlinedCodeCommon( 86 const T &ModuleSpecifier, object::SectionedAddress ModuleOffset) { 87 auto InfoOrErr = getOrCreateModuleInfo(ModuleSpecifier); 88 if (!InfoOrErr) 89 return InfoOrErr.takeError(); 90 91 SymbolizableModule *Info = *InfoOrErr; 92 93 // A null module means an error has already been reported. Return an empty 94 // result. 95 if (!Info) 96 return DIInliningInfo(); 97 98 // If the user is giving us relative addresses, add the preferred base of the 99 // object to the offset before we do the query. It's what DIContext expects. 100 if (Opts.RelativeAddresses) 101 ModuleOffset.Address += Info->getModulePreferredBase(); 102 103 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode( 104 ModuleOffset, DILineInfoSpecifier(Opts.PathStyle, Opts.PrintFunctions), 105 Opts.UseSymbolTable); 106 if (Opts.Demangle) { 107 for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) { 108 auto *Frame = InlinedContext.getMutableFrame(i); 109 Frame->FunctionName = DemangleName(Frame->FunctionName, Info); 110 } 111 } 112 return InlinedContext; 113 } 114 115 Expected<DIInliningInfo> 116 LLVMSymbolizer::symbolizeInlinedCode(const ObjectFile &Obj, 117 object::SectionedAddress ModuleOffset) { 118 return symbolizeInlinedCodeCommon(Obj, ModuleOffset); 119 } 120 121 Expected<DIInliningInfo> 122 LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName, 123 object::SectionedAddress ModuleOffset) { 124 return symbolizeInlinedCodeCommon(ModuleName, ModuleOffset); 125 } 126 127 template <typename T> 128 Expected<DIGlobal> 129 LLVMSymbolizer::symbolizeDataCommon(const T &ModuleSpecifier, 130 object::SectionedAddress ModuleOffset) { 131 132 auto InfoOrErr = getOrCreateModuleInfo(ModuleSpecifier); 133 if (!InfoOrErr) 134 return InfoOrErr.takeError(); 135 136 SymbolizableModule *Info = *InfoOrErr; 137 // A null module means an error has already been reported. Return an empty 138 // result. 139 if (!Info) 140 return DIGlobal(); 141 142 // If the user is giving us relative addresses, add the preferred base of 143 // the object to the offset before we do the query. It's what DIContext 144 // expects. 145 if (Opts.RelativeAddresses) 146 ModuleOffset.Address += Info->getModulePreferredBase(); 147 148 DIGlobal Global = Info->symbolizeData(ModuleOffset); 149 if (Opts.Demangle) 150 Global.Name = DemangleName(Global.Name, Info); 151 return Global; 152 } 153 154 Expected<DIGlobal> 155 LLVMSymbolizer::symbolizeData(const ObjectFile &Obj, 156 object::SectionedAddress ModuleOffset) { 157 return symbolizeDataCommon(Obj, ModuleOffset); 158 } 159 160 Expected<DIGlobal> 161 LLVMSymbolizer::symbolizeData(const std::string &ModuleName, 162 object::SectionedAddress ModuleOffset) { 163 return symbolizeDataCommon(ModuleName, ModuleOffset); 164 } 165 166 template <typename T> 167 Expected<std::vector<DILocal>> 168 LLVMSymbolizer::symbolizeFrameCommon(const T &ModuleSpecifier, 169 object::SectionedAddress ModuleOffset) { 170 auto InfoOrErr = getOrCreateModuleInfo(ModuleSpecifier); 171 if (!InfoOrErr) 172 return InfoOrErr.takeError(); 173 174 SymbolizableModule *Info = *InfoOrErr; 175 // A null module means an error has already been reported. Return an empty 176 // result. 177 if (!Info) 178 return std::vector<DILocal>(); 179 180 // If the user is giving us relative addresses, add the preferred base of 181 // the object to the offset before we do the query. It's what DIContext 182 // expects. 183 if (Opts.RelativeAddresses) 184 ModuleOffset.Address += Info->getModulePreferredBase(); 185 186 return Info->symbolizeFrame(ModuleOffset); 187 } 188 189 Expected<std::vector<DILocal>> 190 LLVMSymbolizer::symbolizeFrame(const ObjectFile &Obj, 191 object::SectionedAddress ModuleOffset) { 192 return symbolizeFrameCommon(Obj, ModuleOffset); 193 } 194 195 Expected<std::vector<DILocal>> 196 LLVMSymbolizer::symbolizeFrame(const std::string &ModuleName, 197 object::SectionedAddress ModuleOffset) { 198 return symbolizeFrameCommon(ModuleName, ModuleOffset); 199 } 200 201 void LLVMSymbolizer::flush() { 202 ObjectForUBPathAndArch.clear(); 203 BinaryForPath.clear(); 204 ObjectPairForPathArch.clear(); 205 Modules.clear(); 206 } 207 208 namespace { 209 210 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in 211 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo. 212 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in 213 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo. 214 std::string getDarwinDWARFResourceForPath(const std::string &Path, 215 const std::string &Basename) { 216 SmallString<16> ResourceName = StringRef(Path); 217 if (sys::path::extension(Path) != ".dSYM") { 218 ResourceName += ".dSYM"; 219 } 220 sys::path::append(ResourceName, "Contents", "Resources", "DWARF"); 221 sys::path::append(ResourceName, Basename); 222 return std::string(ResourceName.str()); 223 } 224 225 bool checkFileCRC(StringRef Path, uint32_t CRCHash) { 226 ErrorOr<std::unique_ptr<MemoryBuffer>> MB = 227 MemoryBuffer::getFileOrSTDIN(Path); 228 if (!MB) 229 return false; 230 return CRCHash == llvm::crc32(arrayRefFromStringRef(MB.get()->getBuffer())); 231 } 232 233 bool findDebugBinary(const std::string &OrigPath, 234 const std::string &DebuglinkName, uint32_t CRCHash, 235 const std::string &FallbackDebugPath, 236 std::string &Result) { 237 SmallString<16> OrigDir(OrigPath); 238 llvm::sys::path::remove_filename(OrigDir); 239 SmallString<16> DebugPath = OrigDir; 240 // Try relative/path/to/original_binary/debuglink_name 241 llvm::sys::path::append(DebugPath, DebuglinkName); 242 if (checkFileCRC(DebugPath, CRCHash)) { 243 Result = std::string(DebugPath.str()); 244 return true; 245 } 246 // Try relative/path/to/original_binary/.debug/debuglink_name 247 DebugPath = OrigDir; 248 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName); 249 if (checkFileCRC(DebugPath, CRCHash)) { 250 Result = std::string(DebugPath.str()); 251 return true; 252 } 253 // Make the path absolute so that lookups will go to 254 // "/usr/lib/debug/full/path/to/debug", not 255 // "/usr/lib/debug/to/debug" 256 llvm::sys::fs::make_absolute(OrigDir); 257 if (!FallbackDebugPath.empty()) { 258 // Try <FallbackDebugPath>/absolute/path/to/original_binary/debuglink_name 259 DebugPath = FallbackDebugPath; 260 } else { 261 #if defined(__NetBSD__) 262 // Try /usr/libdata/debug/absolute/path/to/original_binary/debuglink_name 263 DebugPath = "/usr/libdata/debug"; 264 #else 265 // Try /usr/lib/debug/absolute/path/to/original_binary/debuglink_name 266 DebugPath = "/usr/lib/debug"; 267 #endif 268 } 269 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir), 270 DebuglinkName); 271 if (checkFileCRC(DebugPath, CRCHash)) { 272 Result = std::string(DebugPath.str()); 273 return true; 274 } 275 return false; 276 } 277 278 bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName, 279 uint32_t &CRCHash) { 280 if (!Obj) 281 return false; 282 for (const SectionRef &Section : Obj->sections()) { 283 StringRef Name; 284 consumeError(Section.getName().moveInto(Name)); 285 286 Name = Name.substr(Name.find_first_not_of("._")); 287 if (Name == "gnu_debuglink") { 288 Expected<StringRef> ContentsOrErr = Section.getContents(); 289 if (!ContentsOrErr) { 290 consumeError(ContentsOrErr.takeError()); 291 return false; 292 } 293 DataExtractor DE(*ContentsOrErr, Obj->isLittleEndian(), 0); 294 uint64_t Offset = 0; 295 if (const char *DebugNameStr = DE.getCStr(&Offset)) { 296 // 4-byte align the offset. 297 Offset = (Offset + 3) & ~0x3; 298 if (DE.isValidOffsetForDataOfSize(Offset, 4)) { 299 DebugName = DebugNameStr; 300 CRCHash = DE.getU32(&Offset); 301 return true; 302 } 303 } 304 break; 305 } 306 } 307 return false; 308 } 309 310 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj, 311 const MachOObjectFile *Obj) { 312 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid(); 313 ArrayRef<uint8_t> bin_uuid = Obj->getUuid(); 314 if (dbg_uuid.empty() || bin_uuid.empty()) 315 return false; 316 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size()); 317 } 318 319 template <typename ELFT> 320 Optional<ArrayRef<uint8_t>> getBuildID(const ELFFile<ELFT> &Obj) { 321 auto PhdrsOrErr = Obj.program_headers(); 322 if (!PhdrsOrErr) { 323 consumeError(PhdrsOrErr.takeError()); 324 return {}; 325 } 326 for (const auto &P : *PhdrsOrErr) { 327 if (P.p_type != ELF::PT_NOTE) 328 continue; 329 Error Err = Error::success(); 330 for (auto N : Obj.notes(P, Err)) 331 if (N.getType() == ELF::NT_GNU_BUILD_ID && 332 N.getName() == ELF::ELF_NOTE_GNU) 333 return N.getDesc(); 334 consumeError(std::move(Err)); 335 } 336 return {}; 337 } 338 339 Optional<ArrayRef<uint8_t>> getBuildID(const ELFObjectFileBase *Obj) { 340 Optional<ArrayRef<uint8_t>> BuildID; 341 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Obj)) 342 BuildID = getBuildID(O->getELFFile()); 343 else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Obj)) 344 BuildID = getBuildID(O->getELFFile()); 345 else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Obj)) 346 BuildID = getBuildID(O->getELFFile()); 347 else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Obj)) 348 BuildID = getBuildID(O->getELFFile()); 349 else 350 llvm_unreachable("unsupported file format"); 351 return BuildID; 352 } 353 354 bool findDebugBinary(const std::vector<std::string> &DebugFileDirectory, 355 const ArrayRef<uint8_t> BuildID, std::string &Result) { 356 auto getDebugPath = [&](StringRef Directory) { 357 SmallString<128> Path{Directory}; 358 sys::path::append(Path, ".build-id", 359 llvm::toHex(BuildID[0], /*LowerCase=*/true), 360 llvm::toHex(BuildID.slice(1), /*LowerCase=*/true)); 361 Path += ".debug"; 362 return Path; 363 }; 364 if (DebugFileDirectory.empty()) { 365 SmallString<128> Path = getDebugPath( 366 #if defined(__NetBSD__) 367 // Try /usr/libdata/debug/.build-id/../... 368 "/usr/libdata/debug" 369 #else 370 // Try /usr/lib/debug/.build-id/../... 371 "/usr/lib/debug" 372 #endif 373 ); 374 if (llvm::sys::fs::exists(Path)) { 375 Result = std::string(Path.str()); 376 return true; 377 } 378 } else { 379 for (const auto &Directory : DebugFileDirectory) { 380 // Try <debug-file-directory>/.build-id/../... 381 SmallString<128> Path = getDebugPath(Directory); 382 if (llvm::sys::fs::exists(Path)) { 383 Result = std::string(Path.str()); 384 return true; 385 } 386 } 387 } 388 // Try debuginfod client cache and known servers. 389 Expected<std::string> PathOrErr = getCachedOrDownloadDebuginfo(BuildID); 390 if (!PathOrErr) { 391 consumeError(PathOrErr.takeError()); 392 return false; 393 } 394 Result = *PathOrErr; 395 return true; 396 } 397 398 } // end anonymous namespace 399 400 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath, 401 const MachOObjectFile *MachExeObj, 402 const std::string &ArchName) { 403 // On Darwin we may find DWARF in separate object file in 404 // resource directory. 405 std::vector<std::string> DsymPaths; 406 StringRef Filename = sys::path::filename(ExePath); 407 DsymPaths.push_back( 408 getDarwinDWARFResourceForPath(ExePath, std::string(Filename))); 409 for (const auto &Path : Opts.DsymHints) { 410 DsymPaths.push_back( 411 getDarwinDWARFResourceForPath(Path, std::string(Filename))); 412 } 413 for (const auto &Path : DsymPaths) { 414 auto DbgObjOrErr = getOrCreateObject(Path, ArchName); 415 if (!DbgObjOrErr) { 416 // Ignore errors, the file might not exist. 417 consumeError(DbgObjOrErr.takeError()); 418 continue; 419 } 420 ObjectFile *DbgObj = DbgObjOrErr.get(); 421 if (!DbgObj) 422 continue; 423 const MachOObjectFile *MachDbgObj = dyn_cast<const MachOObjectFile>(DbgObj); 424 if (!MachDbgObj) 425 continue; 426 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) 427 return DbgObj; 428 } 429 return nullptr; 430 } 431 432 ObjectFile *LLVMSymbolizer::lookUpDebuglinkObject(const std::string &Path, 433 const ObjectFile *Obj, 434 const std::string &ArchName) { 435 std::string DebuglinkName; 436 uint32_t CRCHash; 437 std::string DebugBinaryPath; 438 if (!getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash)) 439 return nullptr; 440 if (!findDebugBinary(Path, DebuglinkName, CRCHash, Opts.FallbackDebugPath, 441 DebugBinaryPath)) 442 return nullptr; 443 auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName); 444 if (!DbgObjOrErr) { 445 // Ignore errors, the file might not exist. 446 consumeError(DbgObjOrErr.takeError()); 447 return nullptr; 448 } 449 return DbgObjOrErr.get(); 450 } 451 452 ObjectFile *LLVMSymbolizer::lookUpBuildIDObject(const std::string &Path, 453 const ELFObjectFileBase *Obj, 454 const std::string &ArchName) { 455 auto BuildID = getBuildID(Obj); 456 if (!BuildID) 457 return nullptr; 458 if (BuildID->size() < 2) 459 return nullptr; 460 std::string DebugBinaryPath; 461 if (!findDebugBinary(Opts.DebugFileDirectory, *BuildID, DebugBinaryPath)) 462 return nullptr; 463 auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName); 464 if (!DbgObjOrErr) { 465 consumeError(DbgObjOrErr.takeError()); 466 return nullptr; 467 } 468 return DbgObjOrErr.get(); 469 } 470 471 Expected<LLVMSymbolizer::ObjectPair> 472 LLVMSymbolizer::getOrCreateObjectPair(const std::string &Path, 473 const std::string &ArchName) { 474 auto I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName)); 475 if (I != ObjectPairForPathArch.end()) 476 return I->second; 477 478 auto ObjOrErr = getOrCreateObject(Path, ArchName); 479 if (!ObjOrErr) { 480 ObjectPairForPathArch.emplace(std::make_pair(Path, ArchName), 481 ObjectPair(nullptr, nullptr)); 482 return ObjOrErr.takeError(); 483 } 484 485 ObjectFile *Obj = ObjOrErr.get(); 486 assert(Obj != nullptr); 487 ObjectFile *DbgObj = nullptr; 488 489 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj)) 490 DbgObj = lookUpDsymFile(Path, MachObj, ArchName); 491 else if (auto ELFObj = dyn_cast<const ELFObjectFileBase>(Obj)) 492 DbgObj = lookUpBuildIDObject(Path, ELFObj, ArchName); 493 if (!DbgObj) 494 DbgObj = lookUpDebuglinkObject(Path, Obj, ArchName); 495 if (!DbgObj) 496 DbgObj = Obj; 497 ObjectPair Res = std::make_pair(Obj, DbgObj); 498 ObjectPairForPathArch.emplace(std::make_pair(Path, ArchName), Res); 499 return Res; 500 } 501 502 Expected<ObjectFile *> 503 LLVMSymbolizer::getOrCreateObject(const std::string &Path, 504 const std::string &ArchName) { 505 Binary *Bin; 506 auto Pair = BinaryForPath.emplace(Path, OwningBinary<Binary>()); 507 if (!Pair.second) { 508 Bin = Pair.first->second.getBinary(); 509 } else { 510 Expected<OwningBinary<Binary>> BinOrErr = createBinary(Path); 511 if (!BinOrErr) 512 return BinOrErr.takeError(); 513 Pair.first->second = std::move(BinOrErr.get()); 514 Bin = Pair.first->second.getBinary(); 515 } 516 517 if (!Bin) 518 return static_cast<ObjectFile *>(nullptr); 519 520 if (MachOUniversalBinary *UB = dyn_cast_or_null<MachOUniversalBinary>(Bin)) { 521 auto I = ObjectForUBPathAndArch.find(std::make_pair(Path, ArchName)); 522 if (I != ObjectForUBPathAndArch.end()) 523 return I->second.get(); 524 525 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = 526 UB->getMachOObjectForArch(ArchName); 527 if (!ObjOrErr) { 528 ObjectForUBPathAndArch.emplace(std::make_pair(Path, ArchName), 529 std::unique_ptr<ObjectFile>()); 530 return ObjOrErr.takeError(); 531 } 532 ObjectFile *Res = ObjOrErr->get(); 533 ObjectForUBPathAndArch.emplace(std::make_pair(Path, ArchName), 534 std::move(ObjOrErr.get())); 535 return Res; 536 } 537 if (Bin->isObject()) { 538 return cast<ObjectFile>(Bin); 539 } 540 return errorCodeToError(object_error::arch_not_found); 541 } 542 543 Expected<SymbolizableModule *> 544 LLVMSymbolizer::createModuleInfo(const ObjectFile *Obj, 545 std::unique_ptr<DIContext> Context, 546 StringRef ModuleName) { 547 auto InfoOrErr = SymbolizableObjectFile::create(Obj, std::move(Context), 548 Opts.UntagAddresses); 549 std::unique_ptr<SymbolizableModule> SymMod; 550 if (InfoOrErr) 551 SymMod = std::move(*InfoOrErr); 552 auto InsertResult = Modules.insert( 553 std::make_pair(std::string(ModuleName), std::move(SymMod))); 554 assert(InsertResult.second); 555 if (!InfoOrErr) 556 return InfoOrErr.takeError(); 557 return InsertResult.first->second.get(); 558 } 559 560 Expected<SymbolizableModule *> 561 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) { 562 auto I = Modules.find(ModuleName); 563 if (I != Modules.end()) 564 return I->second.get(); 565 566 std::string BinaryName = ModuleName; 567 std::string ArchName = Opts.DefaultArch; 568 size_t ColonPos = ModuleName.find_last_of(':'); 569 // Verify that substring after colon form a valid arch name. 570 if (ColonPos != std::string::npos) { 571 std::string ArchStr = ModuleName.substr(ColonPos + 1); 572 if (Triple(ArchStr).getArch() != Triple::UnknownArch) { 573 BinaryName = ModuleName.substr(0, ColonPos); 574 ArchName = ArchStr; 575 } 576 } 577 auto ObjectsOrErr = getOrCreateObjectPair(BinaryName, ArchName); 578 if (!ObjectsOrErr) { 579 // Failed to find valid object file. 580 Modules.emplace(ModuleName, std::unique_ptr<SymbolizableModule>()); 581 return ObjectsOrErr.takeError(); 582 } 583 ObjectPair Objects = ObjectsOrErr.get(); 584 585 std::unique_ptr<DIContext> Context; 586 // If this is a COFF object containing PDB info, use a PDBContext to 587 // symbolize. Otherwise, use DWARF. 588 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) { 589 const codeview::DebugInfo *DebugInfo; 590 StringRef PDBFileName; 591 auto EC = CoffObject->getDebugPDBInfo(DebugInfo, PDBFileName); 592 if (!EC && DebugInfo != nullptr && !PDBFileName.empty()) { 593 #if 0 594 using namespace pdb; 595 std::unique_ptr<IPDBSession> Session; 596 597 PDB_ReaderType ReaderType = 598 Opts.UseDIA ? PDB_ReaderType::DIA : PDB_ReaderType::Native; 599 if (auto Err = loadDataForEXE(ReaderType, Objects.first->getFileName(), 600 Session)) { 601 Modules.emplace(ModuleName, std::unique_ptr<SymbolizableModule>()); 602 // Return along the PDB filename to provide more context 603 return createFileError(PDBFileName, std::move(Err)); 604 } 605 Context.reset(new PDBContext(*CoffObject, std::move(Session))); 606 #else 607 return make_error<StringError>( 608 "PDB support not compiled in", 609 std::make_error_code(std::errc::not_supported)); 610 #endif 611 } 612 } 613 if (!Context) 614 Context = DWARFContext::create( 615 *Objects.second, DWARFContext::ProcessDebugRelocations::Process, 616 nullptr, Opts.DWPName); 617 return createModuleInfo(Objects.first, std::move(Context), ModuleName); 618 } 619 620 Expected<SymbolizableModule *> 621 LLVMSymbolizer::getOrCreateModuleInfo(const ObjectFile &Obj) { 622 StringRef ObjName = Obj.getFileName(); 623 auto I = Modules.find(ObjName); 624 if (I != Modules.end()) 625 return I->second.get(); 626 627 std::unique_ptr<DIContext> Context = DWARFContext::create(Obj); 628 // FIXME: handle COFF object with PDB info to use PDBContext 629 return createModuleInfo(&Obj, std::move(Context), ObjName); 630 } 631 632 namespace { 633 634 // Undo these various manglings for Win32 extern "C" functions: 635 // cdecl - _foo 636 // stdcall - _foo@12 637 // fastcall - @foo@12 638 // vectorcall - foo@@12 639 // These are all different linkage names for 'foo'. 640 StringRef demanglePE32ExternCFunc(StringRef SymbolName) { 641 // Remove any '_' or '@' prefix. 642 char Front = SymbolName.empty() ? '\0' : SymbolName[0]; 643 if (Front == '_' || Front == '@') 644 SymbolName = SymbolName.drop_front(); 645 646 // Remove any '@[0-9]+' suffix. 647 if (Front != '?') { 648 size_t AtPos = SymbolName.rfind('@'); 649 if (AtPos != StringRef::npos && 650 all_of(drop_begin(SymbolName, AtPos + 1), isDigit)) 651 SymbolName = SymbolName.substr(0, AtPos); 652 } 653 654 // Remove any ending '@' for vectorcall. 655 if (SymbolName.endswith("@")) 656 SymbolName = SymbolName.drop_back(); 657 658 return SymbolName; 659 } 660 661 } // end anonymous namespace 662 663 std::string 664 LLVMSymbolizer::DemangleName(const std::string &Name, 665 const SymbolizableModule *DbiModuleDescriptor) { 666 std::string Result; 667 if (nonMicrosoftDemangle(Name.c_str(), Result)) 668 return Result; 669 670 if (!Name.empty() && Name.front() == '?') { 671 // Only do MSVC C++ demangling on symbols starting with '?'. 672 int status = 0; 673 char *DemangledName = microsoftDemangle( 674 Name.c_str(), nullptr, nullptr, nullptr, &status, 675 MSDemangleFlags(MSDF_NoAccessSpecifier | MSDF_NoCallingConvention | 676 MSDF_NoMemberType | MSDF_NoReturnType)); 677 if (status != 0) 678 return Name; 679 Result = DemangledName; 680 free(DemangledName); 681 return Result; 682 } 683 684 if (DbiModuleDescriptor && DbiModuleDescriptor->isWin32Module()) 685 return std::string(demanglePE32ExternCFunc(Name)); 686 return Name; 687 } 688 689 } // namespace symbolize 690 } // namespace llvm 691