Don't use 'using std::error_code' in include/llvm.
[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 using std::error_code;
30 namespace symbolize {
31
32 static bool error(error_code ec) {
33   if (!ec)
34     return false;
35   errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
36   return true;
37 }
38
39 static DILineInfoSpecifier
40 getDILineInfoSpecifier(const LLVMSymbolizer::Options &Opts) {
41   return DILineInfoSpecifier(
42       DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
43       Opts.PrintFunctions);
44 }
45
46 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
47     : Module(Obj), DebugInfoContext(DICtx) {
48   for (const SymbolRef &Symbol : Module->symbols()) {
49     addSymbol(Symbol);
50   }
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) {
57       addSymbol(*si);
58     }
59   }
60 }
61
62 void ModuleInfo::addSymbol(const SymbolRef &Symbol) {
63   SymbolRef::Type SymbolType;
64   if (error(Symbol.getType(SymbolType)))
65     return;
66   if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
67     return;
68   uint64_t SymbolAddress;
69   if (error(Symbol.getAddress(SymbolAddress)) ||
70       SymbolAddress == UnknownAddressOrSize)
71     return;
72   uint64_t SymbolSize;
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))
76     SymbolSize = 0;
77   else if (error(Symbol.getSize(SymbolSize)) ||
78            SymbolSize == UnknownAddressOrSize)
79     return;
80   StringRef SymbolName;
81   if (error(Symbol.getName(SymbolName)))
82     return;
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   SymbolMapTy &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
89   SymbolDesc SD = { SymbolAddress, SymbolSize };
90   M.insert(std::make_pair(SD, SymbolName));
91 }
92
93 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
94                                         std::string &Name, uint64_t &Addr,
95                                         uint64_t &Size) const {
96   const SymbolMapTy &M = Type == SymbolRef::ST_Function ? Functions : Objects;
97   if (M.empty())
98     return false;
99   SymbolDesc SD = { Address, Address };
100   SymbolMapTy::const_iterator it = M.upper_bound(SD);
101   if (it == M.begin())
102     return false;
103   --it;
104   if (it->first.Size != 0 && it->first.Addr + it->first.Size <= Address)
105     return false;
106   Name = it->second.str();
107   Addr = it->first.Addr;
108   Size = it->first.Size;
109   return true;
110 }
111
112 DILineInfo ModuleInfo::symbolizeCode(
113     uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
114   DILineInfo LineInfo;
115   if (DebugInfoContext) {
116     LineInfo = DebugInfoContext->getLineInfoForAddress(
117         ModuleOffset, getDILineInfoSpecifier(Opts));
118   }
119   // Override function name from symbol table if necessary.
120   if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
121     std::string FunctionName;
122     uint64_t Start, Size;
123     if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
124                                FunctionName, Start, Size)) {
125       LineInfo.FunctionName = FunctionName;
126     }
127   }
128   return LineInfo;
129 }
130
131 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
132     uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
133   DIInliningInfo InlinedContext;
134   if (DebugInfoContext) {
135     InlinedContext = DebugInfoContext->getInliningInfoForAddress(
136         ModuleOffset, getDILineInfoSpecifier(Opts));
137   }
138   // Make sure there is at least one frame in context.
139   if (InlinedContext.getNumberOfFrames() == 0) {
140     InlinedContext.addFrame(DILineInfo());
141   }
142   // Override the function name in lower frame with name from symbol table.
143   if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
144     DIInliningInfo PatchedInlinedContext;
145     for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
146       DILineInfo LineInfo = InlinedContext.getFrame(i);
147       if (i == n - 1) {
148         std::string FunctionName;
149         uint64_t Start, Size;
150         if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
151                                    FunctionName, Start, Size)) {
152           LineInfo.FunctionName = FunctionName;
153         }
154       }
155       PatchedInlinedContext.addFrame(LineInfo);
156     }
157     InlinedContext = PatchedInlinedContext;
158   }
159   return InlinedContext;
160 }
161
162 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
163                                uint64_t &Start, uint64_t &Size) const {
164   return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
165                                 Size);
166 }
167
168 const char LLVMSymbolizer::kBadString[] = "??";
169
170 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
171                                           uint64_t ModuleOffset) {
172   ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
173   if (!Info)
174     return printDILineInfo(DILineInfo());
175   if (Opts.PrintInlining) {
176     DIInliningInfo InlinedContext =
177         Info->symbolizeInlinedCode(ModuleOffset, Opts);
178     uint32_t FramesNum = InlinedContext.getNumberOfFrames();
179     assert(FramesNum > 0);
180     std::string Result;
181     for (uint32_t i = 0; i < FramesNum; i++) {
182       DILineInfo LineInfo = InlinedContext.getFrame(i);
183       Result += printDILineInfo(LineInfo);
184     }
185     return Result;
186   }
187   DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
188   return printDILineInfo(LineInfo);
189 }
190
191 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
192                                           uint64_t ModuleOffset) {
193   std::string Name = kBadString;
194   uint64_t Start = 0;
195   uint64_t Size = 0;
196   if (Opts.UseSymbolTable) {
197     if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
198       if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
199         Name = DemangleName(Name);
200     }
201   }
202   std::stringstream ss;
203   ss << Name << "\n" << Start << " " << Size << "\n";
204   return ss.str();
205 }
206
207 void LLVMSymbolizer::flush() {
208   DeleteContainerSeconds(Modules);
209   BinaryForPath.clear();
210   ObjectFileForArch.clear();
211 }
212
213 static std::string getDarwinDWARFResourceForPath(const std::string &Path) {
214   StringRef Basename = sys::path::filename(Path);
215   const std::string &DSymDirectory = Path + ".dSYM";
216   SmallString<16> ResourceName = StringRef(DSymDirectory);
217   sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
218   sys::path::append(ResourceName, Basename);
219   return ResourceName.str();
220 }
221
222 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
223   std::unique_ptr<MemoryBuffer> MB;
224   if (MemoryBuffer::getFileOrSTDIN(Path, MB))
225     return false;
226   return !zlib::isAvailable() || CRCHash == zlib::crc32(MB->getBuffer());
227 }
228
229 static bool findDebugBinary(const std::string &OrigPath,
230                             const std::string &DebuglinkName, uint32_t CRCHash,
231                             std::string &Result) {
232   std::string OrigRealPath = OrigPath;
233 #if defined(HAVE_REALPATH)
234   if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
235     OrigRealPath = RP;
236     free(RP);
237   }
238 #endif
239   SmallString<16> OrigDir(OrigRealPath);
240   llvm::sys::path::remove_filename(OrigDir);
241   SmallString<16> DebugPath = OrigDir;
242   // Try /path/to/original_binary/debuglink_name
243   llvm::sys::path::append(DebugPath, DebuglinkName);
244   if (checkFileCRC(DebugPath, CRCHash)) {
245     Result = DebugPath.str();
246     return true;
247   }
248   // Try /path/to/original_binary/.debug/debuglink_name
249   DebugPath = OrigRealPath;
250   llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
251   if (checkFileCRC(DebugPath, CRCHash)) {
252     Result = DebugPath.str();
253     return true;
254   }
255   // Try /usr/lib/debug/path/to/original_binary/debuglink_name
256   DebugPath = "/usr/lib/debug";
257   llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
258                           DebuglinkName);
259   if (checkFileCRC(DebugPath, CRCHash)) {
260     Result = DebugPath.str();
261     return true;
262   }
263   return false;
264 }
265
266 static bool getGNUDebuglinkContents(const Binary *Bin, std::string &DebugName,
267                                     uint32_t &CRCHash) {
268   const ObjectFile *Obj = dyn_cast<ObjectFile>(Bin);
269   if (!Obj)
270     return false;
271   for (const SectionRef &Section : Obj->sections()) {
272     StringRef Name;
273     Section.getName(Name);
274     Name = Name.substr(Name.find_first_not_of("._"));
275     if (Name == "gnu_debuglink") {
276       StringRef Data;
277       Section.getContents(Data);
278       DataExtractor DE(Data, Obj->isLittleEndian(), 0);
279       uint32_t Offset = 0;
280       if (const char *DebugNameStr = DE.getCStr(&Offset)) {
281         // 4-byte align the offset.
282         Offset = (Offset + 3) & ~0x3;
283         if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
284           DebugName = DebugNameStr;
285           CRCHash = DE.getU32(&Offset);
286           return true;
287         }
288       }
289       break;
290     }
291   }
292   return false;
293 }
294
295 LLVMSymbolizer::BinaryPair
296 LLVMSymbolizer::getOrCreateBinary(const std::string &Path) {
297   BinaryMapTy::iterator I = BinaryForPath.find(Path);
298   if (I != BinaryForPath.end())
299     return I->second;
300   Binary *Bin = nullptr;
301   Binary *DbgBin = nullptr;
302   ErrorOr<Binary *> BinaryOrErr = createBinary(Path);
303   if (!error(BinaryOrErr.getError())) {
304     std::unique_ptr<Binary> ParsedBinary(BinaryOrErr.get());
305     // Check if it's a universal binary.
306     Bin = ParsedBinary.get();
307     ParsedBinariesAndObjects.push_back(std::move(ParsedBinary));
308     if (Bin->isMachO() || Bin->isMachOUniversalBinary()) {
309       // On Darwin we may find DWARF in separate object file in
310       // resource directory.
311       const std::string &ResourcePath =
312           getDarwinDWARFResourceForPath(Path);
313       BinaryOrErr = createBinary(ResourcePath);
314       error_code EC = BinaryOrErr.getError();
315       if (EC != std::errc::no_such_file_or_directory && !error(EC)) {
316         DbgBin = BinaryOrErr.get();
317         ParsedBinariesAndObjects.push_back(std::unique_ptr<Binary>(DbgBin));
318       }
319     }
320     // Try to locate the debug binary using .gnu_debuglink section.
321     if (!DbgBin) {
322       std::string DebuglinkName;
323       uint32_t CRCHash;
324       std::string DebugBinaryPath;
325       if (getGNUDebuglinkContents(Bin, DebuglinkName, CRCHash) &&
326           findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
327         BinaryOrErr = createBinary(DebugBinaryPath);
328         if (!error(BinaryOrErr.getError())) {
329           DbgBin = BinaryOrErr.get();
330           ParsedBinariesAndObjects.push_back(std::unique_ptr<Binary>(DbgBin));
331         }
332       }
333     }
334   }
335   if (!DbgBin)
336     DbgBin = Bin;
337   BinaryPair Res = std::make_pair(Bin, DbgBin);
338   BinaryForPath[Path] = Res;
339   return Res;
340 }
341
342 ObjectFile *
343 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin, const std::string &ArchName) {
344   if (!Bin)
345     return nullptr;
346   ObjectFile *Res = nullptr;
347   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
348     ObjectFileForArchMapTy::iterator I = ObjectFileForArch.find(
349         std::make_pair(UB, ArchName));
350     if (I != ObjectFileForArch.end())
351       return I->second;
352     std::unique_ptr<ObjectFile> ParsedObj;
353     if (!UB->getObjectForArch(Triple(ArchName).getArch(), ParsedObj)) {
354       Res = ParsedObj.get();
355       ParsedBinariesAndObjects.push_back(std::move(ParsedObj));
356     }
357     ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
358   } else if (Bin->isObject()) {
359     Res = cast<ObjectFile>(Bin);
360   }
361   return Res;
362 }
363
364 ModuleInfo *
365 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
366   ModuleMapTy::iterator I = Modules.find(ModuleName);
367   if (I != Modules.end())
368     return I->second;
369   std::string BinaryName = ModuleName;
370   std::string ArchName = Opts.DefaultArch;
371   size_t ColonPos = ModuleName.find_last_of(':');
372   // Verify that substring after colon form a valid arch name.
373   if (ColonPos != std::string::npos) {
374     std::string ArchStr = ModuleName.substr(ColonPos + 1);
375     if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
376       BinaryName = ModuleName.substr(0, ColonPos);
377       ArchName = ArchStr;
378     }
379   }
380   BinaryPair Binaries = getOrCreateBinary(BinaryName);
381   ObjectFile *Obj = getObjectFileFromBinary(Binaries.first, ArchName);
382   ObjectFile *DbgObj = getObjectFileFromBinary(Binaries.second, ArchName);
383
384   if (!Obj) {
385     // Failed to find valid object file.
386     Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
387     return nullptr;
388   }
389   DIContext *Context = DIContext::getDWARFContext(DbgObj);
390   assert(Context);
391   ModuleInfo *Info = new ModuleInfo(Obj, Context);
392   Modules.insert(make_pair(ModuleName, Info));
393   return Info;
394 }
395
396 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
397   // By default, DILineInfo contains "<invalid>" for function/filename it
398   // cannot fetch. We replace it to "??" to make our output closer to addr2line.
399   static const std::string kDILineInfoBadString = "<invalid>";
400   std::stringstream Result;
401   if (Opts.PrintFunctions != FunctionNameKind::None) {
402     std::string FunctionName = LineInfo.FunctionName;
403     if (FunctionName == kDILineInfoBadString)
404       FunctionName = kBadString;
405     else if (Opts.Demangle)
406       FunctionName = DemangleName(FunctionName);
407     Result << FunctionName << "\n";
408   }
409   std::string Filename = LineInfo.FileName;
410   if (Filename == kDILineInfoBadString)
411     Filename = kBadString;
412   Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
413   return Result.str();
414 }
415
416 #if !defined(_MSC_VER)
417 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
418 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
419                                 size_t *length, int *status);
420 #endif
421
422 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
423 #if !defined(_MSC_VER)
424   // We can spoil names of symbols with C linkage, so use an heuristic
425   // approach to check if the name should be demangled.
426   if (Name.substr(0, 2) != "_Z")
427     return Name;
428   int status = 0;
429   char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
430   if (status != 0)
431     return Name;
432   std::string Result = DemangledName;
433   free(DemangledName);
434   return Result;
435 #else
436   return Name;
437 #endif
438 }
439
440 } // namespace symbolize
441 } // namespace llvm