Return ErrorOr from SymbolRef::getName.
[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/DebugInfo/DWARF/DWARFContext.h"
18 #include "llvm/DebugInfo/PDB/PDB.h"
19 #include "llvm/DebugInfo/PDB/PDBContext.h"
20 #include "llvm/Object/ELFObjectFile.h"
21 #include "llvm/Object/MachO.h"
22 #include "llvm/Object/SymbolSize.h"
23 #include "llvm/Support/Casting.h"
24 #include "llvm/Support/Compression.h"
25 #include "llvm/Support/DataExtractor.h"
26 #include "llvm/Support/Errc.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/Path.h"
30 #include <sstream>
31 #include <stdlib.h>
32
33 #if defined(_MSC_VER)
34 #include <Windows.h>
35 #include <DbgHelp.h>
36 #pragma comment(lib, "dbghelp.lib")
37 #endif
38
39 namespace llvm {
40 namespace symbolize {
41
42 static bool error(std::error_code ec) {
43   if (!ec)
44     return false;
45   errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
46   return true;
47 }
48
49 static DILineInfoSpecifier
50 getDILineInfoSpecifier(const LLVMSymbolizer::Options &Opts) {
51   return DILineInfoSpecifier(
52       DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
53       Opts.PrintFunctions);
54 }
55
56 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
57     : Module(Obj), DebugInfoContext(DICtx) {
58   std::unique_ptr<DataExtractor> OpdExtractor;
59   uint64_t OpdAddress = 0;
60   // Find the .opd (function descriptor) section if any, for big-endian
61   // PowerPC64 ELF.
62   if (Module->getArch() == Triple::ppc64) {
63     for (section_iterator Section : Module->sections()) {
64       StringRef Name;
65       if (!error(Section->getName(Name)) && Name == ".opd") {
66         StringRef Data;
67         if (!error(Section->getContents(Data))) {
68           OpdExtractor.reset(new DataExtractor(Data, Module->isLittleEndian(),
69                                                Module->getBytesInAddress()));
70           OpdAddress = Section->getAddress();
71         }
72         break;
73       }
74     }
75   }
76   std::vector<std::pair<SymbolRef, uint64_t>> Symbols =
77       computeSymbolSizes(*Module);
78   for (auto &P : Symbols)
79     addSymbol(P.first, P.second, OpdExtractor.get(), OpdAddress);
80 }
81
82 void ModuleInfo::addSymbol(const SymbolRef &Symbol, uint64_t SymbolSize,
83                            DataExtractor *OpdExtractor, uint64_t OpdAddress) {
84   SymbolRef::Type SymbolType = Symbol.getType();
85   if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
86     return;
87   uint64_t SymbolAddress;
88   if (error(Symbol.getAddress(SymbolAddress)) ||
89       SymbolAddress == UnknownAddress)
90     return;
91   if (OpdExtractor) {
92     // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
93     // function descriptors. The first word of the descriptor is a pointer to
94     // the function's code.
95     // For the purposes of symbolization, pretend the symbol's address is that
96     // of the function's code, not the descriptor.
97     uint64_t OpdOffset = SymbolAddress - OpdAddress;
98     uint32_t OpdOffset32 = OpdOffset;
99     if (OpdOffset == OpdOffset32 && 
100         OpdExtractor->isValidOffsetForAddress(OpdOffset32))
101       SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
102   }
103   ErrorOr<StringRef> SymbolNameOrErr = Symbol.getName();
104   if (error(SymbolNameOrErr.getError()))
105     return;
106   StringRef SymbolName = *SymbolNameOrErr;
107   // Mach-O symbol table names have leading underscore, skip it.
108   if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
109     SymbolName = SymbolName.drop_front();
110   // FIXME: If a function has alias, there are two entries in symbol table
111   // with same address size. Make sure we choose the correct one.
112   auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
113   SymbolDesc SD = { SymbolAddress, SymbolSize };
114   M.insert(std::make_pair(SD, SymbolName));
115 }
116
117 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
118                                         std::string &Name, uint64_t &Addr,
119                                         uint64_t &Size) const {
120   const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
121   if (SymbolMap.empty())
122     return false;
123   SymbolDesc SD = { Address, Address };
124   auto SymbolIterator = SymbolMap.upper_bound(SD);
125   if (SymbolIterator == SymbolMap.begin())
126     return false;
127   --SymbolIterator;
128   if (SymbolIterator->first.Size != 0 &&
129       SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
130     return false;
131   Name = SymbolIterator->second.str();
132   Addr = SymbolIterator->first.Addr;
133   Size = SymbolIterator->first.Size;
134   return true;
135 }
136
137 DILineInfo ModuleInfo::symbolizeCode(
138     uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
139   DILineInfo LineInfo;
140   if (DebugInfoContext) {
141     LineInfo = DebugInfoContext->getLineInfoForAddress(
142         ModuleOffset, getDILineInfoSpecifier(Opts));
143   }
144   // Override function name from symbol table if necessary.
145   if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
146     std::string FunctionName;
147     uint64_t Start, Size;
148     if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
149                                FunctionName, Start, Size)) {
150       LineInfo.FunctionName = FunctionName;
151     }
152   }
153   return LineInfo;
154 }
155
156 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
157     uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
158   DIInliningInfo InlinedContext;
159
160   if (DebugInfoContext) {
161     InlinedContext = DebugInfoContext->getInliningInfoForAddress(
162         ModuleOffset, getDILineInfoSpecifier(Opts));
163   }
164   // Make sure there is at least one frame in context.
165   if (InlinedContext.getNumberOfFrames() == 0) {
166     InlinedContext.addFrame(DILineInfo());
167   }
168   // Override the function name in lower frame with name from symbol table.
169   if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
170     DIInliningInfo PatchedInlinedContext;
171     for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
172       DILineInfo LineInfo = InlinedContext.getFrame(i);
173       if (i == n - 1) {
174         std::string FunctionName;
175         uint64_t Start, Size;
176         if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
177                                    FunctionName, Start, Size)) {
178           LineInfo.FunctionName = FunctionName;
179         }
180       }
181       PatchedInlinedContext.addFrame(LineInfo);
182     }
183     InlinedContext = PatchedInlinedContext;
184   }
185   return InlinedContext;
186 }
187
188 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
189                                uint64_t &Start, uint64_t &Size) const {
190   return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
191                                 Size);
192 }
193
194 const char LLVMSymbolizer::kBadString[] = "??";
195
196 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
197                                           uint64_t ModuleOffset) {
198   ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
199   if (!Info)
200     return printDILineInfo(DILineInfo());
201   if (Opts.PrintInlining) {
202     DIInliningInfo InlinedContext =
203         Info->symbolizeInlinedCode(ModuleOffset, Opts);
204     uint32_t FramesNum = InlinedContext.getNumberOfFrames();
205     assert(FramesNum > 0);
206     std::string Result;
207     for (uint32_t i = 0; i < FramesNum; i++) {
208       DILineInfo LineInfo = InlinedContext.getFrame(i);
209       Result += printDILineInfo(LineInfo);
210     }
211     return Result;
212   }
213   DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
214   return printDILineInfo(LineInfo);
215 }
216
217 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
218                                           uint64_t ModuleOffset) {
219   std::string Name = kBadString;
220   uint64_t Start = 0;
221   uint64_t Size = 0;
222   if (Opts.UseSymbolTable) {
223     if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
224       if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
225         Name = DemangleName(Name);
226     }
227   }
228   std::stringstream ss;
229   ss << Name << "\n" << Start << " " << Size << "\n";
230   return ss.str();
231 }
232
233 void LLVMSymbolizer::flush() {
234   DeleteContainerSeconds(Modules);
235   ObjectPairForPathArch.clear();
236   ObjectFileForArch.clear();
237 }
238
239 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
240 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
241 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
242 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
243 static
244 std::string getDarwinDWARFResourceForPath(
245     const std::string &Path, const std::string &Basename) {
246   SmallString<16> ResourceName = StringRef(Path);
247   if (sys::path::extension(Path) != ".dSYM") {
248     ResourceName += ".dSYM";
249   }
250   sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
251   sys::path::append(ResourceName, Basename);
252   return ResourceName.str();
253 }
254
255 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
256   ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
257       MemoryBuffer::getFileOrSTDIN(Path);
258   if (!MB)
259     return false;
260   return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
261 }
262
263 static bool findDebugBinary(const std::string &OrigPath,
264                             const std::string &DebuglinkName, uint32_t CRCHash,
265                             std::string &Result) {
266   std::string OrigRealPath = OrigPath;
267 #if defined(HAVE_REALPATH)
268   if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
269     OrigRealPath = RP;
270     free(RP);
271   }
272 #endif
273   SmallString<16> OrigDir(OrigRealPath);
274   llvm::sys::path::remove_filename(OrigDir);
275   SmallString<16> DebugPath = OrigDir;
276   // Try /path/to/original_binary/debuglink_name
277   llvm::sys::path::append(DebugPath, DebuglinkName);
278   if (checkFileCRC(DebugPath, CRCHash)) {
279     Result = DebugPath.str();
280     return true;
281   }
282   // Try /path/to/original_binary/.debug/debuglink_name
283   DebugPath = OrigRealPath;
284   llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
285   if (checkFileCRC(DebugPath, CRCHash)) {
286     Result = DebugPath.str();
287     return true;
288   }
289   // Try /usr/lib/debug/path/to/original_binary/debuglink_name
290   DebugPath = "/usr/lib/debug";
291   llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
292                           DebuglinkName);
293   if (checkFileCRC(DebugPath, CRCHash)) {
294     Result = DebugPath.str();
295     return true;
296   }
297   return false;
298 }
299
300 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
301                                     uint32_t &CRCHash) {
302   if (!Obj)
303     return false;
304   for (const SectionRef &Section : Obj->sections()) {
305     StringRef Name;
306     Section.getName(Name);
307     Name = Name.substr(Name.find_first_not_of("._"));
308     if (Name == "gnu_debuglink") {
309       StringRef Data;
310       Section.getContents(Data);
311       DataExtractor DE(Data, Obj->isLittleEndian(), 0);
312       uint32_t Offset = 0;
313       if (const char *DebugNameStr = DE.getCStr(&Offset)) {
314         // 4-byte align the offset.
315         Offset = (Offset + 3) & ~0x3;
316         if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
317           DebugName = DebugNameStr;
318           CRCHash = DE.getU32(&Offset);
319           return true;
320         }
321       }
322       break;
323     }
324   }
325   return false;
326 }
327
328 static
329 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
330                              const MachOObjectFile *Obj) {
331   ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
332   ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
333   if (dbg_uuid.empty() || bin_uuid.empty())
334     return false;
335   return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
336 }
337
338 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
339     const MachOObjectFile *MachExeObj, const std::string &ArchName) {
340   // On Darwin we may find DWARF in separate object file in
341   // resource directory.
342   std::vector<std::string> DsymPaths;
343   StringRef Filename = sys::path::filename(ExePath);
344   DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
345   for (const auto &Path : Opts.DsymHints) {
346     DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
347   }
348   for (const auto &path : DsymPaths) {
349     ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
350     std::error_code EC = BinaryOrErr.getError();
351     if (EC != errc::no_such_file_or_directory && !error(EC)) {
352       OwningBinary<Binary> B = std::move(BinaryOrErr.get());
353       ObjectFile *DbgObj =
354           getObjectFileFromBinary(B.getBinary(), ArchName);
355       const MachOObjectFile *MachDbgObj =
356           dyn_cast<const MachOObjectFile>(DbgObj);
357       if (!MachDbgObj) continue;
358       if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
359         addOwningBinary(std::move(B));
360         return DbgObj; 
361       }
362     }
363   }
364   return nullptr;
365 }
366
367 LLVMSymbolizer::ObjectPair
368 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
369                                    const std::string &ArchName) {
370   const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
371   if (I != ObjectPairForPathArch.end())
372     return I->second;
373   ObjectFile *Obj = nullptr;
374   ObjectFile *DbgObj = nullptr;
375   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
376   if (!error(BinaryOrErr.getError())) {
377     OwningBinary<Binary> &B = BinaryOrErr.get();
378     Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
379     if (!Obj) {
380       ObjectPair Res = std::make_pair(nullptr, nullptr);
381       ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
382       return Res;
383     }
384     addOwningBinary(std::move(B));
385     if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
386       DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
387     // Try to locate the debug binary using .gnu_debuglink section.
388     if (!DbgObj) {
389       std::string DebuglinkName;
390       uint32_t CRCHash;
391       std::string DebugBinaryPath;
392       if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
393           findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
394         BinaryOrErr = createBinary(DebugBinaryPath);
395         if (!error(BinaryOrErr.getError())) {
396           OwningBinary<Binary> B = std::move(BinaryOrErr.get());
397           DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
398           addOwningBinary(std::move(B));
399         }
400       }
401     }
402   }
403   if (!DbgObj)
404     DbgObj = Obj;
405   ObjectPair Res = std::make_pair(Obj, DbgObj);
406   ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
407   return Res;
408 }
409
410 ObjectFile *
411 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
412                                         const std::string &ArchName) {
413   if (!Bin)
414     return nullptr;
415   ObjectFile *Res = nullptr;
416   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
417     const auto &I = ObjectFileForArch.find(
418         std::make_pair(UB, ArchName));
419     if (I != ObjectFileForArch.end())
420       return I->second;
421     ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
422         UB->getObjectForArch(ArchName);
423     if (ParsedObj) {
424       Res = ParsedObj.get().get();
425       ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
426     }
427     ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
428   } else if (Bin->isObject()) {
429     Res = cast<ObjectFile>(Bin);
430   }
431   return Res;
432 }
433
434 ModuleInfo *
435 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
436   const auto &I = Modules.find(ModuleName);
437   if (I != Modules.end())
438     return I->second;
439   std::string BinaryName = ModuleName;
440   std::string ArchName = Opts.DefaultArch;
441   size_t ColonPos = ModuleName.find_last_of(':');
442   // Verify that substring after colon form a valid arch name.
443   if (ColonPos != std::string::npos) {
444     std::string ArchStr = ModuleName.substr(ColonPos + 1);
445     if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
446       BinaryName = ModuleName.substr(0, ColonPos);
447       ArchName = ArchStr;
448     }
449   }
450   ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
451
452   if (!Objects.first) {
453     // Failed to find valid object file.
454     Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
455     return nullptr;
456   }
457   DIContext *Context = nullptr;
458   if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
459     // If this is a COFF object, assume it contains PDB debug information.  If
460     // we don't find any we will fall back to the DWARF case.
461     std::unique_ptr<IPDBSession> Session;
462     PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
463                                          Objects.first->getFileName(), Session);
464     if (Error == PDB_ErrorCode::Success) {
465       Context = new PDBContext(*CoffObject, std::move(Session),
466                                Opts.RelativeAddresses);
467     }
468   }
469   if (!Context)
470     Context = new DWARFContextInMemory(*Objects.second);
471   assert(Context);
472   ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
473   Modules.insert(make_pair(ModuleName, Info));
474   return Info;
475 }
476
477 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
478   // By default, DILineInfo contains "<invalid>" for function/filename it
479   // cannot fetch. We replace it to "??" to make our output closer to addr2line.
480   static const std::string kDILineInfoBadString = "<invalid>";
481   std::stringstream Result;
482   if (Opts.PrintFunctions != FunctionNameKind::None) {
483     std::string FunctionName = LineInfo.FunctionName;
484     if (FunctionName == kDILineInfoBadString)
485       FunctionName = kBadString;
486     else if (Opts.Demangle)
487       FunctionName = DemangleName(FunctionName);
488     Result << FunctionName << "\n";
489   }
490   std::string Filename = LineInfo.FileName;
491   if (Filename == kDILineInfoBadString)
492     Filename = kBadString;
493   Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
494   return Result.str();
495 }
496
497 #if !defined(_MSC_VER)
498 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
499 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
500                                 size_t *length, int *status);
501 #endif
502
503 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
504 #if !defined(_MSC_VER)
505   // We can spoil names of symbols with C linkage, so use an heuristic
506   // approach to check if the name should be demangled.
507   if (Name.substr(0, 2) != "_Z")
508     return Name;
509   int status = 0;
510   char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
511   if (status != 0)
512     return Name;
513   std::string Result = DemangledName;
514   free(DemangledName);
515   return Result;
516 #else
517   char DemangledName[1024] = {0};
518   DWORD result = ::UnDecorateSymbolName(
519       Name.c_str(), DemangledName, 1023,
520       UNDNAME_NO_ACCESS_SPECIFIERS |       // Strip public, private, protected
521           UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
522           UNDNAME_NO_THROW_SIGNATURES |    // Strip throw() specifications
523           UNDNAME_NO_MEMBER_TYPE |      // Strip virtual, static, etc specifiers
524           UNDNAME_NO_MS_KEYWORDS |      // Strip all MS extension keywords
525           UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
526
527   return (result == 0) ? Name : std::string(DemangledName);
528 #endif
529 }
530
531 } // namespace symbolize
532 } // namespace llvm