SymbolizableObjectFile.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. //===- SymbolizableObjectFile.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 of SymbolizableObjectFile class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/DebugInfo/Symbolize/SymbolizableObjectFile.h"
  13. #include "llvm/ADT/STLExtras.h"
  14. #include "llvm/ADT/Triple.h"
  15. #include "llvm/BinaryFormat/COFF.h"
  16. #include "llvm/DebugInfo/DWARF/DWARFContext.h"
  17. #include "llvm/Object/COFF.h"
  18. #include "llvm/Object/ELFObjectFile.h"
  19. #include "llvm/Object/ObjectFile.h"
  20. #include "llvm/Object/SymbolSize.h"
  21. #include "llvm/Support/Casting.h"
  22. #include "llvm/Support/DataExtractor.h"
  23. #include <algorithm>
  24. using namespace llvm;
  25. using namespace object;
  26. using namespace symbolize;
  27. Expected<std::unique_ptr<SymbolizableObjectFile>>
  28. SymbolizableObjectFile::create(const object::ObjectFile *Obj,
  29. std::unique_ptr<DIContext> DICtx,
  30. bool UntagAddresses) {
  31. assert(DICtx);
  32. std::unique_ptr<SymbolizableObjectFile> res(
  33. new SymbolizableObjectFile(Obj, std::move(DICtx), UntagAddresses));
  34. std::unique_ptr<DataExtractor> OpdExtractor;
  35. uint64_t OpdAddress = 0;
  36. // Find the .opd (function descriptor) section if any, for big-endian
  37. // PowerPC64 ELF.
  38. if (Obj->getArch() == Triple::ppc64) {
  39. for (section_iterator Section : Obj->sections()) {
  40. Expected<StringRef> NameOrErr = Section->getName();
  41. if (!NameOrErr)
  42. return NameOrErr.takeError();
  43. if (*NameOrErr == ".opd") {
  44. Expected<StringRef> E = Section->getContents();
  45. if (!E)
  46. return E.takeError();
  47. OpdExtractor.reset(new DataExtractor(*E, Obj->isLittleEndian(),
  48. Obj->getBytesInAddress()));
  49. OpdAddress = Section->getAddress();
  50. break;
  51. }
  52. }
  53. }
  54. std::vector<std::pair<SymbolRef, uint64_t>> Symbols =
  55. computeSymbolSizes(*Obj);
  56. for (auto &P : Symbols)
  57. if (Error E =
  58. res->addSymbol(P.first, P.second, OpdExtractor.get(), OpdAddress))
  59. return std::move(E);
  60. // If this is a COFF object and we didn't find any symbols, try the export
  61. // table.
  62. if (Symbols.empty()) {
  63. if (auto *CoffObj = dyn_cast<COFFObjectFile>(Obj))
  64. if (Error E = res->addCoffExportSymbols(CoffObj))
  65. return std::move(E);
  66. }
  67. std::vector<SymbolDesc> &SS = res->Symbols;
  68. // Sort by (Addr,Size,Name). If several SymbolDescs share the same Addr,
  69. // pick the one with the largest Size. This helps us avoid symbols with no
  70. // size information (Size=0).
  71. llvm::stable_sort(SS);
  72. auto I = SS.begin(), E = SS.end(), J = SS.begin();
  73. while (I != E) {
  74. auto OI = I;
  75. while (++I != E && OI->Addr == I->Addr) {
  76. }
  77. *J++ = I[-1];
  78. }
  79. SS.erase(J, SS.end());
  80. return std::move(res);
  81. }
  82. SymbolizableObjectFile::SymbolizableObjectFile(const ObjectFile *Obj,
  83. std::unique_ptr<DIContext> DICtx,
  84. bool UntagAddresses)
  85. : Module(Obj), DebugInfoContext(std::move(DICtx)),
  86. UntagAddresses(UntagAddresses) {}
  87. namespace {
  88. struct OffsetNamePair {
  89. uint32_t Offset;
  90. StringRef Name;
  91. bool operator<(const OffsetNamePair &R) const {
  92. return Offset < R.Offset;
  93. }
  94. };
  95. } // end anonymous namespace
  96. Error SymbolizableObjectFile::addCoffExportSymbols(
  97. const COFFObjectFile *CoffObj) {
  98. // Get all export names and offsets.
  99. std::vector<OffsetNamePair> ExportSyms;
  100. for (const ExportDirectoryEntryRef &Ref : CoffObj->export_directories()) {
  101. StringRef Name;
  102. uint32_t Offset;
  103. if (auto EC = Ref.getSymbolName(Name))
  104. return EC;
  105. if (auto EC = Ref.getExportRVA(Offset))
  106. return EC;
  107. ExportSyms.push_back(OffsetNamePair{Offset, Name});
  108. }
  109. if (ExportSyms.empty())
  110. return Error::success();
  111. // Sort by ascending offset.
  112. array_pod_sort(ExportSyms.begin(), ExportSyms.end());
  113. // Approximate the symbol sizes by assuming they run to the next symbol.
  114. // FIXME: This assumes all exports are functions.
  115. uint64_t ImageBase = CoffObj->getImageBase();
  116. for (auto I = ExportSyms.begin(), E = ExportSyms.end(); I != E; ++I) {
  117. OffsetNamePair &Export = *I;
  118. // FIXME: The last export has a one byte size now.
  119. uint32_t NextOffset = I != E ? I->Offset : Export.Offset + 1;
  120. uint64_t SymbolStart = ImageBase + Export.Offset;
  121. uint64_t SymbolSize = NextOffset - Export.Offset;
  122. Symbols.push_back({SymbolStart, SymbolSize, Export.Name, 0});
  123. }
  124. return Error::success();
  125. }
  126. Error SymbolizableObjectFile::addSymbol(const SymbolRef &Symbol,
  127. uint64_t SymbolSize,
  128. DataExtractor *OpdExtractor,
  129. uint64_t OpdAddress) {
  130. // Avoid adding symbols from an unknown/undefined section.
  131. const ObjectFile &Obj = *Symbol.getObject();
  132. Expected<StringRef> SymbolNameOrErr = Symbol.getName();
  133. if (!SymbolNameOrErr)
  134. return SymbolNameOrErr.takeError();
  135. StringRef SymbolName = *SymbolNameOrErr;
  136. uint32_t ELFSymIdx =
  137. Obj.isELF() ? ELFSymbolRef(Symbol).getRawDataRefImpl().d.b : 0;
  138. Expected<section_iterator> Sec = Symbol.getSection();
  139. if (!Sec || Obj.section_end() == *Sec) {
  140. if (Obj.isELF()) {
  141. // Store the (index, filename) pair for a file symbol.
  142. ELFSymbolRef ESym(Symbol);
  143. if (ESym.getELFType() == ELF::STT_FILE)
  144. FileSymbols.emplace_back(ELFSymIdx, SymbolName);
  145. }
  146. return Error::success();
  147. }
  148. Expected<SymbolRef::Type> SymbolTypeOrErr = Symbol.getType();
  149. if (!SymbolTypeOrErr)
  150. return SymbolTypeOrErr.takeError();
  151. SymbolRef::Type SymbolType = *SymbolTypeOrErr;
  152. if (Obj.isELF()) {
  153. // Ignore any symbols coming from sections that don't have runtime
  154. // allocated memory.
  155. if ((elf_section_iterator(*Sec)->getFlags() & ELF::SHF_ALLOC) == 0)
  156. return Error::success();
  157. // Allow function and data symbols. Additionally allow STT_NONE, which are
  158. // common for functions defined in assembly.
  159. uint8_t Type = ELFSymbolRef(Symbol).getELFType();
  160. if (Type != ELF::STT_NOTYPE && Type != ELF::STT_FUNC &&
  161. Type != ELF::STT_OBJECT && Type != ELF::STT_GNU_IFUNC)
  162. return Error::success();
  163. // Some STT_NOTYPE symbols are not desired. This excludes STT_SECTION and
  164. // ARM mapping symbols.
  165. uint32_t Flags = cantFail(Symbol.getFlags());
  166. if (Flags & SymbolRef::SF_FormatSpecific)
  167. return Error::success();
  168. } else if (SymbolType != SymbolRef::ST_Function &&
  169. SymbolType != SymbolRef::ST_Data) {
  170. return Error::success();
  171. }
  172. Expected<uint64_t> SymbolAddressOrErr = Symbol.getAddress();
  173. if (!SymbolAddressOrErr)
  174. return SymbolAddressOrErr.takeError();
  175. uint64_t SymbolAddress = *SymbolAddressOrErr;
  176. if (UntagAddresses) {
  177. // For kernel addresses, bits 56-63 need to be set, so we sign extend bit 55
  178. // into bits 56-63 instead of masking them out.
  179. SymbolAddress &= (1ull << 56) - 1;
  180. SymbolAddress = (int64_t(SymbolAddress) << 8) >> 8;
  181. }
  182. if (OpdExtractor) {
  183. // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
  184. // function descriptors. The first word of the descriptor is a pointer to
  185. // the function's code.
  186. // For the purposes of symbolization, pretend the symbol's address is that
  187. // of the function's code, not the descriptor.
  188. uint64_t OpdOffset = SymbolAddress - OpdAddress;
  189. if (OpdExtractor->isValidOffsetForAddress(OpdOffset))
  190. SymbolAddress = OpdExtractor->getAddress(&OpdOffset);
  191. }
  192. // Mach-O symbol table names have leading underscore, skip it.
  193. if (Module->isMachO() && !SymbolName.empty() && SymbolName[0] == '_')
  194. SymbolName = SymbolName.drop_front();
  195. if (Obj.isELF() && ELFSymbolRef(Symbol).getBinding() != ELF::STB_LOCAL)
  196. ELFSymIdx = 0;
  197. Symbols.push_back({SymbolAddress, SymbolSize, SymbolName, ELFSymIdx});
  198. return Error::success();
  199. }
  200. // Return true if this is a 32-bit x86 PE COFF module.
  201. bool SymbolizableObjectFile::isWin32Module() const {
  202. auto *CoffObject = dyn_cast<COFFObjectFile>(Module);
  203. return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386;
  204. }
  205. uint64_t SymbolizableObjectFile::getModulePreferredBase() const {
  206. if (auto *CoffObject = dyn_cast<COFFObjectFile>(Module))
  207. return CoffObject->getImageBase();
  208. return 0;
  209. }
  210. bool SymbolizableObjectFile::getNameFromSymbolTable(
  211. uint64_t Address, std::string &Name, uint64_t &Addr, uint64_t &Size,
  212. std::string &FileName) const {
  213. SymbolDesc SD{Address, UINT64_C(-1), StringRef(), 0};
  214. auto SymbolIterator = llvm::upper_bound(Symbols, SD);
  215. if (SymbolIterator == Symbols.begin())
  216. return false;
  217. --SymbolIterator;
  218. if (SymbolIterator->Size != 0 &&
  219. SymbolIterator->Addr + SymbolIterator->Size <= Address)
  220. return false;
  221. Name = SymbolIterator->Name.str();
  222. Addr = SymbolIterator->Addr;
  223. Size = SymbolIterator->Size;
  224. if (SymbolIterator->ELFLocalSymIdx != 0) {
  225. // If this is an ELF local symbol, find the STT_FILE symbol preceding
  226. // SymbolIterator to get the filename. The ELF spec requires the STT_FILE
  227. // symbol (if present) precedes the other STB_LOCAL symbols for the file.
  228. assert(Module->isELF());
  229. auto It = llvm::upper_bound(
  230. FileSymbols,
  231. std::make_pair(SymbolIterator->ELFLocalSymIdx, StringRef()));
  232. if (It != FileSymbols.begin())
  233. FileName = It[-1].second.str();
  234. }
  235. return true;
  236. }
  237. bool SymbolizableObjectFile::shouldOverrideWithSymbolTable(
  238. FunctionNameKind FNKind, bool UseSymbolTable) const {
  239. // When DWARF is used with -gline-tables-only / -gmlt, the symbol table gives
  240. // better answers for linkage names than the DIContext. Otherwise, we are
  241. // probably using PEs and PDBs, and we shouldn't do the override. PE files
  242. // generally only contain the names of exported symbols.
  243. return FNKind == FunctionNameKind::LinkageName && UseSymbolTable &&
  244. isa<DWARFContext>(DebugInfoContext.get());
  245. }
  246. DILineInfo
  247. SymbolizableObjectFile::symbolizeCode(object::SectionedAddress ModuleOffset,
  248. DILineInfoSpecifier LineInfoSpecifier,
  249. bool UseSymbolTable) const {
  250. if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)
  251. ModuleOffset.SectionIndex =
  252. getModuleSectionIndexForAddress(ModuleOffset.Address);
  253. DILineInfo LineInfo =
  254. DebugInfoContext->getLineInfoForAddress(ModuleOffset, LineInfoSpecifier);
  255. // Override function name from symbol table if necessary.
  256. if (shouldOverrideWithSymbolTable(LineInfoSpecifier.FNKind, UseSymbolTable)) {
  257. std::string FunctionName, FileName;
  258. uint64_t Start, Size;
  259. if (getNameFromSymbolTable(ModuleOffset.Address, FunctionName, Start, Size,
  260. FileName)) {
  261. LineInfo.FunctionName = FunctionName;
  262. LineInfo.StartAddress = Start;
  263. if (LineInfo.FileName == DILineInfo::BadString && !FileName.empty())
  264. LineInfo.FileName = FileName;
  265. }
  266. }
  267. return LineInfo;
  268. }
  269. DIInliningInfo SymbolizableObjectFile::symbolizeInlinedCode(
  270. object::SectionedAddress ModuleOffset,
  271. DILineInfoSpecifier LineInfoSpecifier, bool UseSymbolTable) const {
  272. if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)
  273. ModuleOffset.SectionIndex =
  274. getModuleSectionIndexForAddress(ModuleOffset.Address);
  275. DIInliningInfo InlinedContext = DebugInfoContext->getInliningInfoForAddress(
  276. ModuleOffset, LineInfoSpecifier);
  277. // Make sure there is at least one frame in context.
  278. if (InlinedContext.getNumberOfFrames() == 0)
  279. InlinedContext.addFrame(DILineInfo());
  280. // Override the function name in lower frame with name from symbol table.
  281. if (shouldOverrideWithSymbolTable(LineInfoSpecifier.FNKind, UseSymbolTable)) {
  282. std::string FunctionName, FileName;
  283. uint64_t Start, Size;
  284. if (getNameFromSymbolTable(ModuleOffset.Address, FunctionName, Start, Size,
  285. FileName)) {
  286. DILineInfo *LI = InlinedContext.getMutableFrame(
  287. InlinedContext.getNumberOfFrames() - 1);
  288. LI->FunctionName = FunctionName;
  289. LI->StartAddress = Start;
  290. if (LI->FileName == DILineInfo::BadString && !FileName.empty())
  291. LI->FileName = FileName;
  292. }
  293. }
  294. return InlinedContext;
  295. }
  296. DIGlobal SymbolizableObjectFile::symbolizeData(
  297. object::SectionedAddress ModuleOffset) const {
  298. DIGlobal Res;
  299. std::string FileName;
  300. getNameFromSymbolTable(ModuleOffset.Address, Res.Name, Res.Start, Res.Size,
  301. FileName);
  302. Res.DeclFile = FileName;
  303. // Try and get a better filename:lineno pair from the debuginfo, if present.
  304. DILineInfo DL = DebugInfoContext->getLineInfoForDataAddress(ModuleOffset);
  305. if (DL.Line != 0) {
  306. Res.DeclFile = DL.FileName;
  307. Res.DeclLine = DL.Line;
  308. }
  309. return Res;
  310. }
  311. std::vector<DILocal> SymbolizableObjectFile::symbolizeFrame(
  312. object::SectionedAddress ModuleOffset) const {
  313. if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)
  314. ModuleOffset.SectionIndex =
  315. getModuleSectionIndexForAddress(ModuleOffset.Address);
  316. return DebugInfoContext->getLocalsForAddress(ModuleOffset);
  317. }
  318. /// Search for the first occurence of specified Address in ObjectFile.
  319. uint64_t SymbolizableObjectFile::getModuleSectionIndexForAddress(
  320. uint64_t Address) const {
  321. for (SectionRef Sec : Module->sections()) {
  322. if (!Sec.isText() || Sec.isVirtual())
  323. continue;
  324. if (Address >= Sec.getAddress() &&
  325. Address < Sec.getAddress() + Sec.getSize())
  326. return Sec.getIndex();
  327. }
  328. return object::SectionedAddress::UndefSection;
  329. }