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