RuntimeDyld.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482
  1. //===-- RuntimeDyld.cpp - Run-time dynamic linker for MC-JIT ----*- C++ -*-===//
  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 the MC-JIT runtime dynamic linker.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ExecutionEngine/RuntimeDyld.h"
  13. #include "RuntimeDyldCOFF.h"
  14. #include "RuntimeDyldELF.h"
  15. #include "RuntimeDyldImpl.h"
  16. #include "RuntimeDyldMachO.h"
  17. #include "llvm/Object/COFF.h"
  18. #include "llvm/Object/ELFObjectFile.h"
  19. #include "llvm/Support/Alignment.h"
  20. #include "llvm/Support/MSVCErrorWorkarounds.h"
  21. #include "llvm/Support/ManagedStatic.h"
  22. #include "llvm/Support/MathExtras.h"
  23. #include <mutex>
  24. #include <future>
  25. using namespace llvm;
  26. using namespace llvm::object;
  27. #define DEBUG_TYPE "dyld"
  28. namespace {
  29. enum RuntimeDyldErrorCode {
  30. GenericRTDyldError = 1
  31. };
  32. // FIXME: This class is only here to support the transition to llvm::Error. It
  33. // will be removed once this transition is complete. Clients should prefer to
  34. // deal with the Error value directly, rather than converting to error_code.
  35. class RuntimeDyldErrorCategory : public std::error_category {
  36. public:
  37. const char *name() const noexcept override { return "runtimedyld"; }
  38. std::string message(int Condition) const override {
  39. switch (static_cast<RuntimeDyldErrorCode>(Condition)) {
  40. case GenericRTDyldError: return "Generic RuntimeDyld error";
  41. }
  42. llvm_unreachable("Unrecognized RuntimeDyldErrorCode");
  43. }
  44. };
  45. static ManagedStatic<RuntimeDyldErrorCategory> RTDyldErrorCategory;
  46. }
  47. char RuntimeDyldError::ID = 0;
  48. void RuntimeDyldError::log(raw_ostream &OS) const {
  49. OS << ErrMsg << "\n";
  50. }
  51. std::error_code RuntimeDyldError::convertToErrorCode() const {
  52. return std::error_code(GenericRTDyldError, *RTDyldErrorCategory);
  53. }
  54. // Empty out-of-line virtual destructor as the key function.
  55. RuntimeDyldImpl::~RuntimeDyldImpl() {}
  56. // Pin LoadedObjectInfo's vtables to this file.
  57. void RuntimeDyld::LoadedObjectInfo::anchor() {}
  58. namespace llvm {
  59. void RuntimeDyldImpl::registerEHFrames() {}
  60. void RuntimeDyldImpl::deregisterEHFrames() {
  61. MemMgr.deregisterEHFrames();
  62. }
  63. #ifndef NDEBUG
  64. static void dumpSectionMemory(const SectionEntry &S, StringRef State) {
  65. dbgs() << "----- Contents of section " << S.getName() << " " << State
  66. << " -----";
  67. if (S.getAddress() == nullptr) {
  68. dbgs() << "\n <section not emitted>\n";
  69. return;
  70. }
  71. const unsigned ColsPerRow = 16;
  72. uint8_t *DataAddr = S.getAddress();
  73. uint64_t LoadAddr = S.getLoadAddress();
  74. unsigned StartPadding = LoadAddr & (ColsPerRow - 1);
  75. unsigned BytesRemaining = S.getSize();
  76. if (StartPadding) {
  77. dbgs() << "\n" << format("0x%016" PRIx64,
  78. LoadAddr & ~(uint64_t)(ColsPerRow - 1)) << ":";
  79. while (StartPadding--)
  80. dbgs() << " ";
  81. }
  82. while (BytesRemaining > 0) {
  83. if ((LoadAddr & (ColsPerRow - 1)) == 0)
  84. dbgs() << "\n" << format("0x%016" PRIx64, LoadAddr) << ":";
  85. dbgs() << " " << format("%02x", *DataAddr);
  86. ++DataAddr;
  87. ++LoadAddr;
  88. --BytesRemaining;
  89. }
  90. dbgs() << "\n";
  91. }
  92. #endif
  93. // Resolve the relocations for all symbols we currently know about.
  94. void RuntimeDyldImpl::resolveRelocations() {
  95. std::lock_guard<sys::Mutex> locked(lock);
  96. // Print out the sections prior to relocation.
  97. LLVM_DEBUG({
  98. for (SectionEntry &S : Sections)
  99. dumpSectionMemory(S, "before relocations");
  100. });
  101. // First, resolve relocations associated with external symbols.
  102. if (auto Err = resolveExternalSymbols()) {
  103. HasError = true;
  104. ErrorStr = toString(std::move(Err));
  105. }
  106. resolveLocalRelocations();
  107. // Print out sections after relocation.
  108. LLVM_DEBUG({
  109. for (SectionEntry &S : Sections)
  110. dumpSectionMemory(S, "after relocations");
  111. });
  112. }
  113. void RuntimeDyldImpl::resolveLocalRelocations() {
  114. // Iterate over all outstanding relocations
  115. for (const auto &Rel : Relocations) {
  116. // The Section here (Sections[i]) refers to the section in which the
  117. // symbol for the relocation is located. The SectionID in the relocation
  118. // entry provides the section to which the relocation will be applied.
  119. unsigned Idx = Rel.first;
  120. uint64_t Addr = getSectionLoadAddress(Idx);
  121. LLVM_DEBUG(dbgs() << "Resolving relocations Section #" << Idx << "\t"
  122. << format("%p", (uintptr_t)Addr) << "\n");
  123. resolveRelocationList(Rel.second, Addr);
  124. }
  125. Relocations.clear();
  126. }
  127. void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
  128. uint64_t TargetAddress) {
  129. std::lock_guard<sys::Mutex> locked(lock);
  130. for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
  131. if (Sections[i].getAddress() == LocalAddress) {
  132. reassignSectionAddress(i, TargetAddress);
  133. return;
  134. }
  135. }
  136. llvm_unreachable("Attempting to remap address of unknown section!");
  137. }
  138. static Error getOffset(const SymbolRef &Sym, SectionRef Sec,
  139. uint64_t &Result) {
  140. Expected<uint64_t> AddressOrErr = Sym.getAddress();
  141. if (!AddressOrErr)
  142. return AddressOrErr.takeError();
  143. Result = *AddressOrErr - Sec.getAddress();
  144. return Error::success();
  145. }
  146. Expected<RuntimeDyldImpl::ObjSectionToIDMap>
  147. RuntimeDyldImpl::loadObjectImpl(const object::ObjectFile &Obj) {
  148. std::lock_guard<sys::Mutex> locked(lock);
  149. // Save information about our target
  150. Arch = (Triple::ArchType)Obj.getArch();
  151. IsTargetLittleEndian = Obj.isLittleEndian();
  152. setMipsABI(Obj);
  153. // Compute the memory size required to load all sections to be loaded
  154. // and pass this information to the memory manager
  155. if (MemMgr.needsToReserveAllocationSpace()) {
  156. uint64_t CodeSize = 0, RODataSize = 0, RWDataSize = 0;
  157. uint32_t CodeAlign = 1, RODataAlign = 1, RWDataAlign = 1;
  158. if (auto Err = computeTotalAllocSize(Obj,
  159. CodeSize, CodeAlign,
  160. RODataSize, RODataAlign,
  161. RWDataSize, RWDataAlign))
  162. return std::move(Err);
  163. MemMgr.reserveAllocationSpace(CodeSize, CodeAlign, RODataSize, RODataAlign,
  164. RWDataSize, RWDataAlign);
  165. }
  166. // Used sections from the object file
  167. ObjSectionToIDMap LocalSections;
  168. // Common symbols requiring allocation, with their sizes and alignments
  169. CommonSymbolList CommonSymbolsToAllocate;
  170. uint64_t CommonSize = 0;
  171. uint32_t CommonAlign = 0;
  172. // First, collect all weak and common symbols. We need to know if stronger
  173. // definitions occur elsewhere.
  174. JITSymbolResolver::LookupSet ResponsibilitySet;
  175. {
  176. JITSymbolResolver::LookupSet Symbols;
  177. for (auto &Sym : Obj.symbols()) {
  178. Expected<uint32_t> FlagsOrErr = Sym.getFlags();
  179. if (!FlagsOrErr)
  180. // TODO: Test this error.
  181. return FlagsOrErr.takeError();
  182. if ((*FlagsOrErr & SymbolRef::SF_Common) ||
  183. (*FlagsOrErr & SymbolRef::SF_Weak)) {
  184. // Get symbol name.
  185. if (auto NameOrErr = Sym.getName())
  186. Symbols.insert(*NameOrErr);
  187. else
  188. return NameOrErr.takeError();
  189. }
  190. }
  191. if (auto ResultOrErr = Resolver.getResponsibilitySet(Symbols))
  192. ResponsibilitySet = std::move(*ResultOrErr);
  193. else
  194. return ResultOrErr.takeError();
  195. }
  196. // Parse symbols
  197. LLVM_DEBUG(dbgs() << "Parse symbols:\n");
  198. for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
  199. ++I) {
  200. Expected<uint32_t> FlagsOrErr = I->getFlags();
  201. if (!FlagsOrErr)
  202. // TODO: Test this error.
  203. return FlagsOrErr.takeError();
  204. // Skip undefined symbols.
  205. if (*FlagsOrErr & SymbolRef::SF_Undefined)
  206. continue;
  207. // Get the symbol type.
  208. object::SymbolRef::Type SymType;
  209. if (auto SymTypeOrErr = I->getType())
  210. SymType = *SymTypeOrErr;
  211. else
  212. return SymTypeOrErr.takeError();
  213. // Get symbol name.
  214. StringRef Name;
  215. if (auto NameOrErr = I->getName())
  216. Name = *NameOrErr;
  217. else
  218. return NameOrErr.takeError();
  219. // Compute JIT symbol flags.
  220. auto JITSymFlags = getJITSymbolFlags(*I);
  221. if (!JITSymFlags)
  222. return JITSymFlags.takeError();
  223. // If this is a weak definition, check to see if there's a strong one.
  224. // If there is, skip this symbol (we won't be providing it: the strong
  225. // definition will). If there's no strong definition, make this definition
  226. // strong.
  227. if (JITSymFlags->isWeak() || JITSymFlags->isCommon()) {
  228. // First check whether there's already a definition in this instance.
  229. if (GlobalSymbolTable.count(Name))
  230. continue;
  231. // If we're not responsible for this symbol, skip it.
  232. if (!ResponsibilitySet.count(Name))
  233. continue;
  234. // Otherwise update the flags on the symbol to make this definition
  235. // strong.
  236. if (JITSymFlags->isWeak())
  237. *JITSymFlags &= ~JITSymbolFlags::Weak;
  238. if (JITSymFlags->isCommon()) {
  239. *JITSymFlags &= ~JITSymbolFlags::Common;
  240. uint32_t Align = I->getAlignment();
  241. uint64_t Size = I->getCommonSize();
  242. if (!CommonAlign)
  243. CommonAlign = Align;
  244. CommonSize = alignTo(CommonSize, Align) + Size;
  245. CommonSymbolsToAllocate.push_back(*I);
  246. }
  247. }
  248. if (*FlagsOrErr & SymbolRef::SF_Absolute &&
  249. SymType != object::SymbolRef::ST_File) {
  250. uint64_t Addr = 0;
  251. if (auto AddrOrErr = I->getAddress())
  252. Addr = *AddrOrErr;
  253. else
  254. return AddrOrErr.takeError();
  255. unsigned SectionID = AbsoluteSymbolSection;
  256. LLVM_DEBUG(dbgs() << "\tType: " << SymType << " (absolute) Name: " << Name
  257. << " SID: " << SectionID
  258. << " Offset: " << format("%p", (uintptr_t)Addr)
  259. << " flags: " << *FlagsOrErr << "\n");
  260. if (!Name.empty()) // Skip absolute symbol relocations.
  261. GlobalSymbolTable[Name] =
  262. SymbolTableEntry(SectionID, Addr, *JITSymFlags);
  263. } else if (SymType == object::SymbolRef::ST_Function ||
  264. SymType == object::SymbolRef::ST_Data ||
  265. SymType == object::SymbolRef::ST_Unknown ||
  266. SymType == object::SymbolRef::ST_Other) {
  267. section_iterator SI = Obj.section_end();
  268. if (auto SIOrErr = I->getSection())
  269. SI = *SIOrErr;
  270. else
  271. return SIOrErr.takeError();
  272. if (SI == Obj.section_end())
  273. continue;
  274. // Get symbol offset.
  275. uint64_t SectOffset;
  276. if (auto Err = getOffset(*I, *SI, SectOffset))
  277. return std::move(Err);
  278. bool IsCode = SI->isText();
  279. unsigned SectionID;
  280. if (auto SectionIDOrErr =
  281. findOrEmitSection(Obj, *SI, IsCode, LocalSections))
  282. SectionID = *SectionIDOrErr;
  283. else
  284. return SectionIDOrErr.takeError();
  285. LLVM_DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name
  286. << " SID: " << SectionID
  287. << " Offset: " << format("%p", (uintptr_t)SectOffset)
  288. << " flags: " << *FlagsOrErr << "\n");
  289. if (!Name.empty()) // Skip absolute symbol relocations
  290. GlobalSymbolTable[Name] =
  291. SymbolTableEntry(SectionID, SectOffset, *JITSymFlags);
  292. }
  293. }
  294. // Allocate common symbols
  295. if (auto Err = emitCommonSymbols(Obj, CommonSymbolsToAllocate, CommonSize,
  296. CommonAlign))
  297. return std::move(Err);
  298. // Parse and process relocations
  299. LLVM_DEBUG(dbgs() << "Parse relocations:\n");
  300. for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
  301. SI != SE; ++SI) {
  302. StubMap Stubs;
  303. Expected<section_iterator> RelSecOrErr = SI->getRelocatedSection();
  304. if (!RelSecOrErr)
  305. return RelSecOrErr.takeError();
  306. section_iterator RelocatedSection = *RelSecOrErr;
  307. if (RelocatedSection == SE)
  308. continue;
  309. relocation_iterator I = SI->relocation_begin();
  310. relocation_iterator E = SI->relocation_end();
  311. if (I == E && !ProcessAllSections)
  312. continue;
  313. bool IsCode = RelocatedSection->isText();
  314. unsigned SectionID = 0;
  315. if (auto SectionIDOrErr = findOrEmitSection(Obj, *RelocatedSection, IsCode,
  316. LocalSections))
  317. SectionID = *SectionIDOrErr;
  318. else
  319. return SectionIDOrErr.takeError();
  320. LLVM_DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
  321. for (; I != E;)
  322. if (auto IOrErr = processRelocationRef(SectionID, I, Obj, LocalSections, Stubs))
  323. I = *IOrErr;
  324. else
  325. return IOrErr.takeError();
  326. // If there is a NotifyStubEmitted callback set, call it to register any
  327. // stubs created for this section.
  328. if (NotifyStubEmitted) {
  329. StringRef FileName = Obj.getFileName();
  330. StringRef SectionName = Sections[SectionID].getName();
  331. for (auto &KV : Stubs) {
  332. auto &VR = KV.first;
  333. uint64_t StubAddr = KV.second;
  334. // If this is a named stub, just call NotifyStubEmitted.
  335. if (VR.SymbolName) {
  336. NotifyStubEmitted(FileName, SectionName, VR.SymbolName, SectionID,
  337. StubAddr);
  338. continue;
  339. }
  340. // Otherwise we will have to try a reverse lookup on the globla symbol table.
  341. for (auto &GSTMapEntry : GlobalSymbolTable) {
  342. StringRef SymbolName = GSTMapEntry.first();
  343. auto &GSTEntry = GSTMapEntry.second;
  344. if (GSTEntry.getSectionID() == VR.SectionID &&
  345. GSTEntry.getOffset() == VR.Offset) {
  346. NotifyStubEmitted(FileName, SectionName, SymbolName, SectionID,
  347. StubAddr);
  348. break;
  349. }
  350. }
  351. }
  352. }
  353. }
  354. // Process remaining sections
  355. if (ProcessAllSections) {
  356. LLVM_DEBUG(dbgs() << "Process remaining sections:\n");
  357. for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
  358. SI != SE; ++SI) {
  359. /* Ignore already loaded sections */
  360. if (LocalSections.find(*SI) != LocalSections.end())
  361. continue;
  362. bool IsCode = SI->isText();
  363. if (auto SectionIDOrErr =
  364. findOrEmitSection(Obj, *SI, IsCode, LocalSections))
  365. LLVM_DEBUG(dbgs() << "\tSectionID: " << (*SectionIDOrErr) << "\n");
  366. else
  367. return SectionIDOrErr.takeError();
  368. }
  369. }
  370. // Give the subclasses a chance to tie-up any loose ends.
  371. if (auto Err = finalizeLoad(Obj, LocalSections))
  372. return std::move(Err);
  373. // for (auto E : LocalSections)
  374. // llvm::dbgs() << "Added: " << E.first.getRawDataRefImpl() << " -> " << E.second << "\n";
  375. return LocalSections;
  376. }
  377. // A helper method for computeTotalAllocSize.
  378. // Computes the memory size required to allocate sections with the given sizes,
  379. // assuming that all sections are allocated with the given alignment
  380. static uint64_t
  381. computeAllocationSizeForSections(std::vector<uint64_t> &SectionSizes,
  382. uint64_t Alignment) {
  383. uint64_t TotalSize = 0;
  384. for (uint64_t SectionSize : SectionSizes) {
  385. uint64_t AlignedSize =
  386. (SectionSize + Alignment - 1) / Alignment * Alignment;
  387. TotalSize += AlignedSize;
  388. }
  389. return TotalSize;
  390. }
  391. static bool isRequiredForExecution(const SectionRef Section) {
  392. const ObjectFile *Obj = Section.getObject();
  393. if (isa<object::ELFObjectFileBase>(Obj))
  394. return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
  395. if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj)) {
  396. const coff_section *CoffSection = COFFObj->getCOFFSection(Section);
  397. // Avoid loading zero-sized COFF sections.
  398. // In PE files, VirtualSize gives the section size, and SizeOfRawData
  399. // may be zero for sections with content. In Obj files, SizeOfRawData
  400. // gives the section size, and VirtualSize is always zero. Hence
  401. // the need to check for both cases below.
  402. bool HasContent =
  403. (CoffSection->VirtualSize > 0) || (CoffSection->SizeOfRawData > 0);
  404. bool IsDiscardable =
  405. CoffSection->Characteristics &
  406. (COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_LNK_INFO);
  407. return HasContent && !IsDiscardable;
  408. }
  409. assert(isa<MachOObjectFile>(Obj));
  410. return true;
  411. }
  412. static bool isReadOnlyData(const SectionRef Section) {
  413. const ObjectFile *Obj = Section.getObject();
  414. if (isa<object::ELFObjectFileBase>(Obj))
  415. return !(ELFSectionRef(Section).getFlags() &
  416. (ELF::SHF_WRITE | ELF::SHF_EXECINSTR));
  417. if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
  418. return ((COFFObj->getCOFFSection(Section)->Characteristics &
  419. (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
  420. | COFF::IMAGE_SCN_MEM_READ
  421. | COFF::IMAGE_SCN_MEM_WRITE))
  422. ==
  423. (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
  424. | COFF::IMAGE_SCN_MEM_READ));
  425. assert(isa<MachOObjectFile>(Obj));
  426. return false;
  427. }
  428. static bool isZeroInit(const SectionRef Section) {
  429. const ObjectFile *Obj = Section.getObject();
  430. if (isa<object::ELFObjectFileBase>(Obj))
  431. return ELFSectionRef(Section).getType() == ELF::SHT_NOBITS;
  432. if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
  433. return COFFObj->getCOFFSection(Section)->Characteristics &
  434. COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
  435. auto *MachO = cast<MachOObjectFile>(Obj);
  436. unsigned SectionType = MachO->getSectionType(Section);
  437. return SectionType == MachO::S_ZEROFILL ||
  438. SectionType == MachO::S_GB_ZEROFILL;
  439. }
  440. static bool isTLS(const SectionRef Section) {
  441. const ObjectFile *Obj = Section.getObject();
  442. if (isa<object::ELFObjectFileBase>(Obj))
  443. return ELFSectionRef(Section).getFlags() & ELF::SHF_TLS;
  444. return false;
  445. }
  446. // Compute an upper bound of the memory size that is required to load all
  447. // sections
  448. Error RuntimeDyldImpl::computeTotalAllocSize(const ObjectFile &Obj,
  449. uint64_t &CodeSize,
  450. uint32_t &CodeAlign,
  451. uint64_t &RODataSize,
  452. uint32_t &RODataAlign,
  453. uint64_t &RWDataSize,
  454. uint32_t &RWDataAlign) {
  455. // Compute the size of all sections required for execution
  456. std::vector<uint64_t> CodeSectionSizes;
  457. std::vector<uint64_t> ROSectionSizes;
  458. std::vector<uint64_t> RWSectionSizes;
  459. // Collect sizes of all sections to be loaded;
  460. // also determine the max alignment of all sections
  461. for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
  462. SI != SE; ++SI) {
  463. const SectionRef &Section = *SI;
  464. bool IsRequired = isRequiredForExecution(Section) || ProcessAllSections;
  465. // Consider only the sections that are required to be loaded for execution
  466. if (IsRequired) {
  467. uint64_t DataSize = Section.getSize();
  468. uint64_t Alignment64 = Section.getAlignment();
  469. unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
  470. bool IsCode = Section.isText();
  471. bool IsReadOnly = isReadOnlyData(Section);
  472. bool IsTLS = isTLS(Section);
  473. Expected<StringRef> NameOrErr = Section.getName();
  474. if (!NameOrErr)
  475. return NameOrErr.takeError();
  476. StringRef Name = *NameOrErr;
  477. uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);
  478. uint64_t PaddingSize = 0;
  479. if (Name == ".eh_frame")
  480. PaddingSize += 4;
  481. if (StubBufSize != 0)
  482. PaddingSize += getStubAlignment() - 1;
  483. uint64_t SectionSize = DataSize + PaddingSize + StubBufSize;
  484. // The .eh_frame section (at least on Linux) needs an extra four bytes
  485. // padded
  486. // with zeroes added at the end. For MachO objects, this section has a
  487. // slightly different name, so this won't have any effect for MachO
  488. // objects.
  489. if (Name == ".eh_frame")
  490. SectionSize += 4;
  491. if (!SectionSize)
  492. SectionSize = 1;
  493. if (IsCode) {
  494. CodeAlign = std::max(CodeAlign, Alignment);
  495. CodeSectionSizes.push_back(SectionSize);
  496. } else if (IsReadOnly) {
  497. RODataAlign = std::max(RODataAlign, Alignment);
  498. ROSectionSizes.push_back(SectionSize);
  499. } else if (!IsTLS) {
  500. RWDataAlign = std::max(RWDataAlign, Alignment);
  501. RWSectionSizes.push_back(SectionSize);
  502. }
  503. }
  504. }
  505. // Compute Global Offset Table size. If it is not zero we
  506. // also update alignment, which is equal to a size of a
  507. // single GOT entry.
  508. if (unsigned GotSize = computeGOTSize(Obj)) {
  509. RWSectionSizes.push_back(GotSize);
  510. RWDataAlign = std::max<uint32_t>(RWDataAlign, getGOTEntrySize());
  511. }
  512. // Compute the size of all common symbols
  513. uint64_t CommonSize = 0;
  514. uint32_t CommonAlign = 1;
  515. for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
  516. ++I) {
  517. Expected<uint32_t> FlagsOrErr = I->getFlags();
  518. if (!FlagsOrErr)
  519. // TODO: Test this error.
  520. return FlagsOrErr.takeError();
  521. if (*FlagsOrErr & SymbolRef::SF_Common) {
  522. // Add the common symbols to a list. We'll allocate them all below.
  523. uint64_t Size = I->getCommonSize();
  524. uint32_t Align = I->getAlignment();
  525. // If this is the first common symbol, use its alignment as the alignment
  526. // for the common symbols section.
  527. if (CommonSize == 0)
  528. CommonAlign = Align;
  529. CommonSize = alignTo(CommonSize, Align) + Size;
  530. }
  531. }
  532. if (CommonSize != 0) {
  533. RWSectionSizes.push_back(CommonSize);
  534. RWDataAlign = std::max(RWDataAlign, CommonAlign);
  535. }
  536. // Compute the required allocation space for each different type of sections
  537. // (code, read-only data, read-write data) assuming that all sections are
  538. // allocated with the max alignment. Note that we cannot compute with the
  539. // individual alignments of the sections, because then the required size
  540. // depends on the order, in which the sections are allocated.
  541. CodeSize = computeAllocationSizeForSections(CodeSectionSizes, CodeAlign);
  542. RODataSize = computeAllocationSizeForSections(ROSectionSizes, RODataAlign);
  543. RWDataSize = computeAllocationSizeForSections(RWSectionSizes, RWDataAlign);
  544. return Error::success();
  545. }
  546. // compute GOT size
  547. unsigned RuntimeDyldImpl::computeGOTSize(const ObjectFile &Obj) {
  548. size_t GotEntrySize = getGOTEntrySize();
  549. if (!GotEntrySize)
  550. return 0;
  551. size_t GotSize = 0;
  552. for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
  553. SI != SE; ++SI) {
  554. for (const RelocationRef &Reloc : SI->relocations())
  555. if (relocationNeedsGot(Reloc))
  556. GotSize += GotEntrySize;
  557. }
  558. return GotSize;
  559. }
  560. // compute stub buffer size for the given section
  561. unsigned RuntimeDyldImpl::computeSectionStubBufSize(const ObjectFile &Obj,
  562. const SectionRef &Section) {
  563. if (!MemMgr.allowStubAllocation()) {
  564. return 0;
  565. }
  566. unsigned StubSize = getMaxStubSize();
  567. if (StubSize == 0) {
  568. return 0;
  569. }
  570. // FIXME: this is an inefficient way to handle this. We should computed the
  571. // necessary section allocation size in loadObject by walking all the sections
  572. // once.
  573. unsigned StubBufSize = 0;
  574. for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
  575. SI != SE; ++SI) {
  576. Expected<section_iterator> RelSecOrErr = SI->getRelocatedSection();
  577. if (!RelSecOrErr)
  578. report_fatal_error(Twine(toString(RelSecOrErr.takeError())));
  579. section_iterator RelSecI = *RelSecOrErr;
  580. if (!(RelSecI == Section))
  581. continue;
  582. for (const RelocationRef &Reloc : SI->relocations())
  583. if (relocationNeedsStub(Reloc))
  584. StubBufSize += StubSize;
  585. }
  586. // Get section data size and alignment
  587. uint64_t DataSize = Section.getSize();
  588. uint64_t Alignment64 = Section.getAlignment();
  589. // Add stubbuf size alignment
  590. unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
  591. unsigned StubAlignment = getStubAlignment();
  592. unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
  593. if (StubAlignment > EndAlignment)
  594. StubBufSize += StubAlignment - EndAlignment;
  595. return StubBufSize;
  596. }
  597. uint64_t RuntimeDyldImpl::readBytesUnaligned(uint8_t *Src,
  598. unsigned Size) const {
  599. uint64_t Result = 0;
  600. if (IsTargetLittleEndian) {
  601. Src += Size - 1;
  602. while (Size--)
  603. Result = (Result << 8) | *Src--;
  604. } else
  605. while (Size--)
  606. Result = (Result << 8) | *Src++;
  607. return Result;
  608. }
  609. void RuntimeDyldImpl::writeBytesUnaligned(uint64_t Value, uint8_t *Dst,
  610. unsigned Size) const {
  611. if (IsTargetLittleEndian) {
  612. while (Size--) {
  613. *Dst++ = Value & 0xFF;
  614. Value >>= 8;
  615. }
  616. } else {
  617. Dst += Size - 1;
  618. while (Size--) {
  619. *Dst-- = Value & 0xFF;
  620. Value >>= 8;
  621. }
  622. }
  623. }
  624. Expected<JITSymbolFlags>
  625. RuntimeDyldImpl::getJITSymbolFlags(const SymbolRef &SR) {
  626. return JITSymbolFlags::fromObjectSymbol(SR);
  627. }
  628. Error RuntimeDyldImpl::emitCommonSymbols(const ObjectFile &Obj,
  629. CommonSymbolList &SymbolsToAllocate,
  630. uint64_t CommonSize,
  631. uint32_t CommonAlign) {
  632. if (SymbolsToAllocate.empty())
  633. return Error::success();
  634. // Allocate memory for the section
  635. unsigned SectionID = Sections.size();
  636. uint8_t *Addr = MemMgr.allocateDataSection(CommonSize, CommonAlign, SectionID,
  637. "<common symbols>", false);
  638. if (!Addr)
  639. report_fatal_error("Unable to allocate memory for common symbols!");
  640. uint64_t Offset = 0;
  641. Sections.push_back(
  642. SectionEntry("<common symbols>", Addr, CommonSize, CommonSize, 0));
  643. memset(Addr, 0, CommonSize);
  644. LLVM_DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID
  645. << " new addr: " << format("%p", Addr)
  646. << " DataSize: " << CommonSize << "\n");
  647. // Assign the address of each symbol
  648. for (auto &Sym : SymbolsToAllocate) {
  649. uint32_t Alignment = Sym.getAlignment();
  650. uint64_t Size = Sym.getCommonSize();
  651. StringRef Name;
  652. if (auto NameOrErr = Sym.getName())
  653. Name = *NameOrErr;
  654. else
  655. return NameOrErr.takeError();
  656. if (Alignment) {
  657. // This symbol has an alignment requirement.
  658. uint64_t AlignOffset =
  659. offsetToAlignment((uint64_t)Addr, Align(Alignment));
  660. Addr += AlignOffset;
  661. Offset += AlignOffset;
  662. }
  663. auto JITSymFlags = getJITSymbolFlags(Sym);
  664. if (!JITSymFlags)
  665. return JITSymFlags.takeError();
  666. LLVM_DEBUG(dbgs() << "Allocating common symbol " << Name << " address "
  667. << format("%p", Addr) << "\n");
  668. if (!Name.empty()) // Skip absolute symbol relocations.
  669. GlobalSymbolTable[Name] =
  670. SymbolTableEntry(SectionID, Offset, std::move(*JITSymFlags));
  671. Offset += Size;
  672. Addr += Size;
  673. }
  674. return Error::success();
  675. }
  676. Expected<unsigned>
  677. RuntimeDyldImpl::emitSection(const ObjectFile &Obj,
  678. const SectionRef &Section,
  679. bool IsCode) {
  680. StringRef data;
  681. uint64_t Alignment64 = Section.getAlignment();
  682. unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
  683. unsigned PaddingSize = 0;
  684. unsigned StubBufSize = 0;
  685. bool IsRequired = isRequiredForExecution(Section);
  686. bool IsVirtual = Section.isVirtual();
  687. bool IsZeroInit = isZeroInit(Section);
  688. bool IsReadOnly = isReadOnlyData(Section);
  689. bool IsTLS = isTLS(Section);
  690. uint64_t DataSize = Section.getSize();
  691. // An alignment of 0 (at least with ELF) is identical to an alignment of 1,
  692. // while being more "polite". Other formats do not support 0-aligned sections
  693. // anyway, so we should guarantee that the alignment is always at least 1.
  694. Alignment = std::max(1u, Alignment);
  695. Expected<StringRef> NameOrErr = Section.getName();
  696. if (!NameOrErr)
  697. return NameOrErr.takeError();
  698. StringRef Name = *NameOrErr;
  699. StubBufSize = computeSectionStubBufSize(Obj, Section);
  700. // The .eh_frame section (at least on Linux) needs an extra four bytes padded
  701. // with zeroes added at the end. For MachO objects, this section has a
  702. // slightly different name, so this won't have any effect for MachO objects.
  703. if (Name == ".eh_frame")
  704. PaddingSize = 4;
  705. uintptr_t Allocate;
  706. unsigned SectionID = Sections.size();
  707. uint8_t *Addr;
  708. uint64_t LoadAddress = 0;
  709. const char *pData = nullptr;
  710. // If this section contains any bits (i.e. isn't a virtual or bss section),
  711. // grab a reference to them.
  712. if (!IsVirtual && !IsZeroInit) {
  713. // In either case, set the location of the unrelocated section in memory,
  714. // since we still process relocations for it even if we're not applying them.
  715. if (Expected<StringRef> E = Section.getContents())
  716. data = *E;
  717. else
  718. return E.takeError();
  719. pData = data.data();
  720. }
  721. // If there are any stubs then the section alignment needs to be at least as
  722. // high as stub alignment or padding calculations may by incorrect when the
  723. // section is remapped.
  724. if (StubBufSize != 0) {
  725. Alignment = std::max(Alignment, getStubAlignment());
  726. PaddingSize += getStubAlignment() - 1;
  727. }
  728. // Some sections, such as debug info, don't need to be loaded for execution.
  729. // Process those only if explicitly requested.
  730. if (IsRequired || ProcessAllSections) {
  731. Allocate = DataSize + PaddingSize + StubBufSize;
  732. if (!Allocate)
  733. Allocate = 1;
  734. if (IsTLS) {
  735. auto TLSSection =
  736. MemMgr.allocateTLSSection(Allocate, Alignment, SectionID, Name);
  737. Addr = TLSSection.InitializationImage;
  738. LoadAddress = TLSSection.Offset;
  739. } else if (IsCode) {
  740. Addr = MemMgr.allocateCodeSection(Allocate, Alignment, SectionID, Name);
  741. } else {
  742. Addr = MemMgr.allocateDataSection(Allocate, Alignment, SectionID, Name,
  743. IsReadOnly);
  744. }
  745. if (!Addr)
  746. report_fatal_error("Unable to allocate section memory!");
  747. // Zero-initialize or copy the data from the image
  748. if (IsZeroInit || IsVirtual)
  749. memset(Addr, 0, DataSize);
  750. else
  751. memcpy(Addr, pData, DataSize);
  752. // Fill in any extra bytes we allocated for padding
  753. if (PaddingSize != 0) {
  754. memset(Addr + DataSize, 0, PaddingSize);
  755. // Update the DataSize variable to include padding.
  756. DataSize += PaddingSize;
  757. // Align DataSize to stub alignment if we have any stubs (PaddingSize will
  758. // have been increased above to account for this).
  759. if (StubBufSize > 0)
  760. DataSize &= -(uint64_t)getStubAlignment();
  761. }
  762. LLVM_DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: "
  763. << Name << " obj addr: " << format("%p", pData)
  764. << " new addr: " << format("%p", Addr) << " DataSize: "
  765. << DataSize << " StubBufSize: " << StubBufSize
  766. << " Allocate: " << Allocate << "\n");
  767. } else {
  768. // Even if we didn't load the section, we need to record an entry for it
  769. // to handle later processing (and by 'handle' I mean don't do anything
  770. // with these sections).
  771. Allocate = 0;
  772. Addr = nullptr;
  773. LLVM_DEBUG(
  774. dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
  775. << " obj addr: " << format("%p", data.data()) << " new addr: 0"
  776. << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
  777. << " Allocate: " << Allocate << "\n");
  778. }
  779. Sections.push_back(
  780. SectionEntry(Name, Addr, DataSize, Allocate, (uintptr_t)pData));
  781. // The load address of a TLS section is not equal to the address of its
  782. // initialization image
  783. if (IsTLS)
  784. Sections.back().setLoadAddress(LoadAddress);
  785. // Debug info sections are linked as if their load address was zero
  786. if (!IsRequired)
  787. Sections.back().setLoadAddress(0);
  788. return SectionID;
  789. }
  790. Expected<unsigned>
  791. RuntimeDyldImpl::findOrEmitSection(const ObjectFile &Obj,
  792. const SectionRef &Section,
  793. bool IsCode,
  794. ObjSectionToIDMap &LocalSections) {
  795. unsigned SectionID = 0;
  796. ObjSectionToIDMap::iterator i = LocalSections.find(Section);
  797. if (i != LocalSections.end())
  798. SectionID = i->second;
  799. else {
  800. if (auto SectionIDOrErr = emitSection(Obj, Section, IsCode))
  801. SectionID = *SectionIDOrErr;
  802. else
  803. return SectionIDOrErr.takeError();
  804. LocalSections[Section] = SectionID;
  805. }
  806. return SectionID;
  807. }
  808. void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
  809. unsigned SectionID) {
  810. Relocations[SectionID].push_back(RE);
  811. }
  812. void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
  813. StringRef SymbolName) {
  814. // Relocation by symbol. If the symbol is found in the global symbol table,
  815. // create an appropriate section relocation. Otherwise, add it to
  816. // ExternalSymbolRelocations.
  817. RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(SymbolName);
  818. if (Loc == GlobalSymbolTable.end()) {
  819. ExternalSymbolRelocations[SymbolName].push_back(RE);
  820. } else {
  821. assert(!SymbolName.empty() &&
  822. "Empty symbol should not be in GlobalSymbolTable");
  823. // Copy the RE since we want to modify its addend.
  824. RelocationEntry RECopy = RE;
  825. const auto &SymInfo = Loc->second;
  826. RECopy.Addend += SymInfo.getOffset();
  827. Relocations[SymInfo.getSectionID()].push_back(RECopy);
  828. }
  829. }
  830. uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr,
  831. unsigned AbiVariant) {
  832. if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be ||
  833. Arch == Triple::aarch64_32) {
  834. // This stub has to be able to access the full address space,
  835. // since symbol lookup won't necessarily find a handy, in-range,
  836. // PLT stub for functions which could be anywhere.
  837. // Stub can use ip0 (== x16) to calculate address
  838. writeBytesUnaligned(0xd2e00010, Addr, 4); // movz ip0, #:abs_g3:<addr>
  839. writeBytesUnaligned(0xf2c00010, Addr+4, 4); // movk ip0, #:abs_g2_nc:<addr>
  840. writeBytesUnaligned(0xf2a00010, Addr+8, 4); // movk ip0, #:abs_g1_nc:<addr>
  841. writeBytesUnaligned(0xf2800010, Addr+12, 4); // movk ip0, #:abs_g0_nc:<addr>
  842. writeBytesUnaligned(0xd61f0200, Addr+16, 4); // br ip0
  843. return Addr;
  844. } else if (Arch == Triple::arm || Arch == Triple::armeb) {
  845. // TODO: There is only ARM far stub now. We should add the Thumb stub,
  846. // and stubs for branches Thumb - ARM and ARM - Thumb.
  847. writeBytesUnaligned(0xe51ff004, Addr, 4); // ldr pc, [pc, #-4]
  848. return Addr + 4;
  849. } else if (IsMipsO32ABI || IsMipsN32ABI) {
  850. // 0: 3c190000 lui t9,%hi(addr).
  851. // 4: 27390000 addiu t9,t9,%lo(addr).
  852. // 8: 03200008 jr t9.
  853. // c: 00000000 nop.
  854. const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
  855. const unsigned NopInstr = 0x0;
  856. unsigned JrT9Instr = 0x03200008;
  857. if ((AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_32R6 ||
  858. (AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_64R6)
  859. JrT9Instr = 0x03200009;
  860. writeBytesUnaligned(LuiT9Instr, Addr, 4);
  861. writeBytesUnaligned(AdduiT9Instr, Addr + 4, 4);
  862. writeBytesUnaligned(JrT9Instr, Addr + 8, 4);
  863. writeBytesUnaligned(NopInstr, Addr + 12, 4);
  864. return Addr;
  865. } else if (IsMipsN64ABI) {
  866. // 0: 3c190000 lui t9,%highest(addr).
  867. // 4: 67390000 daddiu t9,t9,%higher(addr).
  868. // 8: 0019CC38 dsll t9,t9,16.
  869. // c: 67390000 daddiu t9,t9,%hi(addr).
  870. // 10: 0019CC38 dsll t9,t9,16.
  871. // 14: 67390000 daddiu t9,t9,%lo(addr).
  872. // 18: 03200008 jr t9.
  873. // 1c: 00000000 nop.
  874. const unsigned LuiT9Instr = 0x3c190000, DaddiuT9Instr = 0x67390000,
  875. DsllT9Instr = 0x19CC38;
  876. const unsigned NopInstr = 0x0;
  877. unsigned JrT9Instr = 0x03200008;
  878. if ((AbiVariant & ELF::EF_MIPS_ARCH) == ELF::EF_MIPS_ARCH_64R6)
  879. JrT9Instr = 0x03200009;
  880. writeBytesUnaligned(LuiT9Instr, Addr, 4);
  881. writeBytesUnaligned(DaddiuT9Instr, Addr + 4, 4);
  882. writeBytesUnaligned(DsllT9Instr, Addr + 8, 4);
  883. writeBytesUnaligned(DaddiuT9Instr, Addr + 12, 4);
  884. writeBytesUnaligned(DsllT9Instr, Addr + 16, 4);
  885. writeBytesUnaligned(DaddiuT9Instr, Addr + 20, 4);
  886. writeBytesUnaligned(JrT9Instr, Addr + 24, 4);
  887. writeBytesUnaligned(NopInstr, Addr + 28, 4);
  888. return Addr;
  889. } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
  890. // Depending on which version of the ELF ABI is in use, we need to
  891. // generate one of two variants of the stub. They both start with
  892. // the same sequence to load the target address into r12.
  893. writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
  894. writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
  895. writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
  896. writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
  897. writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
  898. if (AbiVariant == 2) {
  899. // PowerPC64 stub ELFv2 ABI: The address points to the function itself.
  900. // The address is already in r12 as required by the ABI. Branch to it.
  901. writeInt32BE(Addr+20, 0xF8410018); // std r2, 24(r1)
  902. writeInt32BE(Addr+24, 0x7D8903A6); // mtctr r12
  903. writeInt32BE(Addr+28, 0x4E800420); // bctr
  904. } else {
  905. // PowerPC64 stub ELFv1 ABI: The address points to a function descriptor.
  906. // Load the function address on r11 and sets it to control register. Also
  907. // loads the function TOC in r2 and environment pointer to r11.
  908. writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
  909. writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
  910. writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
  911. writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
  912. writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
  913. writeInt32BE(Addr+40, 0x4E800420); // bctr
  914. }
  915. return Addr;
  916. } else if (Arch == Triple::systemz) {
  917. writeInt16BE(Addr, 0xC418); // lgrl %r1,.+8
  918. writeInt16BE(Addr+2, 0x0000);
  919. writeInt16BE(Addr+4, 0x0004);
  920. writeInt16BE(Addr+6, 0x07F1); // brc 15,%r1
  921. // 8-byte address stored at Addr + 8
  922. return Addr;
  923. } else if (Arch == Triple::x86_64) {
  924. *Addr = 0xFF; // jmp
  925. *(Addr+1) = 0x25; // rip
  926. // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
  927. } else if (Arch == Triple::x86) {
  928. *Addr = 0xE9; // 32-bit pc-relative jump.
  929. }
  930. return Addr;
  931. }
  932. // Assign an address to a symbol name and resolve all the relocations
  933. // associated with it.
  934. void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
  935. uint64_t Addr) {
  936. // The address to use for relocation resolution is not
  937. // the address of the local section buffer. We must be doing
  938. // a remote execution environment of some sort. Relocations can't
  939. // be applied until all the sections have been moved. The client must
  940. // trigger this with a call to MCJIT::finalize() or
  941. // RuntimeDyld::resolveRelocations().
  942. //
  943. // Addr is a uint64_t because we can't assume the pointer width
  944. // of the target is the same as that of the host. Just use a generic
  945. // "big enough" type.
  946. LLVM_DEBUG(
  947. dbgs() << "Reassigning address for section " << SectionID << " ("
  948. << Sections[SectionID].getName() << "): "
  949. << format("0x%016" PRIx64, Sections[SectionID].getLoadAddress())
  950. << " -> " << format("0x%016" PRIx64, Addr) << "\n");
  951. Sections[SectionID].setLoadAddress(Addr);
  952. }
  953. void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
  954. uint64_t Value) {
  955. for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
  956. const RelocationEntry &RE = Relocs[i];
  957. // Ignore relocations for sections that were not loaded
  958. if (RE.SectionID != AbsoluteSymbolSection &&
  959. Sections[RE.SectionID].getAddress() == nullptr)
  960. continue;
  961. resolveRelocation(RE, Value);
  962. }
  963. }
  964. void RuntimeDyldImpl::applyExternalSymbolRelocations(
  965. const StringMap<JITEvaluatedSymbol> ExternalSymbolMap) {
  966. for (auto &RelocKV : ExternalSymbolRelocations) {
  967. StringRef Name = RelocKV.first();
  968. RelocationList &Relocs = RelocKV.second;
  969. if (Name.size() == 0) {
  970. // This is an absolute symbol, use an address of zero.
  971. LLVM_DEBUG(dbgs() << "Resolving absolute relocations."
  972. << "\n");
  973. resolveRelocationList(Relocs, 0);
  974. } else {
  975. uint64_t Addr = 0;
  976. JITSymbolFlags Flags;
  977. RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(Name);
  978. if (Loc == GlobalSymbolTable.end()) {
  979. auto RRI = ExternalSymbolMap.find(Name);
  980. assert(RRI != ExternalSymbolMap.end() && "No result for symbol");
  981. Addr = RRI->second.getAddress();
  982. Flags = RRI->second.getFlags();
  983. } else {
  984. // We found the symbol in our global table. It was probably in a
  985. // Module that we loaded previously.
  986. const auto &SymInfo = Loc->second;
  987. Addr = getSectionLoadAddress(SymInfo.getSectionID()) +
  988. SymInfo.getOffset();
  989. Flags = SymInfo.getFlags();
  990. }
  991. // FIXME: Implement error handling that doesn't kill the host program!
  992. if (!Addr && !Resolver.allowsZeroSymbols())
  993. report_fatal_error(Twine("Program used external function '") + Name +
  994. "' which could not be resolved!");
  995. // If Resolver returned UINT64_MAX, the client wants to handle this symbol
  996. // manually and we shouldn't resolve its relocations.
  997. if (Addr != UINT64_MAX) {
  998. // Tweak the address based on the symbol flags if necessary.
  999. // For example, this is used by RuntimeDyldMachOARM to toggle the low bit
  1000. // if the target symbol is Thumb.
  1001. Addr = modifyAddressBasedOnFlags(Addr, Flags);
  1002. LLVM_DEBUG(dbgs() << "Resolving relocations Name: " << Name << "\t"
  1003. << format("0x%lx", Addr) << "\n");
  1004. resolveRelocationList(Relocs, Addr);
  1005. }
  1006. }
  1007. }
  1008. ExternalSymbolRelocations.clear();
  1009. }
  1010. Error RuntimeDyldImpl::resolveExternalSymbols() {
  1011. StringMap<JITEvaluatedSymbol> ExternalSymbolMap;
  1012. // Resolution can trigger emission of more symbols, so iterate until
  1013. // we've resolved *everything*.
  1014. {
  1015. JITSymbolResolver::LookupSet ResolvedSymbols;
  1016. while (true) {
  1017. JITSymbolResolver::LookupSet NewSymbols;
  1018. for (auto &RelocKV : ExternalSymbolRelocations) {
  1019. StringRef Name = RelocKV.first();
  1020. if (!Name.empty() && !GlobalSymbolTable.count(Name) &&
  1021. !ResolvedSymbols.count(Name))
  1022. NewSymbols.insert(Name);
  1023. }
  1024. if (NewSymbols.empty())
  1025. break;
  1026. #ifdef _MSC_VER
  1027. using ExpectedLookupResult =
  1028. MSVCPExpected<JITSymbolResolver::LookupResult>;
  1029. #else
  1030. using ExpectedLookupResult = Expected<JITSymbolResolver::LookupResult>;
  1031. #endif
  1032. auto NewSymbolsP = std::make_shared<std::promise<ExpectedLookupResult>>();
  1033. auto NewSymbolsF = NewSymbolsP->get_future();
  1034. Resolver.lookup(NewSymbols,
  1035. [=](Expected<JITSymbolResolver::LookupResult> Result) {
  1036. NewSymbolsP->set_value(std::move(Result));
  1037. });
  1038. auto NewResolverResults = NewSymbolsF.get();
  1039. if (!NewResolverResults)
  1040. return NewResolverResults.takeError();
  1041. assert(NewResolverResults->size() == NewSymbols.size() &&
  1042. "Should have errored on unresolved symbols");
  1043. for (auto &RRKV : *NewResolverResults) {
  1044. assert(!ResolvedSymbols.count(RRKV.first) && "Redundant resolution?");
  1045. ExternalSymbolMap.insert(RRKV);
  1046. ResolvedSymbols.insert(RRKV.first);
  1047. }
  1048. }
  1049. }
  1050. applyExternalSymbolRelocations(ExternalSymbolMap);
  1051. return Error::success();
  1052. }
  1053. void RuntimeDyldImpl::finalizeAsync(
  1054. std::unique_ptr<RuntimeDyldImpl> This,
  1055. unique_function<void(object::OwningBinary<object::ObjectFile>,
  1056. std::unique_ptr<RuntimeDyld::LoadedObjectInfo>, Error)>
  1057. OnEmitted,
  1058. object::OwningBinary<object::ObjectFile> O,
  1059. std::unique_ptr<RuntimeDyld::LoadedObjectInfo> Info) {
  1060. auto SharedThis = std::shared_ptr<RuntimeDyldImpl>(std::move(This));
  1061. auto PostResolveContinuation =
  1062. [SharedThis, OnEmitted = std::move(OnEmitted), O = std::move(O),
  1063. Info = std::move(Info)](
  1064. Expected<JITSymbolResolver::LookupResult> Result) mutable {
  1065. if (!Result) {
  1066. OnEmitted(std::move(O), std::move(Info), Result.takeError());
  1067. return;
  1068. }
  1069. /// Copy the result into a StringMap, where the keys are held by value.
  1070. StringMap<JITEvaluatedSymbol> Resolved;
  1071. for (auto &KV : *Result)
  1072. Resolved[KV.first] = KV.second;
  1073. SharedThis->applyExternalSymbolRelocations(Resolved);
  1074. SharedThis->resolveLocalRelocations();
  1075. SharedThis->registerEHFrames();
  1076. std::string ErrMsg;
  1077. if (SharedThis->MemMgr.finalizeMemory(&ErrMsg))
  1078. OnEmitted(std::move(O), std::move(Info),
  1079. make_error<StringError>(std::move(ErrMsg),
  1080. inconvertibleErrorCode()));
  1081. else
  1082. OnEmitted(std::move(O), std::move(Info), Error::success());
  1083. };
  1084. JITSymbolResolver::LookupSet Symbols;
  1085. for (auto &RelocKV : SharedThis->ExternalSymbolRelocations) {
  1086. StringRef Name = RelocKV.first();
  1087. if (Name.empty()) // Skip absolute symbol relocations.
  1088. continue;
  1089. assert(!SharedThis->GlobalSymbolTable.count(Name) &&
  1090. "Name already processed. RuntimeDyld instances can not be re-used "
  1091. "when finalizing with finalizeAsync.");
  1092. Symbols.insert(Name);
  1093. }
  1094. if (!Symbols.empty()) {
  1095. SharedThis->Resolver.lookup(Symbols, std::move(PostResolveContinuation));
  1096. } else
  1097. PostResolveContinuation(std::map<StringRef, JITEvaluatedSymbol>());
  1098. }
  1099. //===----------------------------------------------------------------------===//
  1100. // RuntimeDyld class implementation
  1101. uint64_t RuntimeDyld::LoadedObjectInfo::getSectionLoadAddress(
  1102. const object::SectionRef &Sec) const {
  1103. auto I = ObjSecToIDMap.find(Sec);
  1104. if (I != ObjSecToIDMap.end())
  1105. return RTDyld.Sections[I->second].getLoadAddress();
  1106. return 0;
  1107. }
  1108. RuntimeDyld::MemoryManager::TLSSection
  1109. RuntimeDyld::MemoryManager::allocateTLSSection(uintptr_t Size,
  1110. unsigned Alignment,
  1111. unsigned SectionID,
  1112. StringRef SectionName) {
  1113. report_fatal_error("allocation of TLS not implemented");
  1114. }
  1115. void RuntimeDyld::MemoryManager::anchor() {}
  1116. void JITSymbolResolver::anchor() {}
  1117. void LegacyJITSymbolResolver::anchor() {}
  1118. RuntimeDyld::RuntimeDyld(RuntimeDyld::MemoryManager &MemMgr,
  1119. JITSymbolResolver &Resolver)
  1120. : MemMgr(MemMgr), Resolver(Resolver) {
  1121. // FIXME: There's a potential issue lurking here if a single instance of
  1122. // RuntimeDyld is used to load multiple objects. The current implementation
  1123. // associates a single memory manager with a RuntimeDyld instance. Even
  1124. // though the public class spawns a new 'impl' instance for each load,
  1125. // they share a single memory manager. This can become a problem when page
  1126. // permissions are applied.
  1127. Dyld = nullptr;
  1128. ProcessAllSections = false;
  1129. }
  1130. RuntimeDyld::~RuntimeDyld() {}
  1131. static std::unique_ptr<RuntimeDyldCOFF>
  1132. createRuntimeDyldCOFF(
  1133. Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
  1134. JITSymbolResolver &Resolver, bool ProcessAllSections,
  1135. RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
  1136. std::unique_ptr<RuntimeDyldCOFF> Dyld =
  1137. RuntimeDyldCOFF::create(Arch, MM, Resolver);
  1138. Dyld->setProcessAllSections(ProcessAllSections);
  1139. Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
  1140. return Dyld;
  1141. }
  1142. static std::unique_ptr<RuntimeDyldELF>
  1143. createRuntimeDyldELF(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
  1144. JITSymbolResolver &Resolver, bool ProcessAllSections,
  1145. RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
  1146. std::unique_ptr<RuntimeDyldELF> Dyld =
  1147. RuntimeDyldELF::create(Arch, MM, Resolver);
  1148. Dyld->setProcessAllSections(ProcessAllSections);
  1149. Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
  1150. return Dyld;
  1151. }
  1152. static std::unique_ptr<RuntimeDyldMachO>
  1153. createRuntimeDyldMachO(
  1154. Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
  1155. JITSymbolResolver &Resolver,
  1156. bool ProcessAllSections,
  1157. RuntimeDyld::NotifyStubEmittedFunction NotifyStubEmitted) {
  1158. std::unique_ptr<RuntimeDyldMachO> Dyld =
  1159. RuntimeDyldMachO::create(Arch, MM, Resolver);
  1160. Dyld->setProcessAllSections(ProcessAllSections);
  1161. Dyld->setNotifyStubEmitted(std::move(NotifyStubEmitted));
  1162. return Dyld;
  1163. }
  1164. std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
  1165. RuntimeDyld::loadObject(const ObjectFile &Obj) {
  1166. if (!Dyld) {
  1167. if (Obj.isELF())
  1168. Dyld =
  1169. createRuntimeDyldELF(static_cast<Triple::ArchType>(Obj.getArch()),
  1170. MemMgr, Resolver, ProcessAllSections,
  1171. std::move(NotifyStubEmitted));
  1172. else if (Obj.isMachO())
  1173. Dyld = createRuntimeDyldMachO(
  1174. static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
  1175. ProcessAllSections, std::move(NotifyStubEmitted));
  1176. else if (Obj.isCOFF())
  1177. Dyld = createRuntimeDyldCOFF(
  1178. static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
  1179. ProcessAllSections, std::move(NotifyStubEmitted));
  1180. else
  1181. report_fatal_error("Incompatible object format!");
  1182. }
  1183. if (!Dyld->isCompatibleFile(Obj))
  1184. report_fatal_error("Incompatible object format!");
  1185. auto LoadedObjInfo = Dyld->loadObject(Obj);
  1186. MemMgr.notifyObjectLoaded(*this, Obj);
  1187. return LoadedObjInfo;
  1188. }
  1189. void *RuntimeDyld::getSymbolLocalAddress(StringRef Name) const {
  1190. if (!Dyld)
  1191. return nullptr;
  1192. return Dyld->getSymbolLocalAddress(Name);
  1193. }
  1194. unsigned RuntimeDyld::getSymbolSectionID(StringRef Name) const {
  1195. assert(Dyld && "No RuntimeDyld instance attached");
  1196. return Dyld->getSymbolSectionID(Name);
  1197. }
  1198. JITEvaluatedSymbol RuntimeDyld::getSymbol(StringRef Name) const {
  1199. if (!Dyld)
  1200. return nullptr;
  1201. return Dyld->getSymbol(Name);
  1202. }
  1203. std::map<StringRef, JITEvaluatedSymbol> RuntimeDyld::getSymbolTable() const {
  1204. if (!Dyld)
  1205. return std::map<StringRef, JITEvaluatedSymbol>();
  1206. return Dyld->getSymbolTable();
  1207. }
  1208. void RuntimeDyld::resolveRelocations() { Dyld->resolveRelocations(); }
  1209. void RuntimeDyld::reassignSectionAddress(unsigned SectionID, uint64_t Addr) {
  1210. Dyld->reassignSectionAddress(SectionID, Addr);
  1211. }
  1212. void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
  1213. uint64_t TargetAddress) {
  1214. Dyld->mapSectionAddress(LocalAddress, TargetAddress);
  1215. }
  1216. bool RuntimeDyld::hasError() { return Dyld->hasError(); }
  1217. StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); }
  1218. void RuntimeDyld::finalizeWithMemoryManagerLocking() {
  1219. bool MemoryFinalizationLocked = MemMgr.FinalizationLocked;
  1220. MemMgr.FinalizationLocked = true;
  1221. resolveRelocations();
  1222. registerEHFrames();
  1223. if (!MemoryFinalizationLocked) {
  1224. MemMgr.finalizeMemory();
  1225. MemMgr.FinalizationLocked = false;
  1226. }
  1227. }
  1228. StringRef RuntimeDyld::getSectionContent(unsigned SectionID) const {
  1229. assert(Dyld && "No Dyld instance attached");
  1230. return Dyld->getSectionContent(SectionID);
  1231. }
  1232. uint64_t RuntimeDyld::getSectionLoadAddress(unsigned SectionID) const {
  1233. assert(Dyld && "No Dyld instance attached");
  1234. return Dyld->getSectionLoadAddress(SectionID);
  1235. }
  1236. void RuntimeDyld::registerEHFrames() {
  1237. if (Dyld)
  1238. Dyld->registerEHFrames();
  1239. }
  1240. void RuntimeDyld::deregisterEHFrames() {
  1241. if (Dyld)
  1242. Dyld->deregisterEHFrames();
  1243. }
  1244. // FIXME: Kill this with fire once we have a new JIT linker: this is only here
  1245. // so that we can re-use RuntimeDyld's implementation without twisting the
  1246. // interface any further for ORC's purposes.
  1247. void jitLinkForORC(
  1248. object::OwningBinary<object::ObjectFile> O,
  1249. RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver,
  1250. bool ProcessAllSections,
  1251. unique_function<Error(const object::ObjectFile &Obj,
  1252. RuntimeDyld::LoadedObjectInfo &LoadedObj,
  1253. std::map<StringRef, JITEvaluatedSymbol>)>
  1254. OnLoaded,
  1255. unique_function<void(object::OwningBinary<object::ObjectFile>,
  1256. std::unique_ptr<RuntimeDyld::LoadedObjectInfo>, Error)>
  1257. OnEmitted) {
  1258. RuntimeDyld RTDyld(MemMgr, Resolver);
  1259. RTDyld.setProcessAllSections(ProcessAllSections);
  1260. auto Info = RTDyld.loadObject(*O.getBinary());
  1261. if (RTDyld.hasError()) {
  1262. OnEmitted(std::move(O), std::move(Info),
  1263. make_error<StringError>(RTDyld.getErrorString(),
  1264. inconvertibleErrorCode()));
  1265. return;
  1266. }
  1267. if (auto Err = OnLoaded(*O.getBinary(), *Info, RTDyld.getSymbolTable()))
  1268. OnEmitted(std::move(O), std::move(Info), std::move(Err));
  1269. RuntimeDyldImpl::finalizeAsync(std::move(RTDyld.Dyld), std::move(OnEmitted),
  1270. std::move(O), std::move(Info));
  1271. }
  1272. } // end namespace llvm