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