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