SymbolizableObjectFile.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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 "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. // Allow function and data symbols. Additionally allow STT_NONE, which are
  154. // common for functions defined in assembly.
  155. uint8_t Type = ELFSymbolRef(Symbol).getELFType();
  156. if (Type != ELF::STT_NOTYPE && Type != ELF::STT_FUNC &&
  157. Type != ELF::STT_OBJECT && Type != ELF::STT_GNU_IFUNC)
  158. return Error::success();
  159. // Some STT_NOTYPE symbols are not desired. This excludes STT_SECTION and
  160. // ARM mapping symbols.
  161. uint32_t Flags = cantFail(Symbol.getFlags());
  162. if (Flags & SymbolRef::SF_FormatSpecific)
  163. return Error::success();
  164. } else if (SymbolType != SymbolRef::ST_Function &&
  165. SymbolType != SymbolRef::ST_Data) {
  166. return Error::success();
  167. }
  168. Expected<uint64_t> SymbolAddressOrErr = Symbol.getAddress();
  169. if (!SymbolAddressOrErr)
  170. return SymbolAddressOrErr.takeError();
  171. uint64_t SymbolAddress = *SymbolAddressOrErr;
  172. if (UntagAddresses) {
  173. // For kernel addresses, bits 56-63 need to be set, so we sign extend bit 55
  174. // into bits 56-63 instead of masking them out.
  175. SymbolAddress &= (1ull << 56) - 1;
  176. SymbolAddress = (int64_t(SymbolAddress) << 8) >> 8;
  177. }
  178. if (OpdExtractor) {
  179. // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
  180. // function descriptors. The first word of the descriptor is a pointer to
  181. // the function's code.
  182. // For the purposes of symbolization, pretend the symbol's address is that
  183. // of the function's code, not the descriptor.
  184. uint64_t OpdOffset = SymbolAddress - OpdAddress;
  185. if (OpdExtractor->isValidOffsetForAddress(OpdOffset))
  186. SymbolAddress = OpdExtractor->getAddress(&OpdOffset);
  187. }
  188. // Mach-O symbol table names have leading underscore, skip it.
  189. if (Module->isMachO() && !SymbolName.empty() && SymbolName[0] == '_')
  190. SymbolName = SymbolName.drop_front();
  191. if (Obj.isELF() && ELFSymbolRef(Symbol).getBinding() != ELF::STB_LOCAL)
  192. ELFSymIdx = 0;
  193. Symbols.push_back({SymbolAddress, SymbolSize, SymbolName, ELFSymIdx});
  194. return Error::success();
  195. }
  196. // Return true if this is a 32-bit x86 PE COFF module.
  197. bool SymbolizableObjectFile::isWin32Module() const {
  198. auto *CoffObject = dyn_cast<COFFObjectFile>(Module);
  199. return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386;
  200. }
  201. uint64_t SymbolizableObjectFile::getModulePreferredBase() const {
  202. if (auto *CoffObject = dyn_cast<COFFObjectFile>(Module))
  203. return CoffObject->getImageBase();
  204. return 0;
  205. }
  206. bool SymbolizableObjectFile::getNameFromSymbolTable(
  207. uint64_t Address, std::string &Name, uint64_t &Addr, uint64_t &Size,
  208. std::string &FileName) const {
  209. SymbolDesc SD{Address, UINT64_C(-1), StringRef(), 0};
  210. auto SymbolIterator = llvm::upper_bound(Symbols, SD);
  211. if (SymbolIterator == Symbols.begin())
  212. return false;
  213. --SymbolIterator;
  214. if (SymbolIterator->Size != 0 &&
  215. SymbolIterator->Addr + SymbolIterator->Size <= Address)
  216. return false;
  217. Name = SymbolIterator->Name.str();
  218. Addr = SymbolIterator->Addr;
  219. Size = SymbolIterator->Size;
  220. if (SymbolIterator->ELFLocalSymIdx != 0) {
  221. // If this is an ELF local symbol, find the STT_FILE symbol preceding
  222. // SymbolIterator to get the filename. The ELF spec requires the STT_FILE
  223. // symbol (if present) precedes the other STB_LOCAL symbols for the file.
  224. assert(Module->isELF());
  225. auto It = llvm::upper_bound(
  226. FileSymbols,
  227. std::make_pair(SymbolIterator->ELFLocalSymIdx, StringRef()));
  228. if (It != FileSymbols.begin())
  229. FileName = It[-1].second.str();
  230. }
  231. return true;
  232. }
  233. bool SymbolizableObjectFile::shouldOverrideWithSymbolTable(
  234. FunctionNameKind FNKind, bool UseSymbolTable) const {
  235. // When DWARF is used with -gline-tables-only / -gmlt, the symbol table gives
  236. // better answers for linkage names than the DIContext. Otherwise, we are
  237. // probably using PEs and PDBs, and we shouldn't do the override. PE files
  238. // generally only contain the names of exported symbols.
  239. return FNKind == FunctionNameKind::LinkageName && UseSymbolTable &&
  240. isa<DWARFContext>(DebugInfoContext.get());
  241. }
  242. DILineInfo
  243. SymbolizableObjectFile::symbolizeCode(object::SectionedAddress ModuleOffset,
  244. DILineInfoSpecifier LineInfoSpecifier,
  245. bool UseSymbolTable) const {
  246. if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)
  247. ModuleOffset.SectionIndex =
  248. getModuleSectionIndexForAddress(ModuleOffset.Address);
  249. DILineInfo LineInfo =
  250. DebugInfoContext->getLineInfoForAddress(ModuleOffset, LineInfoSpecifier);
  251. // Override function name from symbol table if necessary.
  252. if (shouldOverrideWithSymbolTable(LineInfoSpecifier.FNKind, UseSymbolTable)) {
  253. std::string FunctionName, FileName;
  254. uint64_t Start, Size;
  255. if (getNameFromSymbolTable(ModuleOffset.Address, FunctionName, Start, Size,
  256. FileName)) {
  257. LineInfo.FunctionName = FunctionName;
  258. LineInfo.StartAddress = Start;
  259. if (LineInfo.FileName == DILineInfo::BadString && !FileName.empty())
  260. LineInfo.FileName = FileName;
  261. }
  262. }
  263. return LineInfo;
  264. }
  265. DIInliningInfo SymbolizableObjectFile::symbolizeInlinedCode(
  266. object::SectionedAddress ModuleOffset,
  267. DILineInfoSpecifier LineInfoSpecifier, bool UseSymbolTable) const {
  268. if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)
  269. ModuleOffset.SectionIndex =
  270. getModuleSectionIndexForAddress(ModuleOffset.Address);
  271. DIInliningInfo InlinedContext = DebugInfoContext->getInliningInfoForAddress(
  272. ModuleOffset, LineInfoSpecifier);
  273. // Make sure there is at least one frame in context.
  274. if (InlinedContext.getNumberOfFrames() == 0)
  275. InlinedContext.addFrame(DILineInfo());
  276. // Override the function name in lower frame with name from symbol table.
  277. if (shouldOverrideWithSymbolTable(LineInfoSpecifier.FNKind, UseSymbolTable)) {
  278. std::string FunctionName, FileName;
  279. uint64_t Start, Size;
  280. if (getNameFromSymbolTable(ModuleOffset.Address, FunctionName, Start, Size,
  281. FileName)) {
  282. DILineInfo *LI = InlinedContext.getMutableFrame(
  283. InlinedContext.getNumberOfFrames() - 1);
  284. LI->FunctionName = FunctionName;
  285. LI->StartAddress = Start;
  286. if (LI->FileName == DILineInfo::BadString && !FileName.empty())
  287. LI->FileName = FileName;
  288. }
  289. }
  290. return InlinedContext;
  291. }
  292. DIGlobal SymbolizableObjectFile::symbolizeData(
  293. object::SectionedAddress ModuleOffset) const {
  294. DIGlobal Res;
  295. std::string FileName;
  296. getNameFromSymbolTable(ModuleOffset.Address, Res.Name, Res.Start, Res.Size,
  297. FileName);
  298. return Res;
  299. }
  300. std::vector<DILocal> SymbolizableObjectFile::symbolizeFrame(
  301. object::SectionedAddress ModuleOffset) const {
  302. if (ModuleOffset.SectionIndex == object::SectionedAddress::UndefSection)
  303. ModuleOffset.SectionIndex =
  304. getModuleSectionIndexForAddress(ModuleOffset.Address);
  305. return DebugInfoContext->getLocalsForAddress(ModuleOffset);
  306. }
  307. /// Search for the first occurence of specified Address in ObjectFile.
  308. uint64_t SymbolizableObjectFile::getModuleSectionIndexForAddress(
  309. uint64_t Address) const {
  310. for (SectionRef Sec : Module->sections()) {
  311. if (!Sec.isText() || Sec.isVirtual())
  312. continue;
  313. if (Address >= Sec.getAddress() &&
  314. Address < Sec.getAddress() + Sec.getSize())
  315. return Sec.getIndex();
  316. }
  317. return object::SectionedAddress::UndefSection;
  318. }