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