[Object] Modify OwningBinary's interface to separate inspection from ownership.
[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   ObjectPairForPathArch.clear();
211   ObjectFileForArch.clear();
212 }
213
214 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
215 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
216 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
217 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
218 static
219 std::string getDarwinDWARFResourceForPath(
220     const std::string &Path, const std::string &Basename) {
221   SmallString<16> ResourceName = StringRef(Path);
222   if (sys::path::extension(Path) != ".dSYM") {
223     ResourceName += ".dSYM";
224   }
225   sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
226   sys::path::append(ResourceName, Basename);
227   return ResourceName.str();
228 }
229
230 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
231   ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
232       MemoryBuffer::getFileOrSTDIN(Path);
233   if (!MB)
234     return false;
235   return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->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(), nullptr)) {
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 ObjectFile *Obj, std::string &DebugName,
276                                     uint32_t &CRCHash) {
277   if (!Obj)
278     return false;
279   for (const SectionRef &Section : Obj->sections()) {
280     StringRef Name;
281     Section.getName(Name);
282     Name = Name.substr(Name.find_first_not_of("._"));
283     if (Name == "gnu_debuglink") {
284       StringRef Data;
285       Section.getContents(Data);
286       DataExtractor DE(Data, Obj->isLittleEndian(), 0);
287       uint32_t Offset = 0;
288       if (const char *DebugNameStr = DE.getCStr(&Offset)) {
289         // 4-byte align the offset.
290         Offset = (Offset + 3) & ~0x3;
291         if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
292           DebugName = DebugNameStr;
293           CRCHash = DE.getU32(&Offset);
294           return true;
295         }
296       }
297       break;
298     }
299   }
300   return false;
301 }
302
303 static
304 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
305                              const MachOObjectFile *Obj) {
306   ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
307   ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
308   if (dbg_uuid.empty() || bin_uuid.empty())
309     return false;
310   return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
311 }
312
313 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
314     const MachOObjectFile *MachExeObj, const std::string &ArchName) {
315   // On Darwin we may find DWARF in separate object file in
316   // resource directory.
317   std::vector<std::string> DsymPaths;
318   StringRef Filename = sys::path::filename(ExePath);
319   DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
320   for (const auto &Path : Opts.DsymHints) {
321     DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
322   }
323   for (const auto &path : DsymPaths) {
324     ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
325     std::error_code EC = BinaryOrErr.getError();
326     if (EC != errc::no_such_file_or_directory && !error(EC)) {
327       OwningBinary<Binary> B = std::move(BinaryOrErr.get());
328       ObjectFile *DbgObj =
329           getObjectFileFromBinary(B.getBinary(), ArchName);
330       const MachOObjectFile *MachDbgObj =
331           dyn_cast<const MachOObjectFile>(DbgObj);
332       if (!MachDbgObj) continue;
333       if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
334         addOwningBinary(std::move(B));
335         return DbgObj; 
336       }
337     }
338   }
339   return nullptr;
340 }
341
342 LLVMSymbolizer::ObjectPair
343 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
344                                    const std::string &ArchName) {
345   const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
346   if (I != ObjectPairForPathArch.end())
347     return I->second;
348   ObjectFile *Obj = nullptr;
349   ObjectFile *DbgObj = nullptr;
350   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
351   if (!error(BinaryOrErr.getError())) {
352     OwningBinary<Binary> &B = BinaryOrErr.get();
353     Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
354     if (!Obj) {
355       ObjectPair Res = std::make_pair(nullptr, nullptr);
356       ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
357       return Res;
358     }
359     addOwningBinary(std::move(B));
360     if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
361       DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
362     // Try to locate the debug binary using .gnu_debuglink section.
363     if (!DbgObj) {
364       std::string DebuglinkName;
365       uint32_t CRCHash;
366       std::string DebugBinaryPath;
367       if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
368           findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
369         BinaryOrErr = createBinary(DebugBinaryPath);
370         if (!error(BinaryOrErr.getError())) {
371           OwningBinary<Binary> B = std::move(BinaryOrErr.get());
372           DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
373           addOwningBinary(std::move(B));
374         }
375       }
376     }
377   }
378   if (!DbgObj)
379     DbgObj = Obj;
380   ObjectPair Res = std::make_pair(Obj, DbgObj);
381   ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
382   return Res;
383 }
384
385 ObjectFile *
386 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
387                                         const std::string &ArchName) {
388   if (!Bin)
389     return nullptr;
390   ObjectFile *Res = nullptr;
391   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
392     const auto &I = ObjectFileForArch.find(
393         std::make_pair(UB, ArchName));
394     if (I != ObjectFileForArch.end())
395       return I->second;
396     ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
397         UB->getObjectForArch(Triple(ArchName).getArch());
398     if (ParsedObj) {
399       Res = ParsedObj.get().get();
400       ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
401     }
402     ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
403   } else if (Bin->isObject()) {
404     Res = cast<ObjectFile>(Bin);
405   }
406   return Res;
407 }
408
409 ModuleInfo *
410 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
411   const auto &I = Modules.find(ModuleName);
412   if (I != Modules.end())
413     return I->second;
414   std::string BinaryName = ModuleName;
415   std::string ArchName = Opts.DefaultArch;
416   size_t ColonPos = ModuleName.find_last_of(':');
417   // Verify that substring after colon form a valid arch name.
418   if (ColonPos != std::string::npos) {
419     std::string ArchStr = ModuleName.substr(ColonPos + 1);
420     if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
421       BinaryName = ModuleName.substr(0, ColonPos);
422       ArchName = ArchStr;
423     }
424   }
425   ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
426
427   if (!Objects.first) {
428     // Failed to find valid object file.
429     Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
430     return nullptr;
431   }
432   DIContext *Context = DIContext::getDWARFContext(*Objects.second);
433   assert(Context);
434   ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
435   Modules.insert(make_pair(ModuleName, Info));
436   return Info;
437 }
438
439 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
440   // By default, DILineInfo contains "<invalid>" for function/filename it
441   // cannot fetch. We replace it to "??" to make our output closer to addr2line.
442   static const std::string kDILineInfoBadString = "<invalid>";
443   std::stringstream Result;
444   if (Opts.PrintFunctions != FunctionNameKind::None) {
445     std::string FunctionName = LineInfo.FunctionName;
446     if (FunctionName == kDILineInfoBadString)
447       FunctionName = kBadString;
448     else if (Opts.Demangle)
449       FunctionName = DemangleName(FunctionName);
450     Result << FunctionName << "\n";
451   }
452   std::string Filename = LineInfo.FileName;
453   if (Filename == kDILineInfoBadString)
454     Filename = kBadString;
455   Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
456   return Result.str();
457 }
458
459 #if !defined(_MSC_VER)
460 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
461 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
462                                 size_t *length, int *status);
463 #endif
464
465 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
466 #if !defined(_MSC_VER)
467   // We can spoil names of symbols with C linkage, so use an heuristic
468   // approach to check if the name should be demangled.
469   if (Name.substr(0, 2) != "_Z")
470     return Name;
471   int status = 0;
472   char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
473   if (status != 0)
474     return Name;
475   std::string Result = DemangledName;
476   free(DemangledName);
477   return Result;
478 #else
479   return Name;
480 #endif
481 }
482
483 } // namespace symbolize
484 } // namespace llvm