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/FileSystem.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/Path.h"
31 static bool error(error_code ec) {
34 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
39 getDILineInfoSpecifierFlags(const LLVMSymbolizer::Options &Opts) {
40 uint32_t Flags = llvm::DILineInfoSpecifier::FileLineInfo |
41 llvm::DILineInfoSpecifier::AbsoluteFilePath;
42 if (Opts.PrintFunctions)
43 Flags |= llvm::DILineInfoSpecifier::FunctionName;
47 static void patchFunctionNameInDILineInfo(const std::string &NewFunctionName,
48 DILineInfo &LineInfo) {
49 std::string FileName = LineInfo.getFileName();
50 LineInfo = DILineInfo(StringRef(FileName), StringRef(NewFunctionName),
51 LineInfo.getLine(), LineInfo.getColumn());
54 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
55 : Module(Obj), DebugInfoContext(DICtx) {
56 for (const SymbolRef &Symbol : Module->symbols()) {
59 bool NoSymbolTable = (Module->symbol_begin() == Module->symbol_end());
60 if (NoSymbolTable && Module->isELF()) {
61 // Fallback to dynamic symbol table, if regular symbol table is stripped.
62 std::pair<symbol_iterator, symbol_iterator> IDyn =
63 getELFDynamicSymbolIterators(Module);
64 for (symbol_iterator si = IDyn.first, se = IDyn.second; si != se; ++si) {
70 void ModuleInfo::addSymbol(const SymbolRef &Symbol) {
71 SymbolRef::Type SymbolType;
72 if (error(Symbol.getType(SymbolType)))
74 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
76 uint64_t SymbolAddress;
77 if (error(Symbol.getAddress(SymbolAddress)) ||
78 SymbolAddress == UnknownAddressOrSize)
81 // Getting symbol size is linear for Mach-O files, so assume that symbol
82 // occupies the memory range up to the following symbol.
83 if (isa<MachOObjectFile>(Module))
85 else if (error(Symbol.getSize(SymbolSize)) ||
86 SymbolSize == UnknownAddressOrSize)
89 if (error(Symbol.getName(SymbolName)))
91 // Mach-O symbol table names have leading underscore, skip it.
92 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
93 SymbolName = SymbolName.drop_front();
94 // FIXME: If a function has alias, there are two entries in symbol table
95 // with same address size. Make sure we choose the correct one.
96 SymbolMapTy &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
97 SymbolDesc SD = { SymbolAddress, SymbolSize };
98 M.insert(std::make_pair(SD, SymbolName));
101 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
102 std::string &Name, uint64_t &Addr,
103 uint64_t &Size) const {
104 const SymbolMapTy &M = Type == SymbolRef::ST_Function ? Functions : Objects;
107 SymbolDesc SD = { Address, Address };
108 SymbolMapTy::const_iterator it = M.upper_bound(SD);
112 if (it->first.Size != 0 && it->first.Addr + it->first.Size <= Address)
114 Name = it->second.str();
115 Addr = it->first.Addr;
116 Size = it->first.Size;
120 DILineInfo ModuleInfo::symbolizeCode(
121 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
123 if (DebugInfoContext) {
124 LineInfo = DebugInfoContext->getLineInfoForAddress(
125 ModuleOffset, getDILineInfoSpecifierFlags(Opts));
127 // Override function name from symbol table if necessary.
128 if (Opts.PrintFunctions && Opts.UseSymbolTable) {
129 std::string FunctionName;
130 uint64_t Start, Size;
131 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
132 FunctionName, Start, Size)) {
133 patchFunctionNameInDILineInfo(FunctionName, LineInfo);
139 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
140 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
141 DIInliningInfo InlinedContext;
142 if (DebugInfoContext) {
143 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
144 ModuleOffset, getDILineInfoSpecifierFlags(Opts));
146 // Make sure there is at least one frame in context.
147 if (InlinedContext.getNumberOfFrames() == 0) {
148 InlinedContext.addFrame(DILineInfo());
150 // Override the function name in lower frame with name from symbol table.
151 if (Opts.PrintFunctions && Opts.UseSymbolTable) {
152 DIInliningInfo PatchedInlinedContext;
153 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
154 DILineInfo LineInfo = InlinedContext.getFrame(i);
156 std::string FunctionName;
157 uint64_t Start, Size;
158 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
159 FunctionName, Start, Size)) {
160 patchFunctionNameInDILineInfo(FunctionName, LineInfo);
163 PatchedInlinedContext.addFrame(LineInfo);
165 InlinedContext = PatchedInlinedContext;
167 return InlinedContext;
170 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
171 uint64_t &Start, uint64_t &Size) const {
172 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
176 const char LLVMSymbolizer::kBadString[] = "??";
178 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
179 uint64_t ModuleOffset) {
180 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
182 return printDILineInfo(DILineInfo());
183 if (Opts.PrintInlining) {
184 DIInliningInfo InlinedContext =
185 Info->symbolizeInlinedCode(ModuleOffset, Opts);
186 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
187 assert(FramesNum > 0);
189 for (uint32_t i = 0; i < FramesNum; i++) {
190 DILineInfo LineInfo = InlinedContext.getFrame(i);
191 Result += printDILineInfo(LineInfo);
195 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
196 return printDILineInfo(LineInfo);
199 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
200 uint64_t ModuleOffset) {
201 std::string Name = kBadString;
204 if (Opts.UseSymbolTable) {
205 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
206 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
207 Name = DemangleName(Name);
210 std::stringstream ss;
211 ss << Name << "\n" << Start << " " << Size << "\n";
215 void LLVMSymbolizer::flush() {
216 DeleteContainerSeconds(Modules);
217 DeleteContainerPointers(ParsedBinariesAndObjects);
218 BinaryForPath.clear();
219 ObjectFileForArch.clear();
222 static std::string getDarwinDWARFResourceForPath(const std::string &Path) {
223 StringRef Basename = sys::path::filename(Path);
224 const std::string &DSymDirectory = Path + ".dSYM";
225 SmallString<16> ResourceName = StringRef(DSymDirectory);
226 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
227 sys::path::append(ResourceName, Basename);
228 return ResourceName.str();
231 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
232 std::unique_ptr<MemoryBuffer> MB;
233 if (MemoryBuffer::getFileOrSTDIN(Path, MB))
235 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB->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(), NULL)) {
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 Binary *Bin, std::string &DebugName,
277 const ObjectFile *Obj = dyn_cast<ObjectFile>(Bin);
280 for (const SectionRef &Section : Obj->sections()) {
282 Section.getName(Name);
283 Name = Name.substr(Name.find_first_not_of("._"));
284 if (Name == "gnu_debuglink") {
286 Section.getContents(Data);
287 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
289 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
290 // 4-byte align the offset.
291 Offset = (Offset + 3) & ~0x3;
292 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
293 DebugName = DebugNameStr;
294 CRCHash = DE.getU32(&Offset);
304 LLVMSymbolizer::BinaryPair
305 LLVMSymbolizer::getOrCreateBinary(const std::string &Path) {
306 BinaryMapTy::iterator I = BinaryForPath.find(Path);
307 if (I != BinaryForPath.end())
311 ErrorOr<Binary *> BinaryOrErr = createBinary(Path);
312 if (!error(BinaryOrErr.getError())) {
313 std::unique_ptr<Binary> ParsedBinary(BinaryOrErr.get());
314 // Check if it's a universal binary.
315 Bin = ParsedBinary.release();
316 ParsedBinariesAndObjects.push_back(Bin);
317 if (Bin->isMachO() || Bin->isMachOUniversalBinary()) {
318 // On Darwin we may find DWARF in separate object file in
319 // resource directory.
320 const std::string &ResourcePath =
321 getDarwinDWARFResourceForPath(Path);
322 BinaryOrErr = createBinary(ResourcePath);
323 error_code EC = BinaryOrErr.getError();
324 if (EC != errc::no_such_file_or_directory && !error(EC)) {
325 DbgBin = BinaryOrErr.get();
326 ParsedBinariesAndObjects.push_back(DbgBin);
329 // Try to locate the debug binary using .gnu_debuglink section.
331 std::string DebuglinkName;
333 std::string DebugBinaryPath;
334 if (getGNUDebuglinkContents(Bin, DebuglinkName, CRCHash) &&
335 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
336 BinaryOrErr = createBinary(DebugBinaryPath);
337 if (!error(BinaryOrErr.getError())) {
338 DbgBin = BinaryOrErr.get();
339 ParsedBinariesAndObjects.push_back(DbgBin);
346 BinaryPair Res = std::make_pair(Bin, DbgBin);
347 BinaryForPath[Path] = Res;
352 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin, const std::string &ArchName) {
356 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
357 ObjectFileForArchMapTy::iterator I = ObjectFileForArch.find(
358 std::make_pair(UB, ArchName));
359 if (I != ObjectFileForArch.end())
361 std::unique_ptr<ObjectFile> ParsedObj;
362 if (!UB->getObjectForArch(Triple(ArchName).getArch(), ParsedObj)) {
363 Res = ParsedObj.release();
364 ParsedBinariesAndObjects.push_back(Res);
366 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
367 } else if (Bin->isObject()) {
368 Res = cast<ObjectFile>(Bin);
374 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
375 ModuleMapTy::iterator I = Modules.find(ModuleName);
376 if (I != Modules.end())
378 std::string BinaryName = ModuleName;
379 std::string ArchName = Opts.DefaultArch;
380 size_t ColonPos = ModuleName.find_last_of(':');
381 // Verify that substring after colon form a valid arch name.
382 if (ColonPos != std::string::npos) {
383 std::string ArchStr = ModuleName.substr(ColonPos + 1);
384 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
385 BinaryName = ModuleName.substr(0, ColonPos);
389 BinaryPair Binaries = getOrCreateBinary(BinaryName);
390 ObjectFile *Obj = getObjectFileFromBinary(Binaries.first, ArchName);
391 ObjectFile *DbgObj = getObjectFileFromBinary(Binaries.second, ArchName);
394 // Failed to find valid object file.
395 Modules.insert(make_pair(ModuleName, (ModuleInfo *)0));
398 DIContext *Context = DIContext::getDWARFContext(DbgObj);
400 ModuleInfo *Info = new ModuleInfo(Obj, Context);
401 Modules.insert(make_pair(ModuleName, Info));
405 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
406 // By default, DILineInfo contains "<invalid>" for function/filename it
407 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
408 static const std::string kDILineInfoBadString = "<invalid>";
409 std::stringstream Result;
410 if (Opts.PrintFunctions) {
411 std::string FunctionName = LineInfo.getFunctionName();
412 if (FunctionName == kDILineInfoBadString)
413 FunctionName = kBadString;
414 else if (Opts.Demangle)
415 FunctionName = DemangleName(FunctionName);
416 Result << FunctionName << "\n";
418 std::string Filename = LineInfo.getFileName();
419 if (Filename == kDILineInfoBadString)
420 Filename = kBadString;
421 Result << Filename << ":" << LineInfo.getLine() << ":" << LineInfo.getColumn()
426 #if !defined(_MSC_VER)
427 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
428 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
429 size_t *length, int *status);
432 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
433 #if !defined(_MSC_VER)
434 // We can spoil names of symbols with C linkage, so use an heuristic
435 // approach to check if the name should be demangled.
436 if (Name.substr(0, 2) != "_Z")
439 char *DemangledName = __cxa_demangle(Name.c_str(), 0, 0, &status);
442 std::string Result = DemangledName;
450 } // namespace symbolize