Symbolize.cpp 18 KB

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