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