[C++11] Introduce ObjectFile::symbols() to use range-based loops.
[oota-llvm.git] / tools / llvm-symbolizer / LLVMSymbolize.cpp
1 //===-- LLVMSymbolize.cpp -------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implementation for LLVM symbolization library.
11 //
12 //===----------------------------------------------------------------------===//
13
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"
25 #include <sstream>
26 #include <stdlib.h>
27
28 namespace llvm {
29 namespace symbolize {
30
31 static bool error(error_code ec) {
32   if (!ec)
33     return false;
34   errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
35   return true;
36 }
37
38 static uint32_t
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;
44   return Flags;
45 }
46
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());
52 }
53
54 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
55     : Module(Obj), DebugInfoContext(DICtx) {
56   for (const SymbolRef &Symbol : Module->symbols()) {
57     addSymbol(Symbol);
58   }
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) {
65       addSymbol(*si);
66     }
67   }
68 }
69
70 void ModuleInfo::addSymbol(const SymbolRef &Symbol) {
71   SymbolRef::Type SymbolType;
72   if (error(Symbol.getType(SymbolType)))
73     return;
74   if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
75     return;
76   uint64_t SymbolAddress;
77   if (error(Symbol.getAddress(SymbolAddress)) ||
78       SymbolAddress == UnknownAddressOrSize)
79     return;
80   uint64_t SymbolSize;
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))
84     SymbolSize = 0;
85   else if (error(Symbol.getSize(SymbolSize)) ||
86            SymbolSize == UnknownAddressOrSize)
87     return;
88   StringRef SymbolName;
89   if (error(Symbol.getName(SymbolName)))
90     return;
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));
99 }
100
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;
105   if (M.empty())
106     return false;
107   SymbolDesc SD = { Address, Address };
108   SymbolMapTy::const_iterator it = M.upper_bound(SD);
109   if (it == M.begin())
110     return false;
111   --it;
112   if (it->first.Size != 0 && it->first.Addr + it->first.Size <= Address)
113     return false;
114   Name = it->second.str();
115   Addr = it->first.Addr;
116   Size = it->first.Size;
117   return true;
118 }
119
120 DILineInfo ModuleInfo::symbolizeCode(
121     uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
122   DILineInfo LineInfo;
123   if (DebugInfoContext) {
124     LineInfo = DebugInfoContext->getLineInfoForAddress(
125         ModuleOffset, getDILineInfoSpecifierFlags(Opts));
126   }
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);
134     }
135   }
136   return LineInfo;
137 }
138
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));
145   }
146   // Make sure there is at least one frame in context.
147   if (InlinedContext.getNumberOfFrames() == 0) {
148     InlinedContext.addFrame(DILineInfo());
149   }
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);
155       if (i == n - 1) {
156         std::string FunctionName;
157         uint64_t Start, Size;
158         if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
159                                    FunctionName, Start, Size)) {
160           patchFunctionNameInDILineInfo(FunctionName, LineInfo);
161         }
162       }
163       PatchedInlinedContext.addFrame(LineInfo);
164     }
165     InlinedContext = PatchedInlinedContext;
166   }
167   return InlinedContext;
168 }
169
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,
173                                 Size);
174 }
175
176 const char LLVMSymbolizer::kBadString[] = "??";
177
178 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
179                                           uint64_t ModuleOffset) {
180   ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
181   if (Info == 0)
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);
188     std::string Result;
189     for (uint32_t i = 0; i < FramesNum; i++) {
190       DILineInfo LineInfo = InlinedContext.getFrame(i);
191       Result += printDILineInfo(LineInfo);
192     }
193     return Result;
194   }
195   DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
196   return printDILineInfo(LineInfo);
197 }
198
199 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
200                                           uint64_t ModuleOffset) {
201   std::string Name = kBadString;
202   uint64_t Start = 0;
203   uint64_t Size = 0;
204   if (Opts.UseSymbolTable) {
205     if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
206       if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
207         Name = DemangleName(Name);
208     }
209   }
210   std::stringstream ss;
211   ss << Name << "\n" << Start << " " << Size << "\n";
212   return ss.str();
213 }
214
215 void LLVMSymbolizer::flush() {
216   DeleteContainerSeconds(Modules);
217   DeleteContainerPointers(ParsedBinariesAndObjects);
218   BinaryForPath.clear();
219   ObjectFileForArch.clear();
220 }
221
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();
229 }
230
231 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
232   std::unique_ptr<MemoryBuffer> MB;
233   if (MemoryBuffer::getFileOrSTDIN(Path, MB))
234     return false;
235   return !zlib::isAvailable() || CRCHash == zlib::crc32(MB->getBuffer());
236 }
237
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)) {
244     OrigRealPath = RP;
245     free(RP);
246   }
247 #endif
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();
255     return true;
256   }
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();
262     return true;
263   }
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),
267                           DebuglinkName);
268   if (checkFileCRC(DebugPath, CRCHash)) {
269     Result = DebugPath.str();
270     return true;
271   }
272   return false;
273 }
274
275 static bool getGNUDebuglinkContents(const Binary *Bin, std::string &DebugName,
276                                     uint32_t &CRCHash) {
277   const ObjectFile *Obj = dyn_cast<ObjectFile>(Bin);
278   if (!Obj)
279     return false;
280   for (const SectionRef &Section : Obj->sections()) {
281     StringRef Name;
282     Section.getName(Name);
283     Name = Name.substr(Name.find_first_not_of("._"));
284     if (Name == "gnu_debuglink") {
285       StringRef Data;
286       Section.getContents(Data);
287       DataExtractor DE(Data, Obj->isLittleEndian(), 0);
288       uint32_t Offset = 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);
295           return true;
296         }
297       }
298       break;
299     }
300   }
301   return false;
302 }
303
304 LLVMSymbolizer::BinaryPair
305 LLVMSymbolizer::getOrCreateBinary(const std::string &Path) {
306   BinaryMapTy::iterator I = BinaryForPath.find(Path);
307   if (I != BinaryForPath.end())
308     return I->second;
309   Binary *Bin = 0;
310   Binary *DbgBin = 0;
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);
327       }
328     }
329     // Try to locate the debug binary using .gnu_debuglink section.
330     if (DbgBin == 0) {
331       std::string DebuglinkName;
332       uint32_t CRCHash;
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);
340         }
341       }
342     }
343   }
344   if (DbgBin == 0)
345     DbgBin = Bin;
346   BinaryPair Res = std::make_pair(Bin, DbgBin);
347   BinaryForPath[Path] = Res;
348   return Res;
349 }
350
351 ObjectFile *
352 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin, const std::string &ArchName) {
353   if (Bin == 0)
354     return 0;
355   ObjectFile *Res = 0;
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())
360       return I->second;
361     std::unique_ptr<ObjectFile> ParsedObj;
362     if (!UB->getObjectForArch(Triple(ArchName).getArch(), ParsedObj)) {
363       Res = ParsedObj.release();
364       ParsedBinariesAndObjects.push_back(Res);
365     }
366     ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
367   } else if (Bin->isObject()) {
368     Res = cast<ObjectFile>(Bin);
369   }
370   return Res;
371 }
372
373 ModuleInfo *
374 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
375   ModuleMapTy::iterator I = Modules.find(ModuleName);
376   if (I != Modules.end())
377     return I->second;
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);
386       ArchName = ArchStr;
387     }
388   }
389   BinaryPair Binaries = getOrCreateBinary(BinaryName);
390   ObjectFile *Obj = getObjectFileFromBinary(Binaries.first, ArchName);
391   ObjectFile *DbgObj = getObjectFileFromBinary(Binaries.second, ArchName);
392
393   if (Obj == 0) {
394     // Failed to find valid object file.
395     Modules.insert(make_pair(ModuleName, (ModuleInfo *)0));
396     return 0;
397   }
398   DIContext *Context = DIContext::getDWARFContext(DbgObj);
399   assert(Context);
400   ModuleInfo *Info = new ModuleInfo(Obj, Context);
401   Modules.insert(make_pair(ModuleName, Info));
402   return Info;
403 }
404
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";
417   }
418   std::string Filename = LineInfo.getFileName();
419   if (Filename == kDILineInfoBadString)
420     Filename = kBadString;
421   Result << Filename << ":" << LineInfo.getLine() << ":" << LineInfo.getColumn()
422          << "\n";
423   return Result.str();
424 }
425
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);
430 #endif
431
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")
437     return Name;
438   int status = 0;
439   char *DemangledName = __cxa_demangle(Name.c_str(), 0, 0, &status);
440   if (status != 0)
441     return Name;
442   std::string Result = DemangledName;
443   free(DemangledName);
444   return Result;
445 #else
446   return Name;
447 #endif
448 }
449
450 } // namespace symbolize
451 } // namespace llvm