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 BinaryForPath.clear();
211 ObjectFileForArch.clear();
214 static std::string getDarwinDWARFResourceForPath(const std::string &Path) {
215 StringRef Basename = sys::path::filename(Path);
216 const std::string &DSymDirectory = Path + ".dSYM";
217 SmallString<16> ResourceName = StringRef(DSymDirectory);
218 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
219 sys::path::append(ResourceName, Basename);
220 return ResourceName.str();
223 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
224 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
225 MemoryBuffer::getFileOrSTDIN(Path);
228 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
231 static bool findDebugBinary(const std::string &OrigPath,
232 const std::string &DebuglinkName, uint32_t CRCHash,
233 std::string &Result) {
234 std::string OrigRealPath = OrigPath;
235 #if defined(HAVE_REALPATH)
236 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
241 SmallString<16> OrigDir(OrigRealPath);
242 llvm::sys::path::remove_filename(OrigDir);
243 SmallString<16> DebugPath = OrigDir;
244 // Try /path/to/original_binary/debuglink_name
245 llvm::sys::path::append(DebugPath, DebuglinkName);
246 if (checkFileCRC(DebugPath, CRCHash)) {
247 Result = DebugPath.str();
250 // Try /path/to/original_binary/.debug/debuglink_name
251 DebugPath = OrigRealPath;
252 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
253 if (checkFileCRC(DebugPath, CRCHash)) {
254 Result = DebugPath.str();
257 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
258 DebugPath = "/usr/lib/debug";
259 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
261 if (checkFileCRC(DebugPath, CRCHash)) {
262 Result = DebugPath.str();
268 static bool getGNUDebuglinkContents(const Binary *Bin, std::string &DebugName,
270 const ObjectFile *Obj = dyn_cast<ObjectFile>(Bin);
273 for (const SectionRef &Section : Obj->sections()) {
275 Section.getName(Name);
276 Name = Name.substr(Name.find_first_not_of("._"));
277 if (Name == "gnu_debuglink") {
279 Section.getContents(Data);
280 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
282 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
283 // 4-byte align the offset.
284 Offset = (Offset + 3) & ~0x3;
285 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
286 DebugName = DebugNameStr;
287 CRCHash = DE.getU32(&Offset);
297 LLVMSymbolizer::BinaryPair
298 LLVMSymbolizer::getOrCreateBinary(const std::string &Path) {
299 const auto &I = BinaryForPath.find(Path);
300 if (I != BinaryForPath.end())
302 Binary *Bin = nullptr;
303 Binary *DbgBin = nullptr;
304 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
305 if (!error(BinaryOrErr.getError())) {
306 OwningBinary<Binary> &ParsedBinary = BinaryOrErr.get();
307 // Check if it's a universal binary.
308 Bin = ParsedBinary.getBinary().get();
309 addOwningBinary(std::move(ParsedBinary));
310 if (Bin->isMachO() || Bin->isMachOUniversalBinary()) {
311 // On Darwin we may find DWARF in separate object file in
312 // resource directory.
313 const std::string &ResourcePath =
314 getDarwinDWARFResourceForPath(Path);
315 BinaryOrErr = createBinary(ResourcePath);
316 std::error_code EC = BinaryOrErr.getError();
317 if (EC != errc::no_such_file_or_directory && !error(EC)) {
318 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
319 DbgBin = B.getBinary().get();
320 addOwningBinary(std::move(B));
323 // Try to locate the debug binary using .gnu_debuglink section.
325 std::string DebuglinkName;
327 std::string DebugBinaryPath;
328 if (getGNUDebuglinkContents(Bin, DebuglinkName, CRCHash) &&
329 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
330 BinaryOrErr = createBinary(DebugBinaryPath);
331 if (!error(BinaryOrErr.getError())) {
332 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
333 DbgBin = B.getBinary().get();
334 addOwningBinary(std::move(B));
341 BinaryPair Res = std::make_pair(Bin, DbgBin);
342 BinaryForPath[Path] = Res;
347 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin, const std::string &ArchName) {
350 ObjectFile *Res = nullptr;
351 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
352 const auto &I = ObjectFileForArch.find(
353 std::make_pair(UB, ArchName));
354 if (I != ObjectFileForArch.end())
356 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
357 UB->getObjectForArch(Triple(ArchName).getArch());
359 Res = ParsedObj.get().get();
360 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
362 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
363 } else if (Bin->isObject()) {
364 Res = cast<ObjectFile>(Bin);
370 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
371 const auto &I = Modules.find(ModuleName);
372 if (I != Modules.end())
374 std::string BinaryName = ModuleName;
375 std::string ArchName = Opts.DefaultArch;
376 size_t ColonPos = ModuleName.find_last_of(':');
377 // Verify that substring after colon form a valid arch name.
378 if (ColonPos != std::string::npos) {
379 std::string ArchStr = ModuleName.substr(ColonPos + 1);
380 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
381 BinaryName = ModuleName.substr(0, ColonPos);
385 BinaryPair Binaries = getOrCreateBinary(BinaryName);
386 ObjectFile *Obj = getObjectFileFromBinary(Binaries.first, ArchName);
387 ObjectFile *DbgObj = getObjectFileFromBinary(Binaries.second, ArchName);
390 // Failed to find valid object file.
391 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
394 DIContext *Context = DIContext::getDWARFContext(*DbgObj);
396 ModuleInfo *Info = new ModuleInfo(Obj, Context);
397 Modules.insert(make_pair(ModuleName, Info));
401 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
402 // By default, DILineInfo contains "<invalid>" for function/filename it
403 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
404 static const std::string kDILineInfoBadString = "<invalid>";
405 std::stringstream Result;
406 if (Opts.PrintFunctions != FunctionNameKind::None) {
407 std::string FunctionName = LineInfo.FunctionName;
408 if (FunctionName == kDILineInfoBadString)
409 FunctionName = kBadString;
410 else if (Opts.Demangle)
411 FunctionName = DemangleName(FunctionName);
412 Result << FunctionName << "\n";
414 std::string Filename = LineInfo.FileName;
415 if (Filename == kDILineInfoBadString)
416 Filename = kBadString;
417 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
421 #if !defined(_MSC_VER)
422 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
423 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
424 size_t *length, int *status);
427 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
428 #if !defined(_MSC_VER)
429 // We can spoil names of symbols with C linkage, so use an heuristic
430 // approach to check if the name should be demangled.
431 if (Name.substr(0, 2) != "_Z")
434 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
437 std::string Result = DemangledName;
445 } // namespace symbolize