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