SymbolizableObjectFile.cpp 12 KB

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