RuntimeDyld.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  1. //===-- RuntimeDyld.cpp - Run-time dynamic linker for MC-JIT ----*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Implementation of the MC-JIT runtime dynamic linker.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ExecutionEngine/RuntimeDyld.h"
  14. #include "RuntimeDyldCheckerImpl.h"
  15. #include "RuntimeDyldCOFF.h"
  16. #include "RuntimeDyldELF.h"
  17. #include "RuntimeDyldImpl.h"
  18. #include "RuntimeDyldMachO.h"
  19. #include "llvm/Object/ELFObjectFile.h"
  20. #include "llvm/Object/COFF.h"
  21. #include "llvm/Support/MathExtras.h"
  22. #include "llvm/Support/MutexGuard.h"
  23. using namespace llvm;
  24. using namespace llvm::object;
  25. #define DEBUG_TYPE "dyld"
  26. // Empty out-of-line virtual destructor as the key function.
  27. RuntimeDyldImpl::~RuntimeDyldImpl() {}
  28. // Pin LoadedObjectInfo's vtables to this file.
  29. void RuntimeDyld::LoadedObjectInfo::anchor() {}
  30. namespace llvm {
  31. void RuntimeDyldImpl::registerEHFrames() {}
  32. void RuntimeDyldImpl::deregisterEHFrames() {}
  33. #ifndef NDEBUG
  34. static void dumpSectionMemory(const SectionEntry &S, StringRef State) {
  35. dbgs() << "----- Contents of section " << S.Name << " " << State << " -----";
  36. if (S.Address == nullptr) {
  37. dbgs() << "\n <section not emitted>\n";
  38. return;
  39. }
  40. const unsigned ColsPerRow = 16;
  41. uint8_t *DataAddr = S.Address;
  42. uint64_t LoadAddr = S.LoadAddress;
  43. unsigned StartPadding = LoadAddr & (ColsPerRow - 1);
  44. unsigned BytesRemaining = S.Size;
  45. if (StartPadding) {
  46. dbgs() << "\n" << format("0x%016" PRIx64,
  47. LoadAddr & ~(uint64_t)(ColsPerRow - 1)) << ":";
  48. while (StartPadding--)
  49. dbgs() << " ";
  50. }
  51. while (BytesRemaining > 0) {
  52. if ((LoadAddr & (ColsPerRow - 1)) == 0)
  53. dbgs() << "\n" << format("0x%016" PRIx64, LoadAddr) << ":";
  54. dbgs() << " " << format("%02x", *DataAddr);
  55. ++DataAddr;
  56. ++LoadAddr;
  57. --BytesRemaining;
  58. }
  59. dbgs() << "\n";
  60. }
  61. #endif
  62. // Resolve the relocations for all symbols we currently know about.
  63. void RuntimeDyldImpl::resolveRelocations() {
  64. MutexGuard locked(lock);
  65. // First, resolve relocations associated with external symbols.
  66. resolveExternalSymbols();
  67. // Just iterate over the sections we have and resolve all the relocations
  68. // in them. Gross overkill, but it gets the job done.
  69. for (int i = 0, e = Sections.size(); i != e; ++i) {
  70. // The Section here (Sections[i]) refers to the section in which the
  71. // symbol for the relocation is located. The SectionID in the relocation
  72. // entry provides the section to which the relocation will be applied.
  73. uint64_t Addr = Sections[i].LoadAddress;
  74. DEBUG(dbgs() << "Resolving relocations Section #" << i << "\t"
  75. << format("%p", (uintptr_t)Addr) << "\n");
  76. DEBUG(dumpSectionMemory(Sections[i], "before relocations"));
  77. resolveRelocationList(Relocations[i], Addr);
  78. DEBUG(dumpSectionMemory(Sections[i], "after relocations"));
  79. Relocations.erase(i);
  80. }
  81. }
  82. void RuntimeDyldImpl::mapSectionAddress(const void *LocalAddress,
  83. uint64_t TargetAddress) {
  84. MutexGuard locked(lock);
  85. for (unsigned i = 0, e = Sections.size(); i != e; ++i) {
  86. if (Sections[i].Address == LocalAddress) {
  87. reassignSectionAddress(i, TargetAddress);
  88. return;
  89. }
  90. }
  91. llvm_unreachable("Attempting to remap address of unknown section!");
  92. }
  93. static std::error_code getOffset(const SymbolRef &Sym, SectionRef Sec,
  94. uint64_t &Result) {
  95. ErrorOr<uint64_t> AddressOrErr = Sym.getAddress();
  96. if (std::error_code EC = AddressOrErr.getError())
  97. return EC;
  98. Result = *AddressOrErr - Sec.getAddress();
  99. return std::error_code();
  100. }
  101. std::pair<unsigned, unsigned>
  102. RuntimeDyldImpl::loadObjectImpl(const object::ObjectFile &Obj) {
  103. MutexGuard locked(lock);
  104. // Grab the first Section ID. We'll use this later to construct the underlying
  105. // range for the returned LoadedObjectInfo.
  106. unsigned SectionsAddedBeginIdx = Sections.size();
  107. // Save information about our target
  108. Arch = (Triple::ArchType)Obj.getArch();
  109. IsTargetLittleEndian = Obj.isLittleEndian();
  110. setMipsABI(Obj);
  111. // Compute the memory size required to load all sections to be loaded
  112. // and pass this information to the memory manager
  113. if (MemMgr.needsToReserveAllocationSpace()) {
  114. uint64_t CodeSize = 0, DataSizeRO = 0, DataSizeRW = 0;
  115. computeTotalAllocSize(Obj, CodeSize, DataSizeRO, DataSizeRW);
  116. MemMgr.reserveAllocationSpace(CodeSize, DataSizeRO, DataSizeRW);
  117. }
  118. // Used sections from the object file
  119. ObjSectionToIDMap LocalSections;
  120. // Common symbols requiring allocation, with their sizes and alignments
  121. CommonSymbolList CommonSymbols;
  122. // Parse symbols
  123. DEBUG(dbgs() << "Parse symbols:\n");
  124. for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
  125. ++I) {
  126. uint32_t Flags = I->getFlags();
  127. bool IsCommon = Flags & SymbolRef::SF_Common;
  128. if (IsCommon)
  129. CommonSymbols.push_back(*I);
  130. else {
  131. object::SymbolRef::Type SymType = I->getType();
  132. if (SymType == object::SymbolRef::ST_Function ||
  133. SymType == object::SymbolRef::ST_Data ||
  134. SymType == object::SymbolRef::ST_Unknown) {
  135. ErrorOr<StringRef> NameOrErr = I->getName();
  136. Check(NameOrErr.getError());
  137. StringRef Name = *NameOrErr;
  138. section_iterator SI = Obj.section_end();
  139. Check(I->getSection(SI));
  140. if (SI == Obj.section_end())
  141. continue;
  142. uint64_t SectOffset;
  143. Check(getOffset(*I, *SI, SectOffset));
  144. StringRef SectionData;
  145. Check(SI->getContents(SectionData));
  146. bool IsCode = SI->isText();
  147. unsigned SectionID =
  148. findOrEmitSection(Obj, *SI, IsCode, LocalSections);
  149. DEBUG(dbgs() << "\tType: " << SymType << " Name: " << Name
  150. << " SID: " << SectionID << " Offset: "
  151. << format("%p", (uintptr_t)SectOffset)
  152. << " flags: " << Flags << "\n");
  153. JITSymbolFlags RTDyldSymFlags = JITSymbolFlags::None;
  154. if (Flags & SymbolRef::SF_Weak)
  155. RTDyldSymFlags |= JITSymbolFlags::Weak;
  156. if (Flags & SymbolRef::SF_Exported)
  157. RTDyldSymFlags |= JITSymbolFlags::Exported;
  158. GlobalSymbolTable[Name] =
  159. SymbolTableEntry(SectionID, SectOffset, RTDyldSymFlags);
  160. }
  161. }
  162. }
  163. // Allocate common symbols
  164. emitCommonSymbols(Obj, CommonSymbols);
  165. // Parse and process relocations
  166. DEBUG(dbgs() << "Parse relocations:\n");
  167. for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
  168. SI != SE; ++SI) {
  169. unsigned SectionID = 0;
  170. StubMap Stubs;
  171. section_iterator RelocatedSection = SI->getRelocatedSection();
  172. if (RelocatedSection == SE)
  173. continue;
  174. relocation_iterator I = SI->relocation_begin();
  175. relocation_iterator E = SI->relocation_end();
  176. if (I == E && !ProcessAllSections)
  177. continue;
  178. bool IsCode = RelocatedSection->isText();
  179. SectionID =
  180. findOrEmitSection(Obj, *RelocatedSection, IsCode, LocalSections);
  181. DEBUG(dbgs() << "\tSectionID: " << SectionID << "\n");
  182. for (; I != E;)
  183. I = processRelocationRef(SectionID, I, Obj, LocalSections, Stubs);
  184. // If there is an attached checker, notify it about the stubs for this
  185. // section so that they can be verified.
  186. if (Checker)
  187. Checker->registerStubMap(Obj.getFileName(), SectionID, Stubs);
  188. }
  189. // Give the subclasses a chance to tie-up any loose ends.
  190. finalizeLoad(Obj, LocalSections);
  191. unsigned SectionsAddedEndIdx = Sections.size();
  192. return std::make_pair(SectionsAddedBeginIdx, SectionsAddedEndIdx);
  193. }
  194. // A helper method for computeTotalAllocSize.
  195. // Computes the memory size required to allocate sections with the given sizes,
  196. // assuming that all sections are allocated with the given alignment
  197. static uint64_t
  198. computeAllocationSizeForSections(std::vector<uint64_t> &SectionSizes,
  199. uint64_t Alignment) {
  200. uint64_t TotalSize = 0;
  201. for (size_t Idx = 0, Cnt = SectionSizes.size(); Idx < Cnt; Idx++) {
  202. uint64_t AlignedSize =
  203. (SectionSizes[Idx] + Alignment - 1) / Alignment * Alignment;
  204. TotalSize += AlignedSize;
  205. }
  206. return TotalSize;
  207. }
  208. static bool isRequiredForExecution(const SectionRef Section) {
  209. const ObjectFile *Obj = Section.getObject();
  210. if (isa<object::ELFObjectFileBase>(Obj))
  211. return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
  212. if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj)) {
  213. const coff_section *CoffSection = COFFObj->getCOFFSection(Section);
  214. // Avoid loading zero-sized COFF sections.
  215. // In PE files, VirtualSize gives the section size, and SizeOfRawData
  216. // may be zero for sections with content. In Obj files, SizeOfRawData
  217. // gives the section size, and VirtualSize is always zero. Hence
  218. // the need to check for both cases below.
  219. bool HasContent = (CoffSection->VirtualSize > 0)
  220. || (CoffSection->SizeOfRawData > 0);
  221. bool IsDiscardable = CoffSection->Characteristics &
  222. (COFF::IMAGE_SCN_MEM_DISCARDABLE | COFF::IMAGE_SCN_LNK_INFO);
  223. return HasContent && !IsDiscardable;
  224. }
  225. assert(isa<MachOObjectFile>(Obj));
  226. return true;
  227. }
  228. static bool isReadOnlyData(const SectionRef Section) {
  229. const ObjectFile *Obj = Section.getObject();
  230. if (isa<object::ELFObjectFileBase>(Obj))
  231. return !(ELFSectionRef(Section).getFlags() &
  232. (ELF::SHF_WRITE | ELF::SHF_EXECINSTR));
  233. if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
  234. return ((COFFObj->getCOFFSection(Section)->Characteristics &
  235. (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
  236. | COFF::IMAGE_SCN_MEM_READ
  237. | COFF::IMAGE_SCN_MEM_WRITE))
  238. ==
  239. (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
  240. | COFF::IMAGE_SCN_MEM_READ));
  241. assert(isa<MachOObjectFile>(Obj));
  242. return false;
  243. }
  244. static bool isZeroInit(const SectionRef Section) {
  245. const ObjectFile *Obj = Section.getObject();
  246. if (isa<object::ELFObjectFileBase>(Obj))
  247. return ELFSectionRef(Section).getType() == ELF::SHT_NOBITS;
  248. if (auto *COFFObj = dyn_cast<object::COFFObjectFile>(Obj))
  249. return COFFObj->getCOFFSection(Section)->Characteristics &
  250. COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
  251. auto *MachO = cast<MachOObjectFile>(Obj);
  252. unsigned SectionType = MachO->getSectionType(Section);
  253. return SectionType == MachO::S_ZEROFILL ||
  254. SectionType == MachO::S_GB_ZEROFILL;
  255. }
  256. // Compute an upper bound of the memory size that is required to load all
  257. // sections
  258. void RuntimeDyldImpl::computeTotalAllocSize(const ObjectFile &Obj,
  259. uint64_t &CodeSize,
  260. uint64_t &DataSizeRO,
  261. uint64_t &DataSizeRW) {
  262. // Compute the size of all sections required for execution
  263. std::vector<uint64_t> CodeSectionSizes;
  264. std::vector<uint64_t> ROSectionSizes;
  265. std::vector<uint64_t> RWSectionSizes;
  266. uint64_t MaxAlignment = sizeof(void *);
  267. // Collect sizes of all sections to be loaded;
  268. // also determine the max alignment of all sections
  269. for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
  270. SI != SE; ++SI) {
  271. const SectionRef &Section = *SI;
  272. bool IsRequired = isRequiredForExecution(Section);
  273. // Consider only the sections that are required to be loaded for execution
  274. if (IsRequired) {
  275. StringRef Name;
  276. uint64_t DataSize = Section.getSize();
  277. uint64_t Alignment64 = Section.getAlignment();
  278. bool IsCode = Section.isText();
  279. bool IsReadOnly = isReadOnlyData(Section);
  280. Check(Section.getName(Name));
  281. unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
  282. uint64_t StubBufSize = computeSectionStubBufSize(Obj, Section);
  283. uint64_t SectionSize = DataSize + StubBufSize;
  284. // The .eh_frame section (at least on Linux) needs an extra four bytes
  285. // padded
  286. // with zeroes added at the end. For MachO objects, this section has a
  287. // slightly different name, so this won't have any effect for MachO
  288. // objects.
  289. if (Name == ".eh_frame")
  290. SectionSize += 4;
  291. if (!SectionSize)
  292. SectionSize = 1;
  293. if (IsCode) {
  294. CodeSectionSizes.push_back(SectionSize);
  295. } else if (IsReadOnly) {
  296. ROSectionSizes.push_back(SectionSize);
  297. } else {
  298. RWSectionSizes.push_back(SectionSize);
  299. }
  300. // update the max alignment
  301. if (Alignment > MaxAlignment) {
  302. MaxAlignment = Alignment;
  303. }
  304. }
  305. }
  306. // Compute the size of all common symbols
  307. uint64_t CommonSize = 0;
  308. for (symbol_iterator I = Obj.symbol_begin(), E = Obj.symbol_end(); I != E;
  309. ++I) {
  310. uint32_t Flags = I->getFlags();
  311. if (Flags & SymbolRef::SF_Common) {
  312. // Add the common symbols to a list. We'll allocate them all below.
  313. uint64_t Size = I->getCommonSize();
  314. CommonSize += Size;
  315. }
  316. }
  317. if (CommonSize != 0) {
  318. RWSectionSizes.push_back(CommonSize);
  319. }
  320. // Compute the required allocation space for each different type of sections
  321. // (code, read-only data, read-write data) assuming that all sections are
  322. // allocated with the max alignment. Note that we cannot compute with the
  323. // individual alignments of the sections, because then the required size
  324. // depends on the order, in which the sections are allocated.
  325. CodeSize = computeAllocationSizeForSections(CodeSectionSizes, MaxAlignment);
  326. DataSizeRO = computeAllocationSizeForSections(ROSectionSizes, MaxAlignment);
  327. DataSizeRW = computeAllocationSizeForSections(RWSectionSizes, MaxAlignment);
  328. }
  329. // compute stub buffer size for the given section
  330. unsigned RuntimeDyldImpl::computeSectionStubBufSize(const ObjectFile &Obj,
  331. const SectionRef &Section) {
  332. unsigned StubSize = getMaxStubSize();
  333. if (StubSize == 0) {
  334. return 0;
  335. }
  336. // FIXME: this is an inefficient way to handle this. We should computed the
  337. // necessary section allocation size in loadObject by walking all the sections
  338. // once.
  339. unsigned StubBufSize = 0;
  340. for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
  341. SI != SE; ++SI) {
  342. section_iterator RelSecI = SI->getRelocatedSection();
  343. if (!(RelSecI == Section))
  344. continue;
  345. for (const RelocationRef &Reloc : SI->relocations()) {
  346. (void)Reloc;
  347. StubBufSize += StubSize;
  348. }
  349. }
  350. // Get section data size and alignment
  351. uint64_t DataSize = Section.getSize();
  352. uint64_t Alignment64 = Section.getAlignment();
  353. // Add stubbuf size alignment
  354. unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
  355. unsigned StubAlignment = getStubAlignment();
  356. unsigned EndAlignment = (DataSize | Alignment) & -(DataSize | Alignment);
  357. if (StubAlignment > EndAlignment)
  358. StubBufSize += StubAlignment - EndAlignment;
  359. return StubBufSize;
  360. }
  361. uint64_t RuntimeDyldImpl::readBytesUnaligned(uint8_t *Src,
  362. unsigned Size) const {
  363. uint64_t Result = 0;
  364. if (IsTargetLittleEndian) {
  365. Src += Size - 1;
  366. while (Size--)
  367. Result = (Result << 8) | *Src--;
  368. } else
  369. while (Size--)
  370. Result = (Result << 8) | *Src++;
  371. return Result;
  372. }
  373. void RuntimeDyldImpl::writeBytesUnaligned(uint64_t Value, uint8_t *Dst,
  374. unsigned Size) const {
  375. if (IsTargetLittleEndian) {
  376. while (Size--) {
  377. *Dst++ = Value & 0xFF;
  378. Value >>= 8;
  379. }
  380. } else {
  381. Dst += Size - 1;
  382. while (Size--) {
  383. *Dst-- = Value & 0xFF;
  384. Value >>= 8;
  385. }
  386. }
  387. }
  388. void RuntimeDyldImpl::emitCommonSymbols(const ObjectFile &Obj,
  389. CommonSymbolList &CommonSymbols) {
  390. if (CommonSymbols.empty())
  391. return;
  392. uint64_t CommonSize = 0;
  393. CommonSymbolList SymbolsToAllocate;
  394. DEBUG(dbgs() << "Processing common symbols...\n");
  395. for (const auto &Sym : CommonSymbols) {
  396. ErrorOr<StringRef> NameOrErr = Sym.getName();
  397. Check(NameOrErr.getError());
  398. StringRef Name = *NameOrErr;
  399. // Skip common symbols already elsewhere.
  400. if (GlobalSymbolTable.count(Name) ||
  401. Resolver.findSymbolInLogicalDylib(Name)) {
  402. DEBUG(dbgs() << "\tSkipping already emitted common symbol '" << Name
  403. << "'\n");
  404. continue;
  405. }
  406. uint32_t Align = Sym.getAlignment();
  407. uint64_t Size = Sym.getCommonSize();
  408. CommonSize += Align + Size;
  409. SymbolsToAllocate.push_back(Sym);
  410. }
  411. // Allocate memory for the section
  412. unsigned SectionID = Sections.size();
  413. uint8_t *Addr = MemMgr.allocateDataSection(CommonSize, sizeof(void *),
  414. SectionID, StringRef(), false);
  415. if (!Addr)
  416. report_fatal_error("Unable to allocate memory for common symbols!");
  417. uint64_t Offset = 0;
  418. Sections.push_back(SectionEntry("<common symbols>", Addr, CommonSize, 0));
  419. memset(Addr, 0, CommonSize);
  420. DEBUG(dbgs() << "emitCommonSection SectionID: " << SectionID << " new addr: "
  421. << format("%p", Addr) << " DataSize: " << CommonSize << "\n");
  422. // Assign the address of each symbol
  423. for (auto &Sym : SymbolsToAllocate) {
  424. uint32_t Align = Sym.getAlignment();
  425. uint64_t Size = Sym.getCommonSize();
  426. ErrorOr<StringRef> NameOrErr = Sym.getName();
  427. Check(NameOrErr.getError());
  428. StringRef Name = *NameOrErr;
  429. if (Align) {
  430. // This symbol has an alignment requirement.
  431. uint64_t AlignOffset = OffsetToAlignment((uint64_t)Addr, Align);
  432. Addr += AlignOffset;
  433. Offset += AlignOffset;
  434. }
  435. uint32_t Flags = Sym.getFlags();
  436. JITSymbolFlags RTDyldSymFlags = JITSymbolFlags::None;
  437. if (Flags & SymbolRef::SF_Weak)
  438. RTDyldSymFlags |= JITSymbolFlags::Weak;
  439. if (Flags & SymbolRef::SF_Exported)
  440. RTDyldSymFlags |= JITSymbolFlags::Exported;
  441. DEBUG(dbgs() << "Allocating common symbol " << Name << " address "
  442. << format("%p", Addr) << "\n");
  443. GlobalSymbolTable[Name] =
  444. SymbolTableEntry(SectionID, Offset, RTDyldSymFlags);
  445. Offset += Size;
  446. Addr += Size;
  447. }
  448. }
  449. unsigned RuntimeDyldImpl::emitSection(const ObjectFile &Obj,
  450. const SectionRef &Section, bool IsCode) {
  451. StringRef data;
  452. uint64_t Alignment64 = Section.getAlignment();
  453. unsigned Alignment = (unsigned)Alignment64 & 0xffffffffL;
  454. unsigned PaddingSize = 0;
  455. unsigned StubBufSize = 0;
  456. StringRef Name;
  457. bool IsRequired = isRequiredForExecution(Section);
  458. bool IsVirtual = Section.isVirtual();
  459. bool IsZeroInit = isZeroInit(Section);
  460. bool IsReadOnly = isReadOnlyData(Section);
  461. uint64_t DataSize = Section.getSize();
  462. Check(Section.getName(Name));
  463. StubBufSize = computeSectionStubBufSize(Obj, Section);
  464. // The .eh_frame section (at least on Linux) needs an extra four bytes padded
  465. // with zeroes added at the end. For MachO objects, this section has a
  466. // slightly different name, so this won't have any effect for MachO objects.
  467. if (Name == ".eh_frame")
  468. PaddingSize = 4;
  469. uintptr_t Allocate;
  470. unsigned SectionID = Sections.size();
  471. uint8_t *Addr;
  472. const char *pData = nullptr;
  473. // In either case, set the location of the unrelocated section in memory,
  474. // since we still process relocations for it even if we're not applying them.
  475. Check(Section.getContents(data));
  476. // Virtual sections have no data in the object image, so leave pData = 0
  477. if (!IsVirtual)
  478. pData = data.data();
  479. // Some sections, such as debug info, don't need to be loaded for execution.
  480. // Leave those where they are.
  481. if (IsRequired) {
  482. Allocate = DataSize + PaddingSize + StubBufSize;
  483. if (!Allocate)
  484. Allocate = 1;
  485. Addr = IsCode ? MemMgr.allocateCodeSection(Allocate, Alignment, SectionID,
  486. Name)
  487. : MemMgr.allocateDataSection(Allocate, Alignment, SectionID,
  488. Name, IsReadOnly);
  489. if (!Addr)
  490. report_fatal_error("Unable to allocate section memory!");
  491. // Zero-initialize or copy the data from the image
  492. if (IsZeroInit || IsVirtual)
  493. memset(Addr, 0, DataSize);
  494. else
  495. memcpy(Addr, pData, DataSize);
  496. // Fill in any extra bytes we allocated for padding
  497. if (PaddingSize != 0) {
  498. memset(Addr + DataSize, 0, PaddingSize);
  499. // Update the DataSize variable so that the stub offset is set correctly.
  500. DataSize += PaddingSize;
  501. }
  502. DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
  503. << " obj addr: " << format("%p", pData)
  504. << " new addr: " << format("%p", Addr)
  505. << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
  506. << " Allocate: " << Allocate << "\n");
  507. } else {
  508. // Even if we didn't load the section, we need to record an entry for it
  509. // to handle later processing (and by 'handle' I mean don't do anything
  510. // with these sections).
  511. Allocate = 0;
  512. Addr = nullptr;
  513. DEBUG(dbgs() << "emitSection SectionID: " << SectionID << " Name: " << Name
  514. << " obj addr: " << format("%p", data.data()) << " new addr: 0"
  515. << " DataSize: " << DataSize << " StubBufSize: " << StubBufSize
  516. << " Allocate: " << Allocate << "\n");
  517. }
  518. Sections.push_back(SectionEntry(Name, Addr, DataSize, (uintptr_t)pData));
  519. if (Checker)
  520. Checker->registerSection(Obj.getFileName(), SectionID);
  521. return SectionID;
  522. }
  523. unsigned RuntimeDyldImpl::findOrEmitSection(const ObjectFile &Obj,
  524. const SectionRef &Section,
  525. bool IsCode,
  526. ObjSectionToIDMap &LocalSections) {
  527. unsigned SectionID = 0;
  528. ObjSectionToIDMap::iterator i = LocalSections.find(Section);
  529. if (i != LocalSections.end())
  530. SectionID = i->second;
  531. else {
  532. SectionID = emitSection(Obj, Section, IsCode);
  533. LocalSections[Section] = SectionID;
  534. }
  535. return SectionID;
  536. }
  537. void RuntimeDyldImpl::addRelocationForSection(const RelocationEntry &RE,
  538. unsigned SectionID) {
  539. Relocations[SectionID].push_back(RE);
  540. }
  541. void RuntimeDyldImpl::addRelocationForSymbol(const RelocationEntry &RE,
  542. StringRef SymbolName) {
  543. // Relocation by symbol. If the symbol is found in the global symbol table,
  544. // create an appropriate section relocation. Otherwise, add it to
  545. // ExternalSymbolRelocations.
  546. RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(SymbolName);
  547. if (Loc == GlobalSymbolTable.end()) {
  548. ExternalSymbolRelocations[SymbolName].push_back(RE);
  549. } else {
  550. // Copy the RE since we want to modify its addend.
  551. RelocationEntry RECopy = RE;
  552. const auto &SymInfo = Loc->second;
  553. RECopy.Addend += SymInfo.getOffset();
  554. Relocations[SymInfo.getSectionID()].push_back(RECopy);
  555. }
  556. }
  557. uint8_t *RuntimeDyldImpl::createStubFunction(uint8_t *Addr,
  558. unsigned AbiVariant) {
  559. if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be) {
  560. // This stub has to be able to access the full address space,
  561. // since symbol lookup won't necessarily find a handy, in-range,
  562. // PLT stub for functions which could be anywhere.
  563. // Stub can use ip0 (== x16) to calculate address
  564. writeBytesUnaligned(0xd2e00010, Addr, 4); // movz ip0, #:abs_g3:<addr>
  565. writeBytesUnaligned(0xf2c00010, Addr+4, 4); // movk ip0, #:abs_g2_nc:<addr>
  566. writeBytesUnaligned(0xf2a00010, Addr+8, 4); // movk ip0, #:abs_g1_nc:<addr>
  567. writeBytesUnaligned(0xf2800010, Addr+12, 4); // movk ip0, #:abs_g0_nc:<addr>
  568. writeBytesUnaligned(0xd61f0200, Addr+16, 4); // br ip0
  569. return Addr;
  570. } else if (Arch == Triple::arm || Arch == Triple::armeb) {
  571. // TODO: There is only ARM far stub now. We should add the Thumb stub,
  572. // and stubs for branches Thumb - ARM and ARM - Thumb.
  573. writeBytesUnaligned(0xe51ff004, Addr, 4); // ldr pc,<label>
  574. return Addr + 4;
  575. } else if (IsMipsO32ABI) {
  576. // 0: 3c190000 lui t9,%hi(addr).
  577. // 4: 27390000 addiu t9,t9,%lo(addr).
  578. // 8: 03200008 jr t9.
  579. // c: 00000000 nop.
  580. const unsigned LuiT9Instr = 0x3c190000, AdduiT9Instr = 0x27390000;
  581. const unsigned JrT9Instr = 0x03200008, NopInstr = 0x0;
  582. writeBytesUnaligned(LuiT9Instr, Addr, 4);
  583. writeBytesUnaligned(AdduiT9Instr, Addr+4, 4);
  584. writeBytesUnaligned(JrT9Instr, Addr+8, 4);
  585. writeBytesUnaligned(NopInstr, Addr+12, 4);
  586. return Addr;
  587. } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
  588. // Depending on which version of the ELF ABI is in use, we need to
  589. // generate one of two variants of the stub. They both start with
  590. // the same sequence to load the target address into r12.
  591. writeInt32BE(Addr, 0x3D800000); // lis r12, highest(addr)
  592. writeInt32BE(Addr+4, 0x618C0000); // ori r12, higher(addr)
  593. writeInt32BE(Addr+8, 0x798C07C6); // sldi r12, r12, 32
  594. writeInt32BE(Addr+12, 0x658C0000); // oris r12, r12, h(addr)
  595. writeInt32BE(Addr+16, 0x618C0000); // ori r12, r12, l(addr)
  596. if (AbiVariant == 2) {
  597. // PowerPC64 stub ELFv2 ABI: The address points to the function itself.
  598. // The address is already in r12 as required by the ABI. Branch to it.
  599. writeInt32BE(Addr+20, 0xF8410018); // std r2, 24(r1)
  600. writeInt32BE(Addr+24, 0x7D8903A6); // mtctr r12
  601. writeInt32BE(Addr+28, 0x4E800420); // bctr
  602. } else {
  603. // PowerPC64 stub ELFv1 ABI: The address points to a function descriptor.
  604. // Load the function address on r11 and sets it to control register. Also
  605. // loads the function TOC in r2 and environment pointer to r11.
  606. writeInt32BE(Addr+20, 0xF8410028); // std r2, 40(r1)
  607. writeInt32BE(Addr+24, 0xE96C0000); // ld r11, 0(r12)
  608. writeInt32BE(Addr+28, 0xE84C0008); // ld r2, 0(r12)
  609. writeInt32BE(Addr+32, 0x7D6903A6); // mtctr r11
  610. writeInt32BE(Addr+36, 0xE96C0010); // ld r11, 16(r2)
  611. writeInt32BE(Addr+40, 0x4E800420); // bctr
  612. }
  613. return Addr;
  614. } else if (Arch == Triple::systemz) {
  615. writeInt16BE(Addr, 0xC418); // lgrl %r1,.+8
  616. writeInt16BE(Addr+2, 0x0000);
  617. writeInt16BE(Addr+4, 0x0004);
  618. writeInt16BE(Addr+6, 0x07F1); // brc 15,%r1
  619. // 8-byte address stored at Addr + 8
  620. return Addr;
  621. } else if (Arch == Triple::x86_64) {
  622. *Addr = 0xFF; // jmp
  623. *(Addr+1) = 0x25; // rip
  624. // 32-bit PC-relative address of the GOT entry will be stored at Addr+2
  625. } else if (Arch == Triple::x86) {
  626. *Addr = 0xE9; // 32-bit pc-relative jump.
  627. }
  628. return Addr;
  629. }
  630. // Assign an address to a symbol name and resolve all the relocations
  631. // associated with it.
  632. void RuntimeDyldImpl::reassignSectionAddress(unsigned SectionID,
  633. uint64_t Addr) {
  634. // The address to use for relocation resolution is not
  635. // the address of the local section buffer. We must be doing
  636. // a remote execution environment of some sort. Relocations can't
  637. // be applied until all the sections have been moved. The client must
  638. // trigger this with a call to MCJIT::finalize() or
  639. // RuntimeDyld::resolveRelocations().
  640. //
  641. // Addr is a uint64_t because we can't assume the pointer width
  642. // of the target is the same as that of the host. Just use a generic
  643. // "big enough" type.
  644. DEBUG(dbgs() << "Reassigning address for section "
  645. << SectionID << " (" << Sections[SectionID].Name << "): "
  646. << format("0x%016" PRIx64, Sections[SectionID].LoadAddress) << " -> "
  647. << format("0x%016" PRIx64, Addr) << "\n");
  648. Sections[SectionID].LoadAddress = Addr;
  649. }
  650. void RuntimeDyldImpl::resolveRelocationList(const RelocationList &Relocs,
  651. uint64_t Value) {
  652. for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
  653. const RelocationEntry &RE = Relocs[i];
  654. // Ignore relocations for sections that were not loaded
  655. if (Sections[RE.SectionID].Address == nullptr)
  656. continue;
  657. resolveRelocation(RE, Value);
  658. }
  659. }
  660. void RuntimeDyldImpl::resolveExternalSymbols() {
  661. while (!ExternalSymbolRelocations.empty()) {
  662. StringMap<RelocationList>::iterator i = ExternalSymbolRelocations.begin();
  663. StringRef Name = i->first();
  664. if (Name.size() == 0) {
  665. // This is an absolute symbol, use an address of zero.
  666. DEBUG(dbgs() << "Resolving absolute relocations."
  667. << "\n");
  668. RelocationList &Relocs = i->second;
  669. resolveRelocationList(Relocs, 0);
  670. } else {
  671. uint64_t Addr = 0;
  672. RTDyldSymbolTable::const_iterator Loc = GlobalSymbolTable.find(Name);
  673. if (Loc == GlobalSymbolTable.end()) {
  674. // This is an external symbol, try to get its address from the symbol
  675. // resolver.
  676. Addr = Resolver.findSymbol(Name.data()).getAddress();
  677. // The call to getSymbolAddress may have caused additional modules to
  678. // be loaded, which may have added new entries to the
  679. // ExternalSymbolRelocations map. Consquently, we need to update our
  680. // iterator. This is also why retrieval of the relocation list
  681. // associated with this symbol is deferred until below this point.
  682. // New entries may have been added to the relocation list.
  683. i = ExternalSymbolRelocations.find(Name);
  684. } else {
  685. // We found the symbol in our global table. It was probably in a
  686. // Module that we loaded previously.
  687. const auto &SymInfo = Loc->second;
  688. Addr = getSectionLoadAddress(SymInfo.getSectionID()) +
  689. SymInfo.getOffset();
  690. }
  691. // FIXME: Implement error handling that doesn't kill the host program!
  692. if (!Addr)
  693. report_fatal_error("Program used external function '" + Name +
  694. "' which could not be resolved!");
  695. // If Resolver returned UINT64_MAX, the client wants to handle this symbol
  696. // manually and we shouldn't resolve its relocations.
  697. if (Addr != UINT64_MAX) {
  698. DEBUG(dbgs() << "Resolving relocations Name: " << Name << "\t"
  699. << format("0x%lx", Addr) << "\n");
  700. // This list may have been updated when we called getSymbolAddress, so
  701. // don't change this code to get the list earlier.
  702. RelocationList &Relocs = i->second;
  703. resolveRelocationList(Relocs, Addr);
  704. }
  705. }
  706. ExternalSymbolRelocations.erase(i);
  707. }
  708. }
  709. //===----------------------------------------------------------------------===//
  710. // RuntimeDyld class implementation
  711. uint64_t RuntimeDyld::LoadedObjectInfo::getSectionLoadAddress(
  712. StringRef SectionName) const {
  713. for (unsigned I = BeginIdx; I != EndIdx; ++I)
  714. if (RTDyld.Sections[I].Name == SectionName)
  715. return RTDyld.Sections[I].LoadAddress;
  716. return 0;
  717. }
  718. void RuntimeDyld::MemoryManager::anchor() {}
  719. void RuntimeDyld::SymbolResolver::anchor() {}
  720. RuntimeDyld::RuntimeDyld(RuntimeDyld::MemoryManager &MemMgr,
  721. RuntimeDyld::SymbolResolver &Resolver)
  722. : MemMgr(MemMgr), Resolver(Resolver) {
  723. // FIXME: There's a potential issue lurking here if a single instance of
  724. // RuntimeDyld is used to load multiple objects. The current implementation
  725. // associates a single memory manager with a RuntimeDyld instance. Even
  726. // though the public class spawns a new 'impl' instance for each load,
  727. // they share a single memory manager. This can become a problem when page
  728. // permissions are applied.
  729. Dyld = nullptr;
  730. ProcessAllSections = false;
  731. Checker = nullptr;
  732. }
  733. RuntimeDyld::~RuntimeDyld() {}
  734. static std::unique_ptr<RuntimeDyldCOFF>
  735. createRuntimeDyldCOFF(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
  736. RuntimeDyld::SymbolResolver &Resolver,
  737. bool ProcessAllSections, RuntimeDyldCheckerImpl *Checker) {
  738. std::unique_ptr<RuntimeDyldCOFF> Dyld =
  739. RuntimeDyldCOFF::create(Arch, MM, Resolver);
  740. Dyld->setProcessAllSections(ProcessAllSections);
  741. Dyld->setRuntimeDyldChecker(Checker);
  742. return Dyld;
  743. }
  744. static std::unique_ptr<RuntimeDyldELF>
  745. createRuntimeDyldELF(RuntimeDyld::MemoryManager &MM,
  746. RuntimeDyld::SymbolResolver &Resolver,
  747. bool ProcessAllSections, RuntimeDyldCheckerImpl *Checker) {
  748. std::unique_ptr<RuntimeDyldELF> Dyld(new RuntimeDyldELF(MM, Resolver));
  749. Dyld->setProcessAllSections(ProcessAllSections);
  750. Dyld->setRuntimeDyldChecker(Checker);
  751. return Dyld;
  752. }
  753. static std::unique_ptr<RuntimeDyldMachO>
  754. createRuntimeDyldMachO(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MM,
  755. RuntimeDyld::SymbolResolver &Resolver,
  756. bool ProcessAllSections,
  757. RuntimeDyldCheckerImpl *Checker) {
  758. std::unique_ptr<RuntimeDyldMachO> Dyld =
  759. RuntimeDyldMachO::create(Arch, MM, Resolver);
  760. Dyld->setProcessAllSections(ProcessAllSections);
  761. Dyld->setRuntimeDyldChecker(Checker);
  762. return Dyld;
  763. }
  764. std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
  765. RuntimeDyld::loadObject(const ObjectFile &Obj) {
  766. if (!Dyld) {
  767. if (Obj.isELF())
  768. Dyld = createRuntimeDyldELF(MemMgr, Resolver, ProcessAllSections, Checker);
  769. else if (Obj.isMachO())
  770. Dyld = createRuntimeDyldMachO(
  771. static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
  772. ProcessAllSections, Checker);
  773. else if (Obj.isCOFF())
  774. Dyld = createRuntimeDyldCOFF(
  775. static_cast<Triple::ArchType>(Obj.getArch()), MemMgr, Resolver,
  776. ProcessAllSections, Checker);
  777. else
  778. report_fatal_error("Incompatible object format!");
  779. }
  780. if (!Dyld->isCompatibleFile(Obj))
  781. report_fatal_error("Incompatible object format!");
  782. return Dyld->loadObject(Obj);
  783. }
  784. void *RuntimeDyld::getSymbolLocalAddress(StringRef Name) const {
  785. if (!Dyld)
  786. return nullptr;
  787. return Dyld->getSymbolLocalAddress(Name);
  788. }
  789. RuntimeDyld::SymbolInfo RuntimeDyld::getSymbol(StringRef Name) const {
  790. if (!Dyld)
  791. return nullptr;
  792. return Dyld->getSymbol(Name);
  793. }
  794. void RuntimeDyld::resolveRelocations() { Dyld->resolveRelocations(); }
  795. void RuntimeDyld::reassignSectionAddress(unsigned SectionID, uint64_t Addr) {
  796. Dyld->reassignSectionAddress(SectionID, Addr);
  797. }
  798. void RuntimeDyld::mapSectionAddress(const void *LocalAddress,
  799. uint64_t TargetAddress) {
  800. Dyld->mapSectionAddress(LocalAddress, TargetAddress);
  801. }
  802. bool RuntimeDyld::hasError() { return Dyld->hasError(); }
  803. StringRef RuntimeDyld::getErrorString() { return Dyld->getErrorString(); }
  804. void RuntimeDyld::registerEHFrames() {
  805. if (Dyld)
  806. Dyld->registerEHFrames();
  807. }
  808. void RuntimeDyld::deregisterEHFrames() {
  809. if (Dyld)
  810. Dyld->deregisterEHFrames();
  811. }
  812. } // end namespace llvm