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