fe180f26dc9b86a386352e71669b989fc9bef4eb
[oota-llvm.git] / lib / DebugInfo / Symbolize / Symbolize.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 "llvm/DebugInfo/Symbolize/Symbolize.h"
15
16 #include "SymbolizableObjectFile.h"
17
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
21 #include "llvm/DebugInfo/PDB/PDB.h"
22 #include "llvm/DebugInfo/PDB/PDBContext.h"
23 #include "llvm/Object/ELFObjectFile.h"
24 #include "llvm/Object/MachO.h"
25 #include "llvm/Support/COFF.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/Compression.h"
28 #include "llvm/Support/DataExtractor.h"
29 #include "llvm/Support/Errc.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Path.h"
33 #include <sstream>
34 #include <stdlib.h>
35
36 #if defined(_MSC_VER)
37 #include <Windows.h>
38 #include <DbgHelp.h>
39 #pragma comment(lib, "dbghelp.lib")
40
41 // Windows.h conflicts with our COFF header definitions.
42 #ifdef IMAGE_FILE_MACHINE_I386
43 #undef IMAGE_FILE_MACHINE_I386
44 #endif
45 #endif
46
47 namespace llvm {
48 namespace symbolize {
49
50 // FIXME: Move this to llvm-symbolizer tool.
51 static bool error(std::error_code ec) {
52   if (!ec)
53     return false;
54   errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
55   return true;
56 }
57
58
59 // By default, DILineInfo contains "<invalid>" for function/filename it
60 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
61 static const char kDILineInfoBadString[] = "<invalid>";
62
63 const char LLVMSymbolizer::kBadString[] = "??";
64
65 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
66                                           uint64_t ModuleOffset) {
67   SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName);
68   if (!Info)
69     return printDILineInfo(DILineInfo());
70
71   // If the user is giving us relative addresses, add the preferred base of the
72   // object to the offset before we do the query. It's what DIContext expects.
73   if (Opts.RelativeAddresses)
74     ModuleOffset += Info->getModulePreferredBase();
75
76   DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions,
77                                             Opts.UseSymbolTable);
78   if (Opts.Demangle)
79     LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
80   return printDILineInfo(LineInfo);
81 }
82
83 std::string LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
84                                                  uint64_t ModuleOffset) {
85   SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName);
86   if (!Info)
87     return printDIInliningInfo(DIInliningInfo());
88
89   // If the user is giving us relative addresses, add the preferred base of the
90   // object to the offset before we do the query. It's what DIContext expects.
91   if (Opts.RelativeAddresses)
92     ModuleOffset += Info->getModulePreferredBase();
93
94   DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
95       ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable);
96   if (Opts.Demangle) {
97     for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
98       auto *Frame = InlinedContext.getMutableFrame(i);
99       Frame->FunctionName = DemangleName(Frame->FunctionName, Info);
100     }
101   }
102   return printDIInliningInfo(InlinedContext);
103 }
104
105 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
106                                           uint64_t ModuleOffset) {
107   if (!Opts.UseSymbolTable)
108     return printDIGlobal(DIGlobal());
109   SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName);
110   if (!Info)
111     return printDIGlobal(DIGlobal());
112
113   // If the user is giving us relative addresses, add the preferred base of
114   // the object to the offset before we do the query. It's what DIContext
115   // expects.
116   if (Opts.RelativeAddresses)
117     ModuleOffset += Info->getModulePreferredBase();
118
119   DIGlobal Global = Info->symbolizeData(ModuleOffset);
120   if (Opts.Demangle)
121     Global.Name = DemangleName(Global.Name, Info);
122   return printDIGlobal(Global);
123 }
124
125 void LLVMSymbolizer::flush() {
126   Modules.clear();
127   ObjectPairForPathArch.clear();
128   ObjectFileForArch.clear();
129 }
130
131 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
132 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
133 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
134 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
135 static
136 std::string getDarwinDWARFResourceForPath(
137     const std::string &Path, const std::string &Basename) {
138   SmallString<16> ResourceName = StringRef(Path);
139   if (sys::path::extension(Path) != ".dSYM") {
140     ResourceName += ".dSYM";
141   }
142   sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
143   sys::path::append(ResourceName, Basename);
144   return ResourceName.str();
145 }
146
147 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
148   ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
149       MemoryBuffer::getFileOrSTDIN(Path);
150   if (!MB)
151     return false;
152   return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
153 }
154
155 static bool findDebugBinary(const std::string &OrigPath,
156                             const std::string &DebuglinkName, uint32_t CRCHash,
157                             std::string &Result) {
158   std::string OrigRealPath = OrigPath;
159 #if defined(HAVE_REALPATH)
160   if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
161     OrigRealPath = RP;
162     free(RP);
163   }
164 #endif
165   SmallString<16> OrigDir(OrigRealPath);
166   llvm::sys::path::remove_filename(OrigDir);
167   SmallString<16> DebugPath = OrigDir;
168   // Try /path/to/original_binary/debuglink_name
169   llvm::sys::path::append(DebugPath, DebuglinkName);
170   if (checkFileCRC(DebugPath, CRCHash)) {
171     Result = DebugPath.str();
172     return true;
173   }
174   // Try /path/to/original_binary/.debug/debuglink_name
175   DebugPath = OrigRealPath;
176   llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
177   if (checkFileCRC(DebugPath, CRCHash)) {
178     Result = DebugPath.str();
179     return true;
180   }
181   // Try /usr/lib/debug/path/to/original_binary/debuglink_name
182   DebugPath = "/usr/lib/debug";
183   llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
184                           DebuglinkName);
185   if (checkFileCRC(DebugPath, CRCHash)) {
186     Result = DebugPath.str();
187     return true;
188   }
189   return false;
190 }
191
192 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
193                                     uint32_t &CRCHash) {
194   if (!Obj)
195     return false;
196   for (const SectionRef &Section : Obj->sections()) {
197     StringRef Name;
198     Section.getName(Name);
199     Name = Name.substr(Name.find_first_not_of("._"));
200     if (Name == "gnu_debuglink") {
201       StringRef Data;
202       Section.getContents(Data);
203       DataExtractor DE(Data, Obj->isLittleEndian(), 0);
204       uint32_t Offset = 0;
205       if (const char *DebugNameStr = DE.getCStr(&Offset)) {
206         // 4-byte align the offset.
207         Offset = (Offset + 3) & ~0x3;
208         if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
209           DebugName = DebugNameStr;
210           CRCHash = DE.getU32(&Offset);
211           return true;
212         }
213       }
214       break;
215     }
216   }
217   return false;
218 }
219
220 static
221 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
222                              const MachOObjectFile *Obj) {
223   ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
224   ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
225   if (dbg_uuid.empty() || bin_uuid.empty())
226     return false;
227   return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
228 }
229
230 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
231     const MachOObjectFile *MachExeObj, const std::string &ArchName) {
232   // On Darwin we may find DWARF in separate object file in
233   // resource directory.
234   std::vector<std::string> DsymPaths;
235   StringRef Filename = sys::path::filename(ExePath);
236   DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
237   for (const auto &Path : Opts.DsymHints) {
238     DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
239   }
240   for (const auto &path : DsymPaths) {
241     ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
242     std::error_code EC = BinaryOrErr.getError();
243     if (EC != errc::no_such_file_or_directory && !error(EC)) {
244       OwningBinary<Binary> B = std::move(BinaryOrErr.get());
245       ObjectFile *DbgObj =
246           getObjectFileFromBinary(B.getBinary(), ArchName);
247       const MachOObjectFile *MachDbgObj =
248           dyn_cast<const MachOObjectFile>(DbgObj);
249       if (!MachDbgObj) continue;
250       if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
251         addOwningBinary(std::move(B));
252         return DbgObj; 
253       }
254     }
255   }
256   return nullptr;
257 }
258
259 LLVMSymbolizer::ObjectPair
260 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
261                                    const std::string &ArchName) {
262   const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
263   if (I != ObjectPairForPathArch.end())
264     return I->second;
265   ObjectFile *Obj = nullptr;
266   ObjectFile *DbgObj = nullptr;
267   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
268   if (!error(BinaryOrErr.getError())) {
269     OwningBinary<Binary> &B = BinaryOrErr.get();
270     Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
271     if (!Obj) {
272       ObjectPair Res = std::make_pair(nullptr, nullptr);
273       ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
274       return Res;
275     }
276     addOwningBinary(std::move(B));
277     if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
278       DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
279     // Try to locate the debug binary using .gnu_debuglink section.
280     if (!DbgObj) {
281       std::string DebuglinkName;
282       uint32_t CRCHash;
283       std::string DebugBinaryPath;
284       if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
285           findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
286         BinaryOrErr = createBinary(DebugBinaryPath);
287         if (!error(BinaryOrErr.getError())) {
288           OwningBinary<Binary> B = std::move(BinaryOrErr.get());
289           DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
290           addOwningBinary(std::move(B));
291         }
292       }
293     }
294   }
295   if (!DbgObj)
296     DbgObj = Obj;
297   ObjectPair Res = std::make_pair(Obj, DbgObj);
298   ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
299   return Res;
300 }
301
302 ObjectFile *
303 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
304                                         const std::string &ArchName) {
305   if (!Bin)
306     return nullptr;
307   ObjectFile *Res = nullptr;
308   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
309     const auto &I = ObjectFileForArch.find(
310         std::make_pair(UB, ArchName));
311     if (I != ObjectFileForArch.end())
312       return I->second;
313     ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
314         UB->getObjectForArch(ArchName);
315     if (ParsedObj) {
316       Res = ParsedObj.get().get();
317       ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
318     }
319     ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
320   } else if (Bin->isObject()) {
321     Res = cast<ObjectFile>(Bin);
322   }
323   return Res;
324 }
325
326 SymbolizableModule *
327 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
328   const auto &I = Modules.find(ModuleName);
329   if (I != Modules.end())
330     return I->second.get();
331   std::string BinaryName = ModuleName;
332   std::string ArchName = Opts.DefaultArch;
333   size_t ColonPos = ModuleName.find_last_of(':');
334   // Verify that substring after colon form a valid arch name.
335   if (ColonPos != std::string::npos) {
336     std::string ArchStr = ModuleName.substr(ColonPos + 1);
337     if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
338       BinaryName = ModuleName.substr(0, ColonPos);
339       ArchName = ArchStr;
340     }
341   }
342   ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
343
344   if (!Objects.first) {
345     // Failed to find valid object file.
346     Modules.insert(std::make_pair(ModuleName, nullptr));
347     return nullptr;
348   }
349   std::unique_ptr<DIContext> Context;
350   if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
351     // If this is a COFF object, assume it contains PDB debug information.  If
352     // we don't find any we will fall back to the DWARF case.
353     std::unique_ptr<IPDBSession> Session;
354     PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
355                                          Objects.first->getFileName(), Session);
356     if (Error == PDB_ErrorCode::Success) {
357       Context.reset(new PDBContext(*CoffObject, std::move(Session)));
358     }
359   }
360   if (!Context)
361     Context.reset(new DWARFContextInMemory(*Objects.second));
362   assert(Context);
363   auto ErrOrInfo =
364       SymbolizableObjectFile::create(Objects.first, std::move(Context));
365   if (error(ErrOrInfo.getError())) {
366     Modules.insert(std::make_pair(ModuleName, nullptr));
367     return nullptr;
368   }
369   SymbolizableModule *Res = ErrOrInfo.get().get();
370   Modules.insert(std::make_pair(ModuleName, std::move(ErrOrInfo.get())));
371   return Res;
372 }
373
374 std::string
375 LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
376   std::stringstream Result;
377   if (Opts.PrintFunctions != FunctionNameKind::None) {
378     std::string FunctionName = LineInfo.FunctionName;
379     if (FunctionName == kDILineInfoBadString)
380       FunctionName = kBadString;
381     Result << FunctionName << "\n";
382   }
383   std::string Filename = LineInfo.FileName;
384   if (Filename == kDILineInfoBadString)
385     Filename = kBadString;
386   Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
387   return Result.str();
388 }
389
390 std::string
391 LLVMSymbolizer::printDIInliningInfo(DIInliningInfo InlinedContext) const {
392   uint32_t FramesNum = InlinedContext.getNumberOfFrames();
393   if (FramesNum == 0)
394     return printDILineInfo(DILineInfo());
395   std::string Result;
396   for (uint32_t i = 0; i < FramesNum; i++) {
397     DILineInfo LineInfo = InlinedContext.getFrame(i);
398     Result += printDILineInfo(LineInfo);
399   }
400   return Result;
401 }
402
403 std::string
404 LLVMSymbolizer::printDIGlobal(DIGlobal Global) const {
405   std::stringstream Result;
406   std::string Name = Global.Name;
407   if (Name == kDILineInfoBadString)
408     Name = kBadString;
409   Result << Name << "\n";
410   Result << Global.Start << " " << Global.Size << "\n";
411   return Result.str();
412 }
413
414 // Undo these various manglings for Win32 extern "C" functions:
415 // cdecl       - _foo
416 // stdcall     - _foo@12
417 // fastcall    - @foo@12
418 // vectorcall  - foo@@12
419 // These are all different linkage names for 'foo'.
420 static StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
421   // Remove any '_' or '@' prefix.
422   char Front = SymbolName.empty() ? '\0' : SymbolName[0];
423   if (Front == '_' || Front == '@')
424     SymbolName = SymbolName.drop_front();
425
426   // Remove any '@[0-9]+' suffix.
427   if (Front != '?') {
428     size_t AtPos = SymbolName.rfind('@');
429     if (AtPos != StringRef::npos &&
430         std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
431                     [](char C) { return C >= '0' && C <= '9'; })) {
432       SymbolName = SymbolName.substr(0, AtPos);
433     }
434   }
435
436   // Remove any ending '@' for vectorcall.
437   if (SymbolName.endswith("@"))
438     SymbolName = SymbolName.drop_back();
439
440   return SymbolName;
441 }
442
443 #if !defined(_MSC_VER)
444 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
445 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
446                                 size_t *length, int *status);
447 #endif
448
449 std::string LLVMSymbolizer::DemangleName(const std::string &Name,
450                                          const SymbolizableModule *ModInfo) {
451 #if !defined(_MSC_VER)
452   // We can spoil names of symbols with C linkage, so use an heuristic
453   // approach to check if the name should be demangled.
454   if (Name.substr(0, 2) == "_Z") {
455     int status = 0;
456     char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
457     if (status != 0)
458       return Name;
459     std::string Result = DemangledName;
460     free(DemangledName);
461     return Result;
462   }
463 #else
464   if (!Name.empty() && Name.front() == '?') {
465     // Only do MSVC C++ demangling on symbols starting with '?'.
466     char DemangledName[1024] = {0};
467     DWORD result = ::UnDecorateSymbolName(
468         Name.c_str(), DemangledName, 1023,
469         UNDNAME_NO_ACCESS_SPECIFIERS |       // Strip public, private, protected
470             UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
471             UNDNAME_NO_THROW_SIGNATURES |    // Strip throw() specifications
472             UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
473             UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
474             UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
475     return (result == 0) ? Name : std::string(DemangledName);
476   }
477 #endif
478   if (ModInfo && ModInfo->isWin32Module())
479     return std::string(demanglePE32ExternCFunc(Name));
480   return Name;
481 }
482
483 } // namespace symbolize
484 } // namespace llvm