Symbolize.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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/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/DebugInfo/Symbolize/DIFetcher.h"
  21. #include "llvm/Demangle/Demangle.h"
  22. #include "llvm/Object/COFF.h"
  23. #include "llvm/Object/MachO.h"
  24. #include "llvm/Object/MachOUniversal.h"
  25. #include "llvm/Support/CRC.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. namespace llvm {
  37. namespace symbolize {
  38. template <typename T>
  39. Expected<DILineInfo>
  40. LLVMSymbolizer::symbolizeCodeCommon(const T &ModuleSpecifier,
  41. object::SectionedAddress ModuleOffset) {
  42. auto InfoOrErr = getOrCreateModuleInfo(ModuleSpecifier);
  43. if (!InfoOrErr)
  44. return InfoOrErr.takeError();
  45. SymbolizableModule *Info = *InfoOrErr;
  46. // A null module means an error has already been reported. Return an empty
  47. // result.
  48. if (!Info)
  49. return DILineInfo();
  50. // If the user is giving us relative addresses, add the preferred base of the
  51. // object to the offset before we do the query. It's what DIContext expects.
  52. if (Opts.RelativeAddresses)
  53. ModuleOffset.Address += Info->getModulePreferredBase();
  54. DILineInfo LineInfo = Info->symbolizeCode(
  55. ModuleOffset, DILineInfoSpecifier(Opts.PathStyle, Opts.PrintFunctions),
  56. Opts.UseSymbolTable);
  57. if (Opts.Demangle)
  58. LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
  59. return LineInfo;
  60. }
  61. Expected<DILineInfo>
  62. LLVMSymbolizer::symbolizeCode(const ObjectFile &Obj,
  63. object::SectionedAddress ModuleOffset) {
  64. return symbolizeCodeCommon(Obj, ModuleOffset);
  65. }
  66. Expected<DILineInfo>
  67. LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
  68. object::SectionedAddress ModuleOffset) {
  69. return symbolizeCodeCommon(ModuleName, ModuleOffset);
  70. }
  71. template <typename T>
  72. Expected<DIInliningInfo> LLVMSymbolizer::symbolizeInlinedCodeCommon(
  73. const T &ModuleSpecifier, object::SectionedAddress ModuleOffset) {
  74. auto InfoOrErr = getOrCreateModuleInfo(ModuleSpecifier);
  75. if (!InfoOrErr)
  76. return InfoOrErr.takeError();
  77. SymbolizableModule *Info = *InfoOrErr;
  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, DILineInfoSpecifier(Opts.PathStyle, Opts.PrintFunctions),
  88. Opts.UseSymbolTable);
  89. if (Opts.Demangle) {
  90. for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
  91. auto *Frame = InlinedContext.getMutableFrame(i);
  92. Frame->FunctionName = DemangleName(Frame->FunctionName, Info);
  93. }
  94. }
  95. return InlinedContext;
  96. }
  97. Expected<DIInliningInfo>
  98. LLVMSymbolizer::symbolizeInlinedCode(const ObjectFile &Obj,
  99. object::SectionedAddress ModuleOffset) {
  100. return symbolizeInlinedCodeCommon(Obj, ModuleOffset);
  101. }
  102. Expected<DIInliningInfo>
  103. LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
  104. object::SectionedAddress ModuleOffset) {
  105. return symbolizeInlinedCodeCommon(ModuleName, ModuleOffset);
  106. }
  107. template <typename T>
  108. Expected<DIGlobal>
  109. LLVMSymbolizer::symbolizeDataCommon(const T &ModuleSpecifier,
  110. object::SectionedAddress ModuleOffset) {
  111. auto InfoOrErr = getOrCreateModuleInfo(ModuleSpecifier);
  112. if (!InfoOrErr)
  113. return InfoOrErr.takeError();
  114. SymbolizableModule *Info = *InfoOrErr;
  115. // A null module means an error has already been reported. Return an empty
  116. // result.
  117. if (!Info)
  118. return DIGlobal();
  119. // If the user is giving us relative addresses, add the preferred base of
  120. // the object to the offset before we do the query. It's what DIContext
  121. // expects.
  122. if (Opts.RelativeAddresses)
  123. ModuleOffset.Address += Info->getModulePreferredBase();
  124. DIGlobal Global = Info->symbolizeData(ModuleOffset);
  125. if (Opts.Demangle)
  126. Global.Name = DemangleName(Global.Name, Info);
  127. return Global;
  128. }
  129. Expected<DIGlobal>
  130. LLVMSymbolizer::symbolizeData(const ObjectFile &Obj,
  131. object::SectionedAddress ModuleOffset) {
  132. return symbolizeDataCommon(Obj, ModuleOffset);
  133. }
  134. Expected<DIGlobal>
  135. LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
  136. object::SectionedAddress ModuleOffset) {
  137. return symbolizeDataCommon(ModuleName, ModuleOffset);
  138. }
  139. template <typename T>
  140. Expected<std::vector<DILocal>>
  141. LLVMSymbolizer::symbolizeFrameCommon(const T &ModuleSpecifier,
  142. object::SectionedAddress ModuleOffset) {
  143. auto InfoOrErr = getOrCreateModuleInfo(ModuleSpecifier);
  144. if (!InfoOrErr)
  145. return InfoOrErr.takeError();
  146. SymbolizableModule *Info = *InfoOrErr;
  147. // A null module means an error has already been reported. Return an empty
  148. // result.
  149. if (!Info)
  150. return std::vector<DILocal>();
  151. // If the user is giving us relative addresses, add the preferred base of
  152. // the object to the offset before we do the query. It's what DIContext
  153. // expects.
  154. if (Opts.RelativeAddresses)
  155. ModuleOffset.Address += Info->getModulePreferredBase();
  156. return Info->symbolizeFrame(ModuleOffset);
  157. }
  158. Expected<std::vector<DILocal>>
  159. LLVMSymbolizer::symbolizeFrame(const ObjectFile &Obj,
  160. object::SectionedAddress ModuleOffset) {
  161. return symbolizeFrameCommon(Obj, ModuleOffset);
  162. }
  163. Expected<std::vector<DILocal>>
  164. LLVMSymbolizer::symbolizeFrame(const std::string &ModuleName,
  165. object::SectionedAddress ModuleOffset) {
  166. return symbolizeFrameCommon(ModuleName, ModuleOffset);
  167. }
  168. void LLVMSymbolizer::flush() {
  169. ObjectForUBPathAndArch.clear();
  170. BinaryForPath.clear();
  171. ObjectPairForPathArch.clear();
  172. Modules.clear();
  173. }
  174. namespace {
  175. // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
  176. // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
  177. // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
  178. // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
  179. std::string getDarwinDWARFResourceForPath(const std::string &Path,
  180. const std::string &Basename) {
  181. SmallString<16> ResourceName = StringRef(Path);
  182. if (sys::path::extension(Path) != ".dSYM") {
  183. ResourceName += ".dSYM";
  184. }
  185. sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
  186. sys::path::append(ResourceName, Basename);
  187. return std::string(ResourceName.str());
  188. }
  189. bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
  190. ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
  191. MemoryBuffer::getFileOrSTDIN(Path);
  192. if (!MB)
  193. return false;
  194. return CRCHash == llvm::crc32(arrayRefFromStringRef(MB.get()->getBuffer()));
  195. }
  196. bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
  197. uint32_t &CRCHash) {
  198. if (!Obj)
  199. return false;
  200. for (const SectionRef &Section : Obj->sections()) {
  201. StringRef Name;
  202. consumeError(Section.getName().moveInto(Name));
  203. Name = Name.substr(Name.find_first_not_of("._"));
  204. if (Name == "gnu_debuglink") {
  205. Expected<StringRef> ContentsOrErr = Section.getContents();
  206. if (!ContentsOrErr) {
  207. consumeError(ContentsOrErr.takeError());
  208. return false;
  209. }
  210. DataExtractor DE(*ContentsOrErr, Obj->isLittleEndian(), 0);
  211. uint64_t Offset = 0;
  212. if (const char *DebugNameStr = DE.getCStr(&Offset)) {
  213. // 4-byte align the offset.
  214. Offset = (Offset + 3) & ~0x3;
  215. if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
  216. DebugName = DebugNameStr;
  217. CRCHash = DE.getU32(&Offset);
  218. return true;
  219. }
  220. }
  221. break;
  222. }
  223. }
  224. return false;
  225. }
  226. bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
  227. const MachOObjectFile *Obj) {
  228. ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
  229. ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
  230. if (dbg_uuid.empty() || bin_uuid.empty())
  231. return false;
  232. return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
  233. }
  234. template <typename ELFT>
  235. Optional<ArrayRef<uint8_t>> getBuildID(const ELFFile<ELFT> &Obj) {
  236. auto PhdrsOrErr = Obj.program_headers();
  237. if (!PhdrsOrErr) {
  238. consumeError(PhdrsOrErr.takeError());
  239. return {};
  240. }
  241. for (const auto &P : *PhdrsOrErr) {
  242. if (P.p_type != ELF::PT_NOTE)
  243. continue;
  244. Error Err = Error::success();
  245. for (auto N : Obj.notes(P, Err))
  246. if (N.getType() == ELF::NT_GNU_BUILD_ID &&
  247. N.getName() == ELF::ELF_NOTE_GNU)
  248. return N.getDesc();
  249. consumeError(std::move(Err));
  250. }
  251. return {};
  252. }
  253. Optional<ArrayRef<uint8_t>> getBuildID(const ELFObjectFileBase *Obj) {
  254. Optional<ArrayRef<uint8_t>> BuildID;
  255. if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Obj))
  256. BuildID = getBuildID(O->getELFFile());
  257. else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Obj))
  258. BuildID = getBuildID(O->getELFFile());
  259. else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Obj))
  260. BuildID = getBuildID(O->getELFFile());
  261. else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Obj))
  262. BuildID = getBuildID(O->getELFFile());
  263. else
  264. llvm_unreachable("unsupported file format");
  265. return BuildID;
  266. }
  267. } // end anonymous namespace
  268. ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
  269. const MachOObjectFile *MachExeObj,
  270. const std::string &ArchName) {
  271. // On Darwin we may find DWARF in separate object file in
  272. // resource directory.
  273. std::vector<std::string> DsymPaths;
  274. StringRef Filename = sys::path::filename(ExePath);
  275. DsymPaths.push_back(
  276. getDarwinDWARFResourceForPath(ExePath, std::string(Filename)));
  277. for (const auto &Path : Opts.DsymHints) {
  278. DsymPaths.push_back(
  279. getDarwinDWARFResourceForPath(Path, std::string(Filename)));
  280. }
  281. for (const auto &Path : DsymPaths) {
  282. auto DbgObjOrErr = getOrCreateObject(Path, ArchName);
  283. if (!DbgObjOrErr) {
  284. // Ignore errors, the file might not exist.
  285. consumeError(DbgObjOrErr.takeError());
  286. continue;
  287. }
  288. ObjectFile *DbgObj = DbgObjOrErr.get();
  289. if (!DbgObj)
  290. continue;
  291. const MachOObjectFile *MachDbgObj = dyn_cast<const MachOObjectFile>(DbgObj);
  292. if (!MachDbgObj)
  293. continue;
  294. if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj))
  295. return DbgObj;
  296. }
  297. return nullptr;
  298. }
  299. ObjectFile *LLVMSymbolizer::lookUpDebuglinkObject(const std::string &Path,
  300. const ObjectFile *Obj,
  301. const std::string &ArchName) {
  302. std::string DebuglinkName;
  303. uint32_t CRCHash;
  304. std::string DebugBinaryPath;
  305. if (!getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash))
  306. return nullptr;
  307. if (!findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath))
  308. return nullptr;
  309. auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName);
  310. if (!DbgObjOrErr) {
  311. // Ignore errors, the file might not exist.
  312. consumeError(DbgObjOrErr.takeError());
  313. return nullptr;
  314. }
  315. return DbgObjOrErr.get();
  316. }
  317. ObjectFile *LLVMSymbolizer::lookUpBuildIDObject(const std::string &Path,
  318. const ELFObjectFileBase *Obj,
  319. const std::string &ArchName) {
  320. auto BuildID = getBuildID(Obj);
  321. if (!BuildID)
  322. return nullptr;
  323. if (BuildID->size() < 2)
  324. return nullptr;
  325. std::string DebugBinaryPath;
  326. if (!findDebugBinary(*BuildID, DebugBinaryPath))
  327. return nullptr;
  328. auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName);
  329. if (!DbgObjOrErr) {
  330. consumeError(DbgObjOrErr.takeError());
  331. return nullptr;
  332. }
  333. return DbgObjOrErr.get();
  334. }
  335. bool LLVMSymbolizer::findDebugBinary(const std::string &OrigPath,
  336. const std::string &DebuglinkName,
  337. uint32_t CRCHash, std::string &Result) {
  338. SmallString<16> OrigDir(OrigPath);
  339. llvm::sys::path::remove_filename(OrigDir);
  340. SmallString<16> DebugPath = OrigDir;
  341. // Try relative/path/to/original_binary/debuglink_name
  342. llvm::sys::path::append(DebugPath, DebuglinkName);
  343. if (checkFileCRC(DebugPath, CRCHash)) {
  344. Result = std::string(DebugPath.str());
  345. return true;
  346. }
  347. // Try relative/path/to/original_binary/.debug/debuglink_name
  348. DebugPath = OrigDir;
  349. llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
  350. if (checkFileCRC(DebugPath, CRCHash)) {
  351. Result = std::string(DebugPath.str());
  352. return true;
  353. }
  354. // Make the path absolute so that lookups will go to
  355. // "/usr/lib/debug/full/path/to/debug", not
  356. // "/usr/lib/debug/to/debug"
  357. llvm::sys::fs::make_absolute(OrigDir);
  358. if (!Opts.FallbackDebugPath.empty()) {
  359. // Try <FallbackDebugPath>/absolute/path/to/original_binary/debuglink_name
  360. DebugPath = Opts.FallbackDebugPath;
  361. } else {
  362. #if defined(__NetBSD__)
  363. // Try /usr/libdata/debug/absolute/path/to/original_binary/debuglink_name
  364. DebugPath = "/usr/libdata/debug";
  365. #else
  366. // Try /usr/lib/debug/absolute/path/to/original_binary/debuglink_name
  367. DebugPath = "/usr/lib/debug";
  368. #endif
  369. }
  370. llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
  371. DebuglinkName);
  372. if (checkFileCRC(DebugPath, CRCHash)) {
  373. Result = std::string(DebugPath.str());
  374. return true;
  375. }
  376. return false;
  377. }
  378. bool LLVMSymbolizer::findDebugBinary(const ArrayRef<uint8_t> BuildID,
  379. std::string &Result) {
  380. Optional<std::string> Path;
  381. Path = LocalDIFetcher(Opts.DebugFileDirectory).fetchBuildID(BuildID);
  382. if (Path) {
  383. Result = std::move(*Path);
  384. return true;
  385. }
  386. // Try caller-provided debug info fetchers.
  387. for (const std::unique_ptr<DIFetcher> &Fetcher : DIFetchers) {
  388. Path = Fetcher->fetchBuildID(BuildID);
  389. if (Path) {
  390. Result = std::move(*Path);
  391. return true;
  392. }
  393. }
  394. return false;
  395. }
  396. Expected<LLVMSymbolizer::ObjectPair>
  397. LLVMSymbolizer::getOrCreateObjectPair(const std::string &Path,
  398. const std::string &ArchName) {
  399. auto I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
  400. if (I != ObjectPairForPathArch.end())
  401. return I->second;
  402. auto ObjOrErr = getOrCreateObject(Path, ArchName);
  403. if (!ObjOrErr) {
  404. ObjectPairForPathArch.emplace(std::make_pair(Path, ArchName),
  405. ObjectPair(nullptr, nullptr));
  406. return ObjOrErr.takeError();
  407. }
  408. ObjectFile *Obj = ObjOrErr.get();
  409. assert(Obj != nullptr);
  410. ObjectFile *DbgObj = nullptr;
  411. if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
  412. DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
  413. else if (auto ELFObj = dyn_cast<const ELFObjectFileBase>(Obj))
  414. DbgObj = lookUpBuildIDObject(Path, ELFObj, ArchName);
  415. if (!DbgObj)
  416. DbgObj = lookUpDebuglinkObject(Path, Obj, ArchName);
  417. if (!DbgObj)
  418. DbgObj = Obj;
  419. ObjectPair Res = std::make_pair(Obj, DbgObj);
  420. ObjectPairForPathArch.emplace(std::make_pair(Path, ArchName), Res);
  421. return Res;
  422. }
  423. Expected<ObjectFile *>
  424. LLVMSymbolizer::getOrCreateObject(const std::string &Path,
  425. const std::string &ArchName) {
  426. Binary *Bin;
  427. auto Pair = BinaryForPath.emplace(Path, OwningBinary<Binary>());
  428. if (!Pair.second) {
  429. Bin = Pair.first->second.getBinary();
  430. } else {
  431. Expected<OwningBinary<Binary>> BinOrErr = createBinary(Path);
  432. if (!BinOrErr)
  433. return BinOrErr.takeError();
  434. Pair.first->second = std::move(BinOrErr.get());
  435. Bin = Pair.first->second.getBinary();
  436. }
  437. if (!Bin)
  438. return static_cast<ObjectFile *>(nullptr);
  439. if (MachOUniversalBinary *UB = dyn_cast_or_null<MachOUniversalBinary>(Bin)) {
  440. auto I = ObjectForUBPathAndArch.find(std::make_pair(Path, ArchName));
  441. if (I != ObjectForUBPathAndArch.end())
  442. return I->second.get();
  443. Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
  444. UB->getMachOObjectForArch(ArchName);
  445. if (!ObjOrErr) {
  446. ObjectForUBPathAndArch.emplace(std::make_pair(Path, ArchName),
  447. std::unique_ptr<ObjectFile>());
  448. return ObjOrErr.takeError();
  449. }
  450. ObjectFile *Res = ObjOrErr->get();
  451. ObjectForUBPathAndArch.emplace(std::make_pair(Path, ArchName),
  452. std::move(ObjOrErr.get()));
  453. return Res;
  454. }
  455. if (Bin->isObject()) {
  456. return cast<ObjectFile>(Bin);
  457. }
  458. return errorCodeToError(object_error::arch_not_found);
  459. }
  460. Expected<SymbolizableModule *>
  461. LLVMSymbolizer::createModuleInfo(const ObjectFile *Obj,
  462. std::unique_ptr<DIContext> Context,
  463. StringRef ModuleName) {
  464. auto InfoOrErr = SymbolizableObjectFile::create(Obj, std::move(Context),
  465. Opts.UntagAddresses);
  466. std::unique_ptr<SymbolizableModule> SymMod;
  467. if (InfoOrErr)
  468. SymMod = std::move(*InfoOrErr);
  469. auto InsertResult = Modules.insert(
  470. std::make_pair(std::string(ModuleName), std::move(SymMod)));
  471. assert(InsertResult.second);
  472. if (!InfoOrErr)
  473. return InfoOrErr.takeError();
  474. return InsertResult.first->second.get();
  475. }
  476. Expected<SymbolizableModule *>
  477. LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
  478. auto I = Modules.find(ModuleName);
  479. if (I != Modules.end())
  480. return I->second.get();
  481. std::string BinaryName = ModuleName;
  482. std::string ArchName = Opts.DefaultArch;
  483. size_t ColonPos = ModuleName.find_last_of(':');
  484. // Verify that substring after colon form a valid arch name.
  485. if (ColonPos != std::string::npos) {
  486. std::string ArchStr = ModuleName.substr(ColonPos + 1);
  487. if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
  488. BinaryName = ModuleName.substr(0, ColonPos);
  489. ArchName = ArchStr;
  490. }
  491. }
  492. auto ObjectsOrErr = getOrCreateObjectPair(BinaryName, ArchName);
  493. if (!ObjectsOrErr) {
  494. // Failed to find valid object file.
  495. Modules.emplace(ModuleName, std::unique_ptr<SymbolizableModule>());
  496. return ObjectsOrErr.takeError();
  497. }
  498. ObjectPair Objects = ObjectsOrErr.get();
  499. std::unique_ptr<DIContext> Context;
  500. // If this is a COFF object containing PDB info, use a PDBContext to
  501. // symbolize. Otherwise, use DWARF.
  502. if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
  503. const codeview::DebugInfo *DebugInfo;
  504. StringRef PDBFileName;
  505. auto EC = CoffObject->getDebugPDBInfo(DebugInfo, PDBFileName);
  506. if (!EC && DebugInfo != nullptr && !PDBFileName.empty()) {
  507. using namespace pdb;
  508. std::unique_ptr<IPDBSession> Session;
  509. PDB_ReaderType ReaderType =
  510. Opts.UseDIA ? PDB_ReaderType::DIA : PDB_ReaderType::Native;
  511. if (auto Err = loadDataForEXE(ReaderType, Objects.first->getFileName(),
  512. Session)) {
  513. Modules.emplace(ModuleName, std::unique_ptr<SymbolizableModule>());
  514. // Return along the PDB filename to provide more context
  515. return createFileError(PDBFileName, std::move(Err));
  516. }
  517. Context.reset(new PDBContext(*CoffObject, std::move(Session)));
  518. }
  519. }
  520. if (!Context)
  521. Context = DWARFContext::create(
  522. *Objects.second, DWARFContext::ProcessDebugRelocations::Process,
  523. nullptr, Opts.DWPName);
  524. return createModuleInfo(Objects.first, std::move(Context), ModuleName);
  525. }
  526. Expected<SymbolizableModule *>
  527. LLVMSymbolizer::getOrCreateModuleInfo(const ObjectFile &Obj) {
  528. StringRef ObjName = Obj.getFileName();
  529. auto I = Modules.find(ObjName);
  530. if (I != Modules.end())
  531. return I->second.get();
  532. std::unique_ptr<DIContext> Context = DWARFContext::create(Obj);
  533. // FIXME: handle COFF object with PDB info to use PDBContext
  534. return createModuleInfo(&Obj, std::move(Context), ObjName);
  535. }
  536. namespace {
  537. // Undo these various manglings for Win32 extern "C" functions:
  538. // cdecl - _foo
  539. // stdcall - _foo@12
  540. // fastcall - @foo@12
  541. // vectorcall - foo@@12
  542. // These are all different linkage names for 'foo'.
  543. StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
  544. // Remove any '_' or '@' prefix.
  545. char Front = SymbolName.empty() ? '\0' : SymbolName[0];
  546. if (Front == '_' || Front == '@')
  547. SymbolName = SymbolName.drop_front();
  548. // Remove any '@[0-9]+' suffix.
  549. if (Front != '?') {
  550. size_t AtPos = SymbolName.rfind('@');
  551. if (AtPos != StringRef::npos &&
  552. all_of(drop_begin(SymbolName, AtPos + 1), isDigit))
  553. SymbolName = SymbolName.substr(0, AtPos);
  554. }
  555. // Remove any ending '@' for vectorcall.
  556. if (SymbolName.endswith("@"))
  557. SymbolName = SymbolName.drop_back();
  558. return SymbolName;
  559. }
  560. } // end anonymous namespace
  561. std::string
  562. LLVMSymbolizer::DemangleName(const std::string &Name,
  563. const SymbolizableModule *DbiModuleDescriptor) {
  564. std::string Result;
  565. if (nonMicrosoftDemangle(Name.c_str(), Result))
  566. return Result;
  567. if (!Name.empty() && Name.front() == '?') {
  568. // Only do MSVC C++ demangling on symbols starting with '?'.
  569. int status = 0;
  570. char *DemangledName = microsoftDemangle(
  571. Name.c_str(), nullptr, nullptr, nullptr, &status,
  572. MSDemangleFlags(MSDF_NoAccessSpecifier | MSDF_NoCallingConvention |
  573. MSDF_NoMemberType | MSDF_NoReturnType));
  574. if (status != 0)
  575. return Name;
  576. Result = DemangledName;
  577. free(DemangledName);
  578. return Result;
  579. }
  580. if (DbiModuleDescriptor && DbiModuleDescriptor->isWin32Module())
  581. return std::string(demanglePE32ExternCFunc(Name));
  582. return Name;
  583. }
  584. } // namespace symbolize
  585. } // namespace llvm