1 //===-- LLVMSymbolize.cpp -------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implementation for LLVM symbolization library.
12 //===----------------------------------------------------------------------===//
14 #include "LLVMSymbolize.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/Config/config.h"
17 #include "llvm/Object/ELFObjectFile.h"
18 #include "llvm/Object/MachO.h"
19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/Compression.h"
21 #include "llvm/Support/DataExtractor.h"
22 #include "llvm/Support/Errc.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/Path.h"
32 static bool error(std::error_code ec) {
35 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
39 static DILineInfoSpecifier
40 getDILineInfoSpecifier(const LLVMSymbolizer::Options &Opts) {
41 return DILineInfoSpecifier(
42 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
46 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
47 : Module(Obj), DebugInfoContext(DICtx) {
48 for (const SymbolRef &Symbol : Module->symbols()) {
51 bool NoSymbolTable = (Module->symbol_begin() == Module->symbol_end());
52 if (NoSymbolTable && Module->isELF()) {
53 // Fallback to dynamic symbol table, if regular symbol table is stripped.
54 std::pair<symbol_iterator, symbol_iterator> IDyn =
55 getELFDynamicSymbolIterators(Module);
56 for (symbol_iterator si = IDyn.first, se = IDyn.second; si != se; ++si) {
62 void ModuleInfo::addSymbol(const SymbolRef &Symbol) {
63 SymbolRef::Type SymbolType;
64 if (error(Symbol.getType(SymbolType)))
66 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
68 uint64_t SymbolAddress;
69 if (error(Symbol.getAddress(SymbolAddress)) ||
70 SymbolAddress == UnknownAddressOrSize)
73 // Getting symbol size is linear for Mach-O files, so assume that symbol
74 // occupies the memory range up to the following symbol.
75 if (isa<MachOObjectFile>(Module))
77 else if (error(Symbol.getSize(SymbolSize)) ||
78 SymbolSize == UnknownAddressOrSize)
81 if (error(Symbol.getName(SymbolName)))
83 // Mach-O symbol table names have leading underscore, skip it.
84 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
85 SymbolName = SymbolName.drop_front();
86 // FIXME: If a function has alias, there are two entries in symbol table
87 // with same address size. Make sure we choose the correct one.
88 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
89 SymbolDesc SD = { SymbolAddress, SymbolSize };
90 M.insert(std::make_pair(SD, SymbolName));
93 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
94 std::string &Name, uint64_t &Addr,
95 uint64_t &Size) const {
96 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
97 if (SymbolMap.empty())
99 SymbolDesc SD = { Address, Address };
100 auto SymbolIterator = SymbolMap.upper_bound(SD);
101 if (SymbolIterator == SymbolMap.begin())
104 if (SymbolIterator->first.Size != 0 &&
105 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
107 Name = SymbolIterator->second.str();
108 Addr = SymbolIterator->first.Addr;
109 Size = SymbolIterator->first.Size;
113 DILineInfo ModuleInfo::symbolizeCode(
114 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
116 if (DebugInfoContext) {
117 LineInfo = DebugInfoContext->getLineInfoForAddress(
118 ModuleOffset, getDILineInfoSpecifier(Opts));
120 // Override function name from symbol table if necessary.
121 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
122 std::string FunctionName;
123 uint64_t Start, Size;
124 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
125 FunctionName, Start, Size)) {
126 LineInfo.FunctionName = FunctionName;
132 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
133 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
134 DIInliningInfo InlinedContext;
135 if (DebugInfoContext) {
136 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
137 ModuleOffset, getDILineInfoSpecifier(Opts));
139 // Make sure there is at least one frame in context.
140 if (InlinedContext.getNumberOfFrames() == 0) {
141 InlinedContext.addFrame(DILineInfo());
143 // Override the function name in lower frame with name from symbol table.
144 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
145 DIInliningInfo PatchedInlinedContext;
146 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
147 DILineInfo LineInfo = InlinedContext.getFrame(i);
149 std::string FunctionName;
150 uint64_t Start, Size;
151 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
152 FunctionName, Start, Size)) {
153 LineInfo.FunctionName = FunctionName;
156 PatchedInlinedContext.addFrame(LineInfo);
158 InlinedContext = PatchedInlinedContext;
160 return InlinedContext;
163 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
164 uint64_t &Start, uint64_t &Size) const {
165 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
169 const char LLVMSymbolizer::kBadString[] = "??";
171 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
172 uint64_t ModuleOffset) {
173 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
175 return printDILineInfo(DILineInfo());
176 if (Opts.PrintInlining) {
177 DIInliningInfo InlinedContext =
178 Info->symbolizeInlinedCode(ModuleOffset, Opts);
179 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
180 assert(FramesNum > 0);
182 for (uint32_t i = 0; i < FramesNum; i++) {
183 DILineInfo LineInfo = InlinedContext.getFrame(i);
184 Result += printDILineInfo(LineInfo);
188 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
189 return printDILineInfo(LineInfo);
192 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
193 uint64_t ModuleOffset) {
194 std::string Name = kBadString;
197 if (Opts.UseSymbolTable) {
198 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
199 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
200 Name = DemangleName(Name);
203 std::stringstream ss;
204 ss << Name << "\n" << Start << " " << Size << "\n";
208 void LLVMSymbolizer::flush() {
209 DeleteContainerSeconds(Modules);
210 ObjectPairForPathArch.clear();
211 ObjectFileForArch.clear();
214 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
215 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
216 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
217 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
219 std::string getDarwinDWARFResourceForPath(
220 const std::string &Path, const std::string &Basename) {
221 SmallString<16> ResourceName = StringRef(Path);
222 if (sys::path::extension(Path) != ".dSYM") {
223 ResourceName += ".dSYM";
225 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
226 sys::path::append(ResourceName, Basename);
227 return ResourceName.str();
230 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
231 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
232 MemoryBuffer::getFileOrSTDIN(Path);
235 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
238 static bool findDebugBinary(const std::string &OrigPath,
239 const std::string &DebuglinkName, uint32_t CRCHash,
240 std::string &Result) {
241 std::string OrigRealPath = OrigPath;
242 #if defined(HAVE_REALPATH)
243 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
248 SmallString<16> OrigDir(OrigRealPath);
249 llvm::sys::path::remove_filename(OrigDir);
250 SmallString<16> DebugPath = OrigDir;
251 // Try /path/to/original_binary/debuglink_name
252 llvm::sys::path::append(DebugPath, DebuglinkName);
253 if (checkFileCRC(DebugPath, CRCHash)) {
254 Result = DebugPath.str();
257 // Try /path/to/original_binary/.debug/debuglink_name
258 DebugPath = OrigRealPath;
259 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
260 if (checkFileCRC(DebugPath, CRCHash)) {
261 Result = DebugPath.str();
264 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
265 DebugPath = "/usr/lib/debug";
266 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
268 if (checkFileCRC(DebugPath, CRCHash)) {
269 Result = DebugPath.str();
275 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
279 for (const SectionRef &Section : Obj->sections()) {
281 Section.getName(Name);
282 Name = Name.substr(Name.find_first_not_of("._"));
283 if (Name == "gnu_debuglink") {
285 Section.getContents(Data);
286 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
288 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
289 // 4-byte align the offset.
290 Offset = (Offset + 3) & ~0x3;
291 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
292 DebugName = DebugNameStr;
293 CRCHash = DE.getU32(&Offset);
304 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
305 const MachOObjectFile *Obj) {
306 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
307 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
308 if (dbg_uuid.empty() || bin_uuid.empty())
310 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
313 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
314 const MachOObjectFile *MachExeObj, 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(getDarwinDWARFResourceForPath(ExePath, Filename));
320 for (const auto &Path : Opts.DsymHints) {
321 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
323 for (const auto &path : DsymPaths) {
324 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
325 std::error_code EC = BinaryOrErr.getError();
326 if (EC != errc::no_such_file_or_directory && !error(EC)) {
327 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
329 getObjectFileFromBinary(B.getBinary().get(), ArchName);
330 const MachOObjectFile *MachDbgObj =
331 dyn_cast<const MachOObjectFile>(DbgObj);
332 if (!MachDbgObj) continue;
333 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
334 addOwningBinary(std::move(B));
342 LLVMSymbolizer::ObjectPair
343 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
344 const std::string &ArchName) {
345 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
346 if (I != ObjectPairForPathArch.end())
348 ObjectFile *Obj = nullptr;
349 ObjectFile *DbgObj = nullptr;
350 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
351 if (!error(BinaryOrErr.getError())) {
352 OwningBinary<Binary> &B = BinaryOrErr.get();
353 Obj = getObjectFileFromBinary(B.getBinary().get(), ArchName);
355 ObjectPair Res = std::make_pair(nullptr, nullptr);
356 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
359 addOwningBinary(std::move(B));
360 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
361 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
362 // Try to locate the debug binary using .gnu_debuglink section.
364 std::string DebuglinkName;
366 std::string DebugBinaryPath;
367 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
368 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
369 BinaryOrErr = createBinary(DebugBinaryPath);
370 if (!error(BinaryOrErr.getError())) {
371 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
372 DbgObj = getObjectFileFromBinary(B.getBinary().get(), ArchName);
373 addOwningBinary(std::move(B));
380 ObjectPair Res = std::make_pair(Obj, DbgObj);
381 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
386 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
387 const std::string &ArchName) {
390 ObjectFile *Res = nullptr;
391 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
392 const auto &I = ObjectFileForArch.find(
393 std::make_pair(UB, ArchName));
394 if (I != ObjectFileForArch.end())
396 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
397 UB->getObjectForArch(Triple(ArchName).getArch());
399 Res = ParsedObj.get().get();
400 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
402 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
403 } else if (Bin->isObject()) {
404 Res = cast<ObjectFile>(Bin);
410 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
411 const auto &I = Modules.find(ModuleName);
412 if (I != Modules.end())
414 std::string BinaryName = ModuleName;
415 std::string ArchName = Opts.DefaultArch;
416 size_t ColonPos = ModuleName.find_last_of(':');
417 // Verify that substring after colon form a valid arch name.
418 if (ColonPos != std::string::npos) {
419 std::string ArchStr = ModuleName.substr(ColonPos + 1);
420 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
421 BinaryName = ModuleName.substr(0, ColonPos);
425 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
427 if (!Objects.first) {
428 // Failed to find valid object file.
429 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
432 DIContext *Context = DIContext::getDWARFContext(*Objects.second);
434 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
435 Modules.insert(make_pair(ModuleName, Info));
439 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
440 // By default, DILineInfo contains "<invalid>" for function/filename it
441 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
442 static const std::string kDILineInfoBadString = "<invalid>";
443 std::stringstream Result;
444 if (Opts.PrintFunctions != FunctionNameKind::None) {
445 std::string FunctionName = LineInfo.FunctionName;
446 if (FunctionName == kDILineInfoBadString)
447 FunctionName = kBadString;
448 else if (Opts.Demangle)
449 FunctionName = DemangleName(FunctionName);
450 Result << FunctionName << "\n";
452 std::string Filename = LineInfo.FileName;
453 if (Filename == kDILineInfoBadString)
454 Filename = kBadString;
455 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
459 #if !defined(_MSC_VER)
460 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
461 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
462 size_t *length, int *status);
465 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
466 #if !defined(_MSC_VER)
467 // We can spoil names of symbols with C linkage, so use an heuristic
468 // approach to check if the name should be demangled.
469 if (Name.substr(0, 2) != "_Z")
472 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
475 std::string Result = DemangledName;
483 } // namespace symbolize