[llvm-symbolizer] Minor typedef cleanup. NFC.
[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/Errc.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/Path.h"
26 #include <sstream>
27 #include <stdlib.h>
28
29 namespace llvm {
30 namespace symbolize {
31
32 static bool error(std::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   auto &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 auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
97   if (SymbolMap.empty())
98     return false;
99   SymbolDesc SD = { Address, Address };
100   auto SymbolIterator = SymbolMap.upper_bound(SD);
101   if (SymbolIterator == SymbolMap.begin())
102     return false;
103   --SymbolIterator;
104   if (SymbolIterator->first.Size != 0 &&
105       SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
106     return false;
107   Name = SymbolIterator->second.str();
108   Addr = SymbolIterator->first.Addr;
109   Size = SymbolIterator->first.Size;
110   return true;
111 }
112
113 DILineInfo ModuleInfo::symbolizeCode(
114     uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
115   DILineInfo LineInfo;
116   if (DebugInfoContext) {
117     LineInfo = DebugInfoContext->getLineInfoForAddress(
118         ModuleOffset, getDILineInfoSpecifier(Opts));
119   }
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;
127     }
128   }
129   return LineInfo;
130 }
131
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));
138   }
139   // Make sure there is at least one frame in context.
140   if (InlinedContext.getNumberOfFrames() == 0) {
141     InlinedContext.addFrame(DILineInfo());
142   }
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);
148       if (i == n - 1) {
149         std::string FunctionName;
150         uint64_t Start, Size;
151         if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
152                                    FunctionName, Start, Size)) {
153           LineInfo.FunctionName = FunctionName;
154         }
155       }
156       PatchedInlinedContext.addFrame(LineInfo);
157     }
158     InlinedContext = PatchedInlinedContext;
159   }
160   return InlinedContext;
161 }
162
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,
166                                 Size);
167 }
168
169 const char LLVMSymbolizer::kBadString[] = "??";
170
171 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
172                                           uint64_t ModuleOffset) {
173   ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
174   if (!Info)
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);
181     std::string Result;
182     for (uint32_t i = 0; i < FramesNum; i++) {
183       DILineInfo LineInfo = InlinedContext.getFrame(i);
184       Result += printDILineInfo(LineInfo);
185     }
186     return Result;
187   }
188   DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
189   return printDILineInfo(LineInfo);
190 }
191
192 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
193                                           uint64_t ModuleOffset) {
194   std::string Name = kBadString;
195   uint64_t Start = 0;
196   uint64_t Size = 0;
197   if (Opts.UseSymbolTable) {
198     if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
199       if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
200         Name = DemangleName(Name);
201     }
202   }
203   std::stringstream ss;
204   ss << Name << "\n" << Start << " " << Size << "\n";
205   return ss.str();
206 }
207
208 void LLVMSymbolizer::flush() {
209   DeleteContainerSeconds(Modules);
210   BinaryForPath.clear();
211   ObjectFileForArch.clear();
212 }
213
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();
221 }
222
223 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
224   ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
225       MemoryBuffer::getFileOrSTDIN(Path);
226   if (!MB)
227     return false;
228   return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
229 }
230
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)) {
237     OrigRealPath = RP;
238     free(RP);
239   }
240 #endif
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();
248     return true;
249   }
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();
255     return true;
256   }
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),
260                           DebuglinkName);
261   if (checkFileCRC(DebugPath, CRCHash)) {
262     Result = DebugPath.str();
263     return true;
264   }
265   return false;
266 }
267
268 static bool getGNUDebuglinkContents(const Binary *Bin, std::string &DebugName,
269                                     uint32_t &CRCHash) {
270   const ObjectFile *Obj = dyn_cast<ObjectFile>(Bin);
271   if (!Obj)
272     return false;
273   for (const SectionRef &Section : Obj->sections()) {
274     StringRef Name;
275     Section.getName(Name);
276     Name = Name.substr(Name.find_first_not_of("._"));
277     if (Name == "gnu_debuglink") {
278       StringRef Data;
279       Section.getContents(Data);
280       DataExtractor DE(Data, Obj->isLittleEndian(), 0);
281       uint32_t Offset = 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);
288           return true;
289         }
290       }
291       break;
292     }
293   }
294   return false;
295 }
296
297 LLVMSymbolizer::BinaryPair
298 LLVMSymbolizer::getOrCreateBinary(const std::string &Path) {
299   const auto &I = BinaryForPath.find(Path);
300   if (I != BinaryForPath.end())
301     return I->second;
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));
321       }
322     }
323     // Try to locate the debug binary using .gnu_debuglink section.
324     if (!DbgBin) {
325       std::string DebuglinkName;
326       uint32_t CRCHash;
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));
335         }
336       }
337     }
338   }
339   if (!DbgBin)
340     DbgBin = Bin;
341   BinaryPair Res = std::make_pair(Bin, DbgBin);
342   BinaryForPath[Path] = Res;
343   return Res;
344 }
345
346 ObjectFile *
347 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin, const std::string &ArchName) {
348   if (!Bin)
349     return nullptr;
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())
355       return I->second;
356     ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
357         UB->getObjectForArch(Triple(ArchName).getArch());
358     if (ParsedObj) {
359       Res = ParsedObj.get().get();
360       ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
361     }
362     ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
363   } else if (Bin->isObject()) {
364     Res = cast<ObjectFile>(Bin);
365   }
366   return Res;
367 }
368
369 ModuleInfo *
370 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
371   const auto &I = Modules.find(ModuleName);
372   if (I != Modules.end())
373     return I->second;
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);
382       ArchName = ArchStr;
383     }
384   }
385   BinaryPair Binaries = getOrCreateBinary(BinaryName);
386   ObjectFile *Obj = getObjectFileFromBinary(Binaries.first, ArchName);
387   ObjectFile *DbgObj = getObjectFileFromBinary(Binaries.second, ArchName);
388
389   if (!Obj) {
390     // Failed to find valid object file.
391     Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
392     return nullptr;
393   }
394   DIContext *Context = DIContext::getDWARFContext(*DbgObj);
395   assert(Context);
396   ModuleInfo *Info = new ModuleInfo(Obj, Context);
397   Modules.insert(make_pair(ModuleName, Info));
398   return Info;
399 }
400
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";
413   }
414   std::string Filename = LineInfo.FileName;
415   if (Filename == kDILineInfoBadString)
416     Filename = kBadString;
417   Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
418   return Result.str();
419 }
420
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);
425 #endif
426
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")
432     return Name;
433   int status = 0;
434   char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
435   if (status != 0)
436     return Name;
437   std::string Result = DemangledName;
438   free(DemangledName);
439   return Result;
440 #else
441   return Name;
442 #endif
443 }
444
445 } // namespace symbolize
446 } // namespace llvm