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 (symbol_iterator si = Module->symbol_begin(), se = Module->symbol_end();
60 bool NoSymbolTable = (Module->symbol_begin() == Module->symbol_end());
61 if (NoSymbolTable && Module->isELF()) {
62 // Fallback to dynamic symbol table, if regular symbol table is stripped.
63 std::pair<symbol_iterator, symbol_iterator> IDyn =
64 getELFDynamicSymbolIterators(Module);
65 for (symbol_iterator si = IDyn.first, se = IDyn.second; si != se; ++si) {
71 void ModuleInfo::addSymbol(const symbol_iterator &Sym) {
72 SymbolRef::Type SymbolType;
73 if (error(Sym->getType(SymbolType)))
75 if (SymbolType != SymbolRef::ST_Function &&
76 SymbolType != SymbolRef::ST_Data)
78 uint64_t SymbolAddress;
79 if (error(Sym->getAddress(SymbolAddress)) ||
80 SymbolAddress == UnknownAddressOrSize)
83 // Getting symbol size is linear for Mach-O files, so assume that symbol
84 // occupies the memory range up to the following symbol.
85 if (isa<MachOObjectFile>(Module))
87 else if (error(Sym->getSize(SymbolSize)) ||
88 SymbolSize == UnknownAddressOrSize)
91 if (error(Sym->getName(SymbolName)))
93 // Mach-O symbol table names have leading underscore, skip it.
94 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
95 SymbolName = SymbolName.drop_front();
96 // FIXME: If a function has alias, there are two entries in symbol table
97 // with same address size. Make sure we choose the correct one.
98 SymbolMapTy &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
99 SymbolDesc SD = { SymbolAddress, SymbolSize };
100 M.insert(std::make_pair(SD, SymbolName));
103 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
104 std::string &Name, uint64_t &Addr,
105 uint64_t &Size) const {
106 const SymbolMapTy &M = Type == SymbolRef::ST_Function ? Functions : Objects;
109 SymbolDesc SD = { Address, Address };
110 SymbolMapTy::const_iterator it = M.upper_bound(SD);
114 if (it->first.Size != 0 && it->first.Addr + it->first.Size <= Address)
116 Name = it->second.str();
117 Addr = it->first.Addr;
118 Size = it->first.Size;
122 DILineInfo ModuleInfo::symbolizeCode(
123 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
125 if (DebugInfoContext) {
126 LineInfo = DebugInfoContext->getLineInfoForAddress(
127 ModuleOffset, getDILineInfoSpecifierFlags(Opts));
129 // Override function name from symbol table if necessary.
130 if (Opts.PrintFunctions && Opts.UseSymbolTable) {
131 std::string FunctionName;
132 uint64_t Start, Size;
133 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
134 FunctionName, Start, Size)) {
135 patchFunctionNameInDILineInfo(FunctionName, LineInfo);
141 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
142 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
143 DIInliningInfo InlinedContext;
144 if (DebugInfoContext) {
145 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
146 ModuleOffset, getDILineInfoSpecifierFlags(Opts));
148 // Make sure there is at least one frame in context.
149 if (InlinedContext.getNumberOfFrames() == 0) {
150 InlinedContext.addFrame(DILineInfo());
152 // Override the function name in lower frame with name from symbol table.
153 if (Opts.PrintFunctions && Opts.UseSymbolTable) {
154 DIInliningInfo PatchedInlinedContext;
155 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
156 DILineInfo LineInfo = InlinedContext.getFrame(i);
158 std::string FunctionName;
159 uint64_t Start, Size;
160 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
161 FunctionName, Start, Size)) {
162 patchFunctionNameInDILineInfo(FunctionName, LineInfo);
165 PatchedInlinedContext.addFrame(LineInfo);
167 InlinedContext = PatchedInlinedContext;
169 return InlinedContext;
172 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
173 uint64_t &Start, uint64_t &Size) const {
174 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
178 const char LLVMSymbolizer::kBadString[] = "??";
180 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
181 uint64_t ModuleOffset) {
182 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
184 return printDILineInfo(DILineInfo());
185 if (Opts.PrintInlining) {
186 DIInliningInfo InlinedContext =
187 Info->symbolizeInlinedCode(ModuleOffset, Opts);
188 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
189 assert(FramesNum > 0);
191 for (uint32_t i = 0; i < FramesNum; i++) {
192 DILineInfo LineInfo = InlinedContext.getFrame(i);
193 Result += printDILineInfo(LineInfo);
197 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
198 return printDILineInfo(LineInfo);
201 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
202 uint64_t ModuleOffset) {
203 std::string Name = kBadString;
206 if (Opts.UseSymbolTable) {
207 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
208 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
209 Name = DemangleName(Name);
212 std::stringstream ss;
213 ss << Name << "\n" << Start << " " << Size << "\n";
217 void LLVMSymbolizer::flush() {
218 DeleteContainerSeconds(Modules);
219 DeleteContainerPointers(ParsedBinariesAndObjects);
220 BinaryForPath.clear();
221 ObjectFileForArch.clear();
224 static std::string getDarwinDWARFResourceForPath(const std::string &Path) {
225 StringRef Basename = sys::path::filename(Path);
226 const std::string &DSymDirectory = Path + ".dSYM";
227 SmallString<16> ResourceName = StringRef(DSymDirectory);
228 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
229 sys::path::append(ResourceName, Basename);
230 return ResourceName.str();
233 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
234 std::unique_ptr<MemoryBuffer> MB;
235 if (MemoryBuffer::getFileOrSTDIN(Path, MB))
237 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB->getBuffer());
240 static bool findDebugBinary(const std::string &OrigPath,
241 const std::string &DebuglinkName, uint32_t CRCHash,
242 std::string &Result) {
243 std::string OrigRealPath = OrigPath;
244 #if defined(HAVE_REALPATH)
245 if (char *RP = realpath(OrigPath.c_str(), NULL)) {
250 SmallString<16> OrigDir(OrigRealPath);
251 llvm::sys::path::remove_filename(OrigDir);
252 SmallString<16> DebugPath = OrigDir;
253 // Try /path/to/original_binary/debuglink_name
254 llvm::sys::path::append(DebugPath, DebuglinkName);
255 if (checkFileCRC(DebugPath, CRCHash)) {
256 Result = DebugPath.str();
259 // Try /path/to/original_binary/.debug/debuglink_name
260 DebugPath = OrigRealPath;
261 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
262 if (checkFileCRC(DebugPath, CRCHash)) {
263 Result = DebugPath.str();
266 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
267 DebugPath = "/usr/lib/debug";
268 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
270 if (checkFileCRC(DebugPath, CRCHash)) {
271 Result = DebugPath.str();
277 static bool getGNUDebuglinkContents(const Binary *Bin, std::string &DebugName,
279 const ObjectFile *Obj = dyn_cast<ObjectFile>(Bin);
282 for (const SectionRef &Section : Obj->sections()) {
284 Section.getName(Name);
285 Name = Name.substr(Name.find_first_not_of("._"));
286 if (Name == "gnu_debuglink") {
288 Section.getContents(Data);
289 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
291 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
292 // 4-byte align the offset.
293 Offset = (Offset + 3) & ~0x3;
294 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
295 DebugName = DebugNameStr;
296 CRCHash = DE.getU32(&Offset);
306 LLVMSymbolizer::BinaryPair
307 LLVMSymbolizer::getOrCreateBinary(const std::string &Path) {
308 BinaryMapTy::iterator I = BinaryForPath.find(Path);
309 if (I != BinaryForPath.end())
313 ErrorOr<Binary *> BinaryOrErr = createBinary(Path);
314 if (!error(BinaryOrErr.getError())) {
315 std::unique_ptr<Binary> ParsedBinary(BinaryOrErr.get());
316 // Check if it's a universal binary.
317 Bin = ParsedBinary.release();
318 ParsedBinariesAndObjects.push_back(Bin);
319 if (Bin->isMachO() || Bin->isMachOUniversalBinary()) {
320 // On Darwin we may find DWARF in separate object file in
321 // resource directory.
322 const std::string &ResourcePath =
323 getDarwinDWARFResourceForPath(Path);
324 BinaryOrErr = createBinary(ResourcePath);
325 error_code EC = BinaryOrErr.getError();
326 if (EC != errc::no_such_file_or_directory && !error(EC)) {
327 DbgBin = BinaryOrErr.get();
328 ParsedBinariesAndObjects.push_back(DbgBin);
331 // Try to locate the debug binary using .gnu_debuglink section.
333 std::string DebuglinkName;
335 std::string DebugBinaryPath;
336 if (getGNUDebuglinkContents(Bin, DebuglinkName, CRCHash) &&
337 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
338 BinaryOrErr = createBinary(DebugBinaryPath);
339 if (!error(BinaryOrErr.getError())) {
340 DbgBin = BinaryOrErr.get();
341 ParsedBinariesAndObjects.push_back(DbgBin);
348 BinaryPair Res = std::make_pair(Bin, DbgBin);
349 BinaryForPath[Path] = Res;
354 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin, const std::string &ArchName) {
358 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
359 ObjectFileForArchMapTy::iterator I = ObjectFileForArch.find(
360 std::make_pair(UB, ArchName));
361 if (I != ObjectFileForArch.end())
363 std::unique_ptr<ObjectFile> ParsedObj;
364 if (!UB->getObjectForArch(Triple(ArchName).getArch(), ParsedObj)) {
365 Res = ParsedObj.release();
366 ParsedBinariesAndObjects.push_back(Res);
368 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
369 } else if (Bin->isObject()) {
370 Res = cast<ObjectFile>(Bin);
376 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
377 ModuleMapTy::iterator I = Modules.find(ModuleName);
378 if (I != Modules.end())
380 std::string BinaryName = ModuleName;
381 std::string ArchName = Opts.DefaultArch;
382 size_t ColonPos = ModuleName.find_last_of(':');
383 // Verify that substring after colon form a valid arch name.
384 if (ColonPos != std::string::npos) {
385 std::string ArchStr = ModuleName.substr(ColonPos + 1);
386 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
387 BinaryName = ModuleName.substr(0, ColonPos);
391 BinaryPair Binaries = getOrCreateBinary(BinaryName);
392 ObjectFile *Obj = getObjectFileFromBinary(Binaries.first, ArchName);
393 ObjectFile *DbgObj = getObjectFileFromBinary(Binaries.second, ArchName);
396 // Failed to find valid object file.
397 Modules.insert(make_pair(ModuleName, (ModuleInfo *)0));
400 DIContext *Context = DIContext::getDWARFContext(DbgObj);
402 ModuleInfo *Info = new ModuleInfo(Obj, Context);
403 Modules.insert(make_pair(ModuleName, Info));
407 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
408 // By default, DILineInfo contains "<invalid>" for function/filename it
409 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
410 static const std::string kDILineInfoBadString = "<invalid>";
411 std::stringstream Result;
412 if (Opts.PrintFunctions) {
413 std::string FunctionName = LineInfo.getFunctionName();
414 if (FunctionName == kDILineInfoBadString)
415 FunctionName = kBadString;
416 else if (Opts.Demangle)
417 FunctionName = DemangleName(FunctionName);
418 Result << FunctionName << "\n";
420 std::string Filename = LineInfo.getFileName();
421 if (Filename == kDILineInfoBadString)
422 Filename = kBadString;
423 Result << Filename << ":" << LineInfo.getLine() << ":" << LineInfo.getColumn()
428 #if !defined(_MSC_VER)
429 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
430 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
431 size_t *length, int *status);
434 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
435 #if !defined(_MSC_VER)
436 // We can spoil names of symbols with C linkage, so use an heuristic
437 // approach to check if the name should be demangled.
438 if (Name.substr(0, 2) != "_Z")
441 char *DemangledName = __cxa_demangle(Name.c_str(), 0, 0, &status);
444 std::string Result = DemangledName;
452 } // namespace symbolize