LLVM 20.0.0git
Symbolize.cpp
Go to the documentation of this file.
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
14
15#include "llvm/ADT/STLExtras.h"
22#include "llvm/Object/BuildID.h"
23#include "llvm/Object/COFF.h"
25#include "llvm/Object/MachO.h"
27#include "llvm/Support/CRC.h"
30#include "llvm/Support/Errc.h"
33#include "llvm/Support/Path.h"
34#include <algorithm>
35#include <cassert>
36#include <cstring>
37
38namespace llvm {
39namespace codeview {
40union DebugInfo;
41}
42namespace symbolize {
43
45
47 : Opts(Opts),
48 BIDFetcher(std::make_unique<BuildIDFetcher>(Opts.DebugFileDirectory)) {}
49
51
52template <typename T>
54LLVMSymbolizer::symbolizeCodeCommon(const T &ModuleSpecifier,
55 object::SectionedAddress ModuleOffset) {
56
57 auto InfoOrErr = getOrCreateModuleInfo(ModuleSpecifier);
58 if (!InfoOrErr)
59 return InfoOrErr.takeError();
60
61 SymbolizableModule *Info = *InfoOrErr;
62
63 // A null module means an error has already been reported. Return an empty
64 // result.
65 if (!Info)
66 return DILineInfo();
67
68 // If the user is giving us relative addresses, add the preferred base of the
69 // object to the offset before we do the query. It's what DIContext expects.
70 if (Opts.RelativeAddresses)
71 ModuleOffset.Address += Info->getModulePreferredBase();
72
73 DILineInfo LineInfo = Info->symbolizeCode(
74 ModuleOffset,
76 Opts.SkipLineZero),
77 Opts.UseSymbolTable);
78 if (Opts.Demangle)
79 LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
80 return LineInfo;
81}
82
85 object::SectionedAddress ModuleOffset) {
86 return symbolizeCodeCommon(Obj, ModuleOffset);
87}
88
91 object::SectionedAddress ModuleOffset) {
92 return symbolizeCodeCommon(ModuleName, ModuleOffset);
93}
94
97 object::SectionedAddress ModuleOffset) {
98 return symbolizeCodeCommon(BuildID, ModuleOffset);
99}
100
101template <typename T>
102Expected<DIInliningInfo> LLVMSymbolizer::symbolizeInlinedCodeCommon(
103 const T &ModuleSpecifier, object::SectionedAddress ModuleOffset) {
104 auto InfoOrErr = getOrCreateModuleInfo(ModuleSpecifier);
105 if (!InfoOrErr)
106 return InfoOrErr.takeError();
107
108 SymbolizableModule *Info = *InfoOrErr;
109
110 // A null module means an error has already been reported. Return an empty
111 // result.
112 if (!Info)
113 return DIInliningInfo();
114
115 // If the user is giving us relative addresses, add the preferred base of the
116 // object to the offset before we do the query. It's what DIContext expects.
117 if (Opts.RelativeAddresses)
118 ModuleOffset.Address += Info->getModulePreferredBase();
119
120 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
121 ModuleOffset,
123 Opts.SkipLineZero),
124 Opts.UseSymbolTable);
125 if (Opts.Demangle) {
126 for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
127 auto *Frame = InlinedContext.getMutableFrame(i);
128 Frame->FunctionName = DemangleName(Frame->FunctionName, Info);
129 }
130 }
131 return InlinedContext;
132}
133
134Expected<DIInliningInfo>
136 object::SectionedAddress ModuleOffset) {
137 return symbolizeInlinedCodeCommon(Obj, ModuleOffset);
138}
139
142 object::SectionedAddress ModuleOffset) {
143 return symbolizeInlinedCodeCommon(ModuleName, ModuleOffset);
144}
145
148 object::SectionedAddress ModuleOffset) {
149 return symbolizeInlinedCodeCommon(BuildID, ModuleOffset);
150}
151
152template <typename T>
154LLVMSymbolizer::symbolizeDataCommon(const T &ModuleSpecifier,
155 object::SectionedAddress ModuleOffset) {
156
157 auto InfoOrErr = getOrCreateModuleInfo(ModuleSpecifier);
158 if (!InfoOrErr)
159 return InfoOrErr.takeError();
160
161 SymbolizableModule *Info = *InfoOrErr;
162 // A null module means an error has already been reported. Return an empty
163 // result.
164 if (!Info)
165 return DIGlobal();
166
167 // If the user is giving us relative addresses, add the preferred base of
168 // the object to the offset before we do the query. It's what DIContext
169 // expects.
170 if (Opts.RelativeAddresses)
171 ModuleOffset.Address += Info->getModulePreferredBase();
172
173 DIGlobal Global = Info->symbolizeData(ModuleOffset);
174 if (Opts.Demangle)
175 Global.Name = DemangleName(Global.Name, Info);
176 return Global;
177}
178
181 object::SectionedAddress ModuleOffset) {
182 return symbolizeDataCommon(Obj, ModuleOffset);
183}
184
187 object::SectionedAddress ModuleOffset) {
188 return symbolizeDataCommon(ModuleName, ModuleOffset);
189}
190
193 object::SectionedAddress ModuleOffset) {
194 return symbolizeDataCommon(BuildID, ModuleOffset);
195}
196
197template <typename T>
199LLVMSymbolizer::symbolizeFrameCommon(const T &ModuleSpecifier,
200 object::SectionedAddress ModuleOffset) {
201 auto InfoOrErr = getOrCreateModuleInfo(ModuleSpecifier);
202 if (!InfoOrErr)
203 return InfoOrErr.takeError();
204
205 SymbolizableModule *Info = *InfoOrErr;
206 // A null module means an error has already been reported. Return an empty
207 // result.
208 if (!Info)
209 return std::vector<DILocal>();
210
211 // If the user is giving us relative addresses, add the preferred base of
212 // the object to the offset before we do the query. It's what DIContext
213 // expects.
214 if (Opts.RelativeAddresses)
215 ModuleOffset.Address += Info->getModulePreferredBase();
216
217 return Info->symbolizeFrame(ModuleOffset);
218}
219
222 object::SectionedAddress ModuleOffset) {
223 return symbolizeFrameCommon(Obj, ModuleOffset);
224}
225
228 object::SectionedAddress ModuleOffset) {
229 return symbolizeFrameCommon(ModuleName, ModuleOffset);
230}
231
234 object::SectionedAddress ModuleOffset) {
235 return symbolizeFrameCommon(BuildID, ModuleOffset);
236}
237
238template <typename T>
240LLVMSymbolizer::findSymbolCommon(const T &ModuleSpecifier, StringRef Symbol,
242 auto InfoOrErr = getOrCreateModuleInfo(ModuleSpecifier);
243 if (!InfoOrErr)
244 return InfoOrErr.takeError();
245
246 SymbolizableModule *Info = *InfoOrErr;
247 std::vector<DILineInfo> Result;
248
249 // A null module means an error has already been reported. Return an empty
250 // result.
251 if (!Info)
252 return Result;
253
254 for (object::SectionedAddress A : Info->findSymbol(Symbol, Offset)) {
255 DILineInfo LineInfo = Info->symbolizeCode(
257 Opts.UseSymbolTable);
258 if (LineInfo.FileName != DILineInfo::BadString) {
259 if (Opts.Demangle)
260 LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
261 Result.push_back(LineInfo);
262 }
263 }
264
265 return Result;
266}
267
268Expected<std::vector<DILineInfo>>
271 return findSymbolCommon(Obj, Symbol, Offset);
272}
273
277 return findSymbolCommon(ModuleName, Symbol, Offset);
278}
279
283 return findSymbolCommon(BuildID, Symbol, Offset);
284}
285
287 ObjectForUBPathAndArch.clear();
288 LRUBinaries.clear();
289 CacheSize = 0;
290 BinaryForPath.clear();
291 ObjectPairForPathArch.clear();
292 Modules.clear();
293 BuildIDPaths.clear();
294}
295
296namespace {
297
298// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
299// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
300// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
301// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
302std::string getDarwinDWARFResourceForPath(const std::string &Path,
303 const std::string &Basename) {
304 SmallString<16> ResourceName = StringRef(Path);
305 if (sys::path::extension(Path) != ".dSYM") {
306 ResourceName += ".dSYM";
307 }
308 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
309 sys::path::append(ResourceName, Basename);
310 return std::string(ResourceName);
311}
312
313bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
314 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
316 if (!MB)
317 return false;
318 return CRCHash == llvm::crc32(arrayRefFromStringRef(MB.get()->getBuffer()));
319}
320
321bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
322 uint32_t &CRCHash) {
323 if (!Obj)
324 return false;
325 for (const SectionRef &Section : Obj->sections()) {
326 StringRef Name;
327 consumeError(Section.getName().moveInto(Name));
328
329 Name = Name.substr(Name.find_first_not_of("._"));
330 if (Name == "gnu_debuglink") {
331 Expected<StringRef> ContentsOrErr = Section.getContents();
332 if (!ContentsOrErr) {
333 consumeError(ContentsOrErr.takeError());
334 return false;
335 }
336 DataExtractor DE(*ContentsOrErr, Obj->isLittleEndian(), 0);
337 uint64_t Offset = 0;
338 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
339 // 4-byte align the offset.
340 Offset = (Offset + 3) & ~0x3;
341 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
342 DebugName = DebugNameStr;
343 CRCHash = DE.getU32(&Offset);
344 return true;
345 }
346 }
347 break;
348 }
349 }
350 return false;
351}
352
353bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
354 const MachOObjectFile *Obj) {
355 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
356 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
357 if (dbg_uuid.empty() || bin_uuid.empty())
358 return false;
359 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
360}
361
362} // end anonymous namespace
363
364ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
365 const MachOObjectFile *MachExeObj,
366 const std::string &ArchName) {
367 // On Darwin we may find DWARF in separate object file in
368 // resource directory.
369 std::vector<std::string> DsymPaths;
370 StringRef Filename = sys::path::filename(ExePath);
371 DsymPaths.push_back(
372 getDarwinDWARFResourceForPath(ExePath, std::string(Filename)));
373 for (const auto &Path : Opts.DsymHints) {
374 DsymPaths.push_back(
375 getDarwinDWARFResourceForPath(Path, std::string(Filename)));
376 }
377 for (const auto &Path : DsymPaths) {
378 auto DbgObjOrErr = getOrCreateObject(Path, ArchName);
379 if (!DbgObjOrErr) {
380 // Ignore errors, the file might not exist.
381 consumeError(DbgObjOrErr.takeError());
382 continue;
383 }
384 ObjectFile *DbgObj = DbgObjOrErr.get();
385 if (!DbgObj)
386 continue;
387 const MachOObjectFile *MachDbgObj = dyn_cast<const MachOObjectFile>(DbgObj);
388 if (!MachDbgObj)
389 continue;
390 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj))
391 return DbgObj;
392 }
393 return nullptr;
394}
395
396ObjectFile *LLVMSymbolizer::lookUpDebuglinkObject(const std::string &Path,
397 const ObjectFile *Obj,
398 const std::string &ArchName) {
399 std::string DebuglinkName;
400 uint32_t CRCHash;
401 std::string DebugBinaryPath;
402 if (!getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash))
403 return nullptr;
404 if (!findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath))
405 return nullptr;
406 auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName);
407 if (!DbgObjOrErr) {
408 // Ignore errors, the file might not exist.
409 consumeError(DbgObjOrErr.takeError());
410 return nullptr;
411 }
412 return DbgObjOrErr.get();
413}
414
415ObjectFile *LLVMSymbolizer::lookUpBuildIDObject(const std::string &Path,
416 const ELFObjectFileBase *Obj,
417 const std::string &ArchName) {
418 auto BuildID = getBuildID(Obj);
419 if (BuildID.size() < 2)
420 return nullptr;
421 std::string DebugBinaryPath;
422 if (!getOrFindDebugBinary(BuildID, DebugBinaryPath))
423 return nullptr;
424 auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName);
425 if (!DbgObjOrErr) {
426 consumeError(DbgObjOrErr.takeError());
427 return nullptr;
428 }
429 return DbgObjOrErr.get();
430}
431
432bool LLVMSymbolizer::findDebugBinary(const std::string &OrigPath,
433 const std::string &DebuglinkName,
434 uint32_t CRCHash, std::string &Result) {
435 SmallString<16> OrigDir(OrigPath);
437 SmallString<16> DebugPath = OrigDir;
438 // Try relative/path/to/original_binary/debuglink_name
439 llvm::sys::path::append(DebugPath, DebuglinkName);
440 if (checkFileCRC(DebugPath, CRCHash)) {
441 Result = std::string(DebugPath);
442 return true;
443 }
444 // Try relative/path/to/original_binary/.debug/debuglink_name
445 DebugPath = OrigDir;
446 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
447 if (checkFileCRC(DebugPath, CRCHash)) {
448 Result = std::string(DebugPath);
449 return true;
450 }
451 // Make the path absolute so that lookups will go to
452 // "/usr/lib/debug/full/path/to/debug", not
453 // "/usr/lib/debug/to/debug"
455 if (!Opts.FallbackDebugPath.empty()) {
456 // Try <FallbackDebugPath>/absolute/path/to/original_binary/debuglink_name
457 DebugPath = Opts.FallbackDebugPath;
458 } else {
459#if defined(__NetBSD__)
460 // Try /usr/libdata/debug/absolute/path/to/original_binary/debuglink_name
461 DebugPath = "/usr/libdata/debug";
462#else
463 // Try /usr/lib/debug/absolute/path/to/original_binary/debuglink_name
464 DebugPath = "/usr/lib/debug";
465#endif
466 }
468 DebuglinkName);
469 if (checkFileCRC(DebugPath, CRCHash)) {
470 Result = std::string(DebugPath);
471 return true;
472 }
473 return false;
474}
475
477 return StringRef(reinterpret_cast<const char *>(BuildID.data()),
478 BuildID.size());
479}
480
481bool LLVMSymbolizer::getOrFindDebugBinary(const ArrayRef<uint8_t> BuildID,
482 std::string &Result) {
483 StringRef BuildIDStr = getBuildIDStr(BuildID);
484 auto I = BuildIDPaths.find(BuildIDStr);
485 if (I != BuildIDPaths.end()) {
486 Result = I->second;
487 return true;
488 }
489 if (!BIDFetcher)
490 return false;
491 if (std::optional<std::string> Path = BIDFetcher->fetch(BuildID)) {
492 Result = *Path;
493 auto InsertResult = BuildIDPaths.insert({BuildIDStr, Result});
494 assert(InsertResult.second);
495 (void)InsertResult;
496 return true;
497 }
498
499 return false;
500}
501
502Expected<LLVMSymbolizer::ObjectPair>
503LLVMSymbolizer::getOrCreateObjectPair(const std::string &Path,
504 const std::string &ArchName) {
505 auto I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
506 if (I != ObjectPairForPathArch.end()) {
507 recordAccess(BinaryForPath.find(Path)->second);
508 return I->second;
509 }
510
511 auto ObjOrErr = getOrCreateObject(Path, ArchName);
512 if (!ObjOrErr) {
513 ObjectPairForPathArch.emplace(std::make_pair(Path, ArchName),
514 ObjectPair(nullptr, nullptr));
515 return ObjOrErr.takeError();
516 }
517
518 ObjectFile *Obj = ObjOrErr.get();
519 assert(Obj != nullptr);
520 ObjectFile *DbgObj = nullptr;
521
522 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
523 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
524 else if (auto ELFObj = dyn_cast<const ELFObjectFileBase>(Obj))
525 DbgObj = lookUpBuildIDObject(Path, ELFObj, ArchName);
526 if (!DbgObj)
527 DbgObj = lookUpDebuglinkObject(Path, Obj, ArchName);
528 if (!DbgObj)
529 DbgObj = Obj;
530 ObjectPair Res = std::make_pair(Obj, DbgObj);
531 std::string DbgObjPath = DbgObj->getFileName().str();
532 auto Pair =
533 ObjectPairForPathArch.emplace(std::make_pair(Path, ArchName), Res);
534 BinaryForPath.find(DbgObjPath)->second.pushEvictor([this, I = Pair.first]() {
535 ObjectPairForPathArch.erase(I);
536 });
537 return Res;
538}
539
540Expected<ObjectFile *>
541LLVMSymbolizer::getOrCreateObject(const std::string &Path,
542 const std::string &ArchName) {
543 Binary *Bin;
544 auto Pair = BinaryForPath.emplace(Path, OwningBinary<Binary>());
545 if (!Pair.second) {
546 Bin = Pair.first->second->getBinary();
547 recordAccess(Pair.first->second);
548 } else {
549 Expected<OwningBinary<Binary>> BinOrErr = createBinary(Path);
550 if (!BinOrErr)
551 return BinOrErr.takeError();
552
553 CachedBinary &CachedBin = Pair.first->second;
554 CachedBin = std::move(BinOrErr.get());
555 CachedBin.pushEvictor([this, I = Pair.first]() { BinaryForPath.erase(I); });
556 LRUBinaries.push_back(CachedBin);
557 CacheSize += CachedBin.size();
558 Bin = CachedBin->getBinary();
559 }
560
561 if (!Bin)
562 return static_cast<ObjectFile *>(nullptr);
563
564 if (MachOUniversalBinary *UB = dyn_cast_or_null<MachOUniversalBinary>(Bin)) {
565 auto I = ObjectForUBPathAndArch.find(std::make_pair(Path, ArchName));
566 if (I != ObjectForUBPathAndArch.end())
567 return I->second.get();
568
569 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
570 UB->getMachOObjectForArch(ArchName);
571 if (!ObjOrErr) {
572 ObjectForUBPathAndArch.emplace(std::make_pair(Path, ArchName),
573 std::unique_ptr<ObjectFile>());
574 return ObjOrErr.takeError();
575 }
576 ObjectFile *Res = ObjOrErr->get();
577 auto Pair = ObjectForUBPathAndArch.emplace(std::make_pair(Path, ArchName),
578 std::move(ObjOrErr.get()));
579 BinaryForPath.find(Path)->second.pushEvictor(
580 [this, Iter = Pair.first]() { ObjectForUBPathAndArch.erase(Iter); });
581 return Res;
582 }
583 if (Bin->isObject()) {
584 return cast<ObjectFile>(Bin);
585 }
586 return errorCodeToError(object_error::arch_not_found);
587}
588
589Expected<SymbolizableModule *>
590LLVMSymbolizer::createModuleInfo(const ObjectFile *Obj,
591 std::unique_ptr<DIContext> Context,
592 StringRef ModuleName) {
593 auto InfoOrErr = SymbolizableObjectFile::create(Obj, std::move(Context),
594 Opts.UntagAddresses);
595 std::unique_ptr<SymbolizableModule> SymMod;
596 if (InfoOrErr)
597 SymMod = std::move(*InfoOrErr);
598 auto InsertResult = Modules.insert(
599 std::make_pair(std::string(ModuleName), std::move(SymMod)));
600 assert(InsertResult.second);
601 if (!InfoOrErr)
602 return InfoOrErr.takeError();
603 return InsertResult.first->second.get();
604}
605
606Expected<SymbolizableModule *>
608 std::string BinaryName = ModuleName;
609 std::string ArchName = Opts.DefaultArch;
610 size_t ColonPos = ModuleName.find_last_of(':');
611 // Verify that substring after colon form a valid arch name.
612 if (ColonPos != std::string::npos) {
613 std::string ArchStr = ModuleName.substr(ColonPos + 1);
614 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
615 BinaryName = ModuleName.substr(0, ColonPos);
616 ArchName = ArchStr;
617 }
618 }
619
620 auto I = Modules.find(ModuleName);
621 if (I != Modules.end()) {
622 recordAccess(BinaryForPath.find(BinaryName)->second);
623 return I->second.get();
624 }
625
626 auto ObjectsOrErr = getOrCreateObjectPair(BinaryName, ArchName);
627 if (!ObjectsOrErr) {
628 // Failed to find valid object file.
629 Modules.emplace(ModuleName, std::unique_ptr<SymbolizableModule>());
630 return ObjectsOrErr.takeError();
631 }
632 ObjectPair Objects = ObjectsOrErr.get();
633
634 std::unique_ptr<DIContext> Context;
635 // If this is a COFF object containing PDB info and not containing DWARF
636 // section, use a PDBContext to symbolize. Otherwise, use DWARF.
637 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
639 StringRef PDBFileName;
640 auto EC = CoffObject->getDebugPDBInfo(DebugInfo, PDBFileName);
641 // Use DWARF if there're DWARF sections.
642 bool HasDwarf =
643 llvm::any_of(Objects.first->sections(), [](SectionRef Section) -> bool {
644 if (Expected<StringRef> SectionName = Section.getName())
645 return SectionName.get() == ".debug_info";
646 return false;
647 });
648 if (!EC && !HasDwarf && DebugInfo != nullptr && !PDBFileName.empty()) {
649 using namespace pdb;
650 std::unique_ptr<IPDBSession> Session;
651
652 PDB_ReaderType ReaderType =
653 Opts.UseDIA ? PDB_ReaderType::DIA : PDB_ReaderType::Native;
654 if (auto Err = loadDataForEXE(ReaderType, Objects.first->getFileName(),
655 Session)) {
656 Modules.emplace(ModuleName, std::unique_ptr<SymbolizableModule>());
657 // Return along the PDB filename to provide more context
658 return createFileError(PDBFileName, std::move(Err));
659 }
660 Context.reset(new PDBContext(*CoffObject, std::move(Session)));
661 }
662 }
663 if (!Context)
664 Context = DWARFContext::create(
666 nullptr, Opts.DWPName);
667 auto ModuleOrErr =
668 createModuleInfo(Objects.first, std::move(Context), ModuleName);
669 if (ModuleOrErr) {
670 auto I = Modules.find(ModuleName);
671 BinaryForPath.find(BinaryName)->second.pushEvictor([this, I]() {
672 Modules.erase(I);
673 });
674 }
675 return ModuleOrErr;
676}
677
678// For BPF programs .BTF.ext section contains line numbers information,
679// use it if regular DWARF is not available (e.g. for stripped binary).
680static bool useBTFContext(const ObjectFile &Obj) {
681 return Obj.makeTriple().isBPF() && !Obj.hasDebugInfo() &&
683}
684
687 StringRef ObjName = Obj.getFileName();
688 auto I = Modules.find(ObjName);
689 if (I != Modules.end())
690 return I->second.get();
691
692 std::unique_ptr<DIContext> Context;
693 if (useBTFContext(Obj))
694 Context = BTFContext::create(Obj);
695 else
696 Context = DWARFContext::create(Obj);
697 // FIXME: handle COFF object with PDB info to use PDBContext
698 return createModuleInfo(&Obj, std::move(Context), ObjName);
699}
700
701Expected<SymbolizableModule *>
703 std::string Path;
704 if (!getOrFindDebugBinary(BuildID, Path)) {
706 "could not find build ID");
707 }
708 return getOrCreateModuleInfo(Path);
709}
710
711namespace {
712
713// Undo these various manglings for Win32 extern "C" functions:
714// cdecl - _foo
715// stdcall - _foo@12
716// fastcall - @foo@12
717// vectorcall - foo@@12
718// These are all different linkage names for 'foo'.
719StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
720 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
721
722 // Remove any '@[0-9]+' suffix.
723 bool HasAtNumSuffix = false;
724 if (Front != '?') {
725 size_t AtPos = SymbolName.rfind('@');
726 if (AtPos != StringRef::npos &&
727 all_of(drop_begin(SymbolName, AtPos + 1), isDigit)) {
728 SymbolName = SymbolName.substr(0, AtPos);
729 HasAtNumSuffix = true;
730 }
731 }
732
733 // Remove any ending '@' for vectorcall.
734 bool IsVectorCall = false;
735 if (HasAtNumSuffix && SymbolName.ends_with("@")) {
736 SymbolName = SymbolName.drop_back();
737 IsVectorCall = true;
738 }
739
740 // If not vectorcall, remove any '_' or '@' prefix.
741 if (!IsVectorCall && (Front == '_' || Front == '@'))
742 SymbolName = SymbolName.drop_front();
743
744 return SymbolName;
745}
746
747} // end anonymous namespace
748
749std::string
751 const SymbolizableModule *DbiModuleDescriptor) {
752 std::string Result;
753 if (nonMicrosoftDemangle(Name, Result))
754 return Result;
755
756 if (!Name.empty() && Name.front() == '?') {
757 // Only do MSVC C++ demangling on symbols starting with '?'.
758 int status = 0;
759 char *DemangledName = microsoftDemangle(
760 Name, nullptr, &status,
763 if (status != 0)
764 return Name;
765 Result = DemangledName;
766 free(DemangledName);
767 return Result;
768 }
769
770 if (DbiModuleDescriptor && DbiModuleDescriptor->isWin32Module()) {
771 std::string DemangledCName(demanglePE32ExternCFunc(Name));
772 // On i386 Windows, the C name mangling for different calling conventions
773 // may also be applied on top of the Itanium or Rust name mangling.
774 if (nonMicrosoftDemangle(DemangledCName, Result))
775 return Result;
776 return DemangledCName;
777 }
778 return Name;
779}
780
781void LLVMSymbolizer::recordAccess(CachedBinary &Bin) {
782 if (Bin->getBinary())
783 LRUBinaries.splice(LRUBinaries.end(), LRUBinaries, Bin.getIterator());
784}
785
787 // Evict the LRU binary until the max cache size is reached or there's <= 1
788 // item in the cache. The MRU binary is always kept to avoid thrashing if it's
789 // larger than the cache size.
790 while (CacheSize > Opts.MaxCacheSize && !LRUBinaries.empty() &&
791 std::next(LRUBinaries.begin()) != LRUBinaries.end()) {
792 CachedBinary &Bin = LRUBinaries.front();
793 CacheSize -= Bin.size();
794 LRUBinaries.pop_front();
795 Bin.evict();
796 }
797}
798
799void CachedBinary::pushEvictor(std::function<void()> NewEvictor) {
800 if (Evictor) {
801 this->Evictor = [OldEvictor = std::move(this->Evictor),
802 NewEvictor = std::move(NewEvictor)]() {
803 NewEvictor();
804 OldEvictor();
805 };
806 } else {
807 this->Evictor = std::move(NewEvictor);
808 }
809}
810
811} // namespace symbolize
812} // namespace llvm
This file declares a library for handling Build IDs and using them to find debug info.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
std::string Name
#define I(x, y, z)
Definition: MD5.cpp:58
Merge contiguous icmps into a memcmp
Definition: MergeICmps.cpp:911
static bool isDigit(const char C)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
static std::unique_ptr< BTFContext > create(const object::ObjectFile &Obj, std::function< void(Error)> ErrorHandler=WithColor::defaultErrorHandler)
Definition: BTFContext.cpp:63
static bool hasBTFSections(const ObjectFile &Obj)
Definition: BTFParser.cpp:410
A format-neutral container for inlined code description.
Definition: DIContext.h:94
static std::unique_ptr< DWARFContext > create(const object::ObjectFile &Obj, ProcessDebugRelocations RelocAction=ProcessDebugRelocations::Process, const LoadedObjectInfo *L=nullptr, std::string DWPName="", std::function< void(Error)> RecoverableErrorHandler=WithColor::defaultErrorHandler, std::function< void(Error)> WarningHandler=WithColor::defaultWarningHandler, bool ThreadSafe=false)
Tagged union holding either a T or a Error.
Definition: Error.h:481
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
size_t size() const
Definition: SmallVector.h:91
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:299
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
iterator end()
Definition: StringMap.h:220
iterator find(StringRef Key)
Definition: StringMap.h:233
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition: StringMap.h:308
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
static constexpr size_t npos
Definition: StringRef.h:52
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
bool isBPF() const
Tests whether the target is eBPF.
Definition: Triple.h:1043
@ UnknownArch
Definition: Triple.h:47
StringRef getFileName() const
Definition: Binary.cpp:41
BuildIDFetcher searches local cache directories for debug info.
Definition: BuildID.h:39
This class is the base class for all object file types.
Definition: ObjectFile.h:229
Triple makeTriple() const
Create a triple from the data in this object file.
Definition: ObjectFile.cpp:109
virtual bool hasDebugInfo() const
Definition: ObjectFile.cpp:99
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:81
void pushEvictor(std::function< void()> Evictor)
Definition: Symbolize.cpp:799
Expected< std::vector< DILineInfo > > findSymbol(const ObjectFile &Obj, StringRef Symbol, uint64_t Offset)
Definition: Symbolize.cpp:269
Expected< DIInliningInfo > symbolizeInlinedCode(const ObjectFile &Obj, object::SectionedAddress ModuleOffset)
Definition: Symbolize.cpp:135
Expected< SymbolizableModule * > getOrCreateModuleInfo(const std::string &ModuleName)
Returns a SymbolizableModule or an error if loading debug info failed.
Definition: Symbolize.cpp:607
Expected< DILineInfo > symbolizeCode(const ObjectFile &Obj, object::SectionedAddress ModuleOffset)
Definition: Symbolize.cpp:84
static std::string DemangleName(const std::string &Name, const SymbolizableModule *DbiModuleDescriptor)
Definition: Symbolize.cpp:750
Expected< DIGlobal > symbolizeData(const ObjectFile &Obj, object::SectionedAddress ModuleOffset)
Definition: Symbolize.cpp:180
Expected< std::vector< DILocal > > symbolizeFrame(const ObjectFile &Obj, object::SectionedAddress ModuleOffset)
Definition: Symbolize.cpp:221
virtual bool isWin32Module() const =0
static Expected< std::unique_ptr< SymbolizableObjectFile > > create(const object::ObjectFile *Obj, std::unique_ptr< DIContext > DICtx, bool UntagAddresses)
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
SmallVector< uint8_t, 10 > BuildID
A build ID in binary form.
Definition: BuildID.h:25
BuildIDRef getBuildID(const ObjectFile *Obj)
Returns the build ID, if any, contained in the given object file.
Definition: BuildID.cpp:56
Expected< std::unique_ptr< Binary > > createBinary(MemoryBufferRef Source, LLVMContext *Context=nullptr, bool InitContent=true)
Create a Binary from Source, autodetecting the file type.
Definition: Binary.cpp:45
static bool useBTFContext(const ObjectFile &Obj)
Definition: Symbolize.cpp:680
static StringRef getBuildIDStr(ArrayRef< uint8_t > BuildID)
Definition: Symbolize.cpp:476
void make_absolute(const Twine &current_directory, SmallVectorImpl< char > &path)
Make path an absolute path.
Definition: Path.cpp:907
void remove_filename(SmallVectorImpl< char > &path, Style style=Style::native)
Remove the last component from path unless it is the root dir.
Definition: Path.cpp:475
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:578
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:457
StringRef extension(StringRef path, Style style=Style::native)
Get extension.
Definition: Path.cpp:591
StringRef relative_path(StringRef path, Style style=Style::native)
Get relative path.
Definition: Path.cpp:414
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
@ Offset
Definition: DWP.cpp:480
bool nonMicrosoftDemangle(std::string_view MangledName, std::string &Result, bool CanHaveLeadingDot=true, bool ParseParams=true)
Definition: Demangle.cpp:49
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1722
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition: Error.h:1380
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1286
@ no_such_file_or_directory
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
@ Global
Append to llvm.global_dtors.
uint32_t crc32(ArrayRef< uint8_t > Data)
Definition: CRC.cpp:101
char * microsoftDemangle(std::string_view mangled_name, size_t *n_read, int *status, MSDemangleFlags Flags=MSDF_None)
Demangles the Microsoft symbol pointed at by mangled_name and returns it.
MSDemangleFlags
Definition: Demangle.h:37
@ MSDF_NoReturnType
Definition: Demangle.h:42
@ MSDF_NoMemberType
Definition: Demangle.h:43
@ MSDF_NoCallingConvention
Definition: Demangle.h:41
@ MSDF_NoAccessSpecifier
Definition: Demangle.h:40
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:111
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1069
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
Container for description of a global variable.
Definition: DIContext.h:120
Controls which fields of DILineInfo container should be filled with data.
Definition: DIContext.h:146
A format-neutral container for source line information.
Definition: DIContext.h:32
static constexpr const char *const BadString
Definition: DIContext.h:35
std::string FileName
Definition: DIContext.h:38
std::string FunctionName
Definition: DIContext.h:39
std::vector< std::string > DsymHints
Definition: Symbolize.h:62