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