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