RuntimeDyldMachO.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. //===-- RuntimeDyldMachO.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 "RuntimeDyldMachO.h"
  14. #include "Targets/RuntimeDyldMachOAArch64.h"
  15. #include "Targets/RuntimeDyldMachOARM.h"
  16. #include "Targets/RuntimeDyldMachOI386.h"
  17. #include "Targets/RuntimeDyldMachOX86_64.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/ADT/StringRef.h"
  20. using namespace llvm;
  21. using namespace llvm::object;
  22. #define DEBUG_TYPE "dyld"
  23. namespace {
  24. class LoadedMachOObjectInfo
  25. : public RuntimeDyld::LoadedObjectInfoHelper<LoadedMachOObjectInfo> {
  26. public:
  27. LoadedMachOObjectInfo(RuntimeDyldImpl &RTDyld, unsigned BeginIdx,
  28. unsigned EndIdx)
  29. : LoadedObjectInfoHelper(RTDyld, BeginIdx, EndIdx) {}
  30. OwningBinary<ObjectFile>
  31. getObjectForDebug(const ObjectFile &Obj) const override {
  32. return OwningBinary<ObjectFile>();
  33. }
  34. };
  35. }
  36. namespace llvm {
  37. int64_t RuntimeDyldMachO::memcpyAddend(const RelocationEntry &RE) const {
  38. unsigned NumBytes = 1 << RE.Size;
  39. uint8_t *Src = Sections[RE.SectionID].Address + RE.Offset;
  40. return static_cast<int64_t>(readBytesUnaligned(Src, NumBytes));
  41. }
  42. RelocationValueRef RuntimeDyldMachO::getRelocationValueRef(
  43. const ObjectFile &BaseTObj, const relocation_iterator &RI,
  44. const RelocationEntry &RE, ObjSectionToIDMap &ObjSectionToID) {
  45. const MachOObjectFile &Obj =
  46. static_cast<const MachOObjectFile &>(BaseTObj);
  47. MachO::any_relocation_info RelInfo =
  48. Obj.getRelocation(RI->getRawDataRefImpl());
  49. RelocationValueRef Value;
  50. bool IsExternal = Obj.getPlainRelocationExternal(RelInfo);
  51. if (IsExternal) {
  52. symbol_iterator Symbol = RI->getSymbol();
  53. ErrorOr<StringRef> TargetNameOrErr = Symbol->getName();
  54. if (std::error_code EC = TargetNameOrErr.getError())
  55. report_fatal_error(EC.message());
  56. StringRef TargetName = *TargetNameOrErr;
  57. RTDyldSymbolTable::const_iterator SI =
  58. GlobalSymbolTable.find(TargetName.data());
  59. if (SI != GlobalSymbolTable.end()) {
  60. const auto &SymInfo = SI->second;
  61. Value.SectionID = SymInfo.getSectionID();
  62. Value.Offset = SymInfo.getOffset() + RE.Addend;
  63. } else {
  64. Value.SymbolName = TargetName.data();
  65. Value.Offset = RE.Addend;
  66. }
  67. } else {
  68. SectionRef Sec = Obj.getAnyRelocationSection(RelInfo);
  69. bool IsCode = Sec.isText();
  70. Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
  71. uint64_t Addr = Sec.getAddress();
  72. Value.Offset = RE.Addend - Addr;
  73. }
  74. return Value;
  75. }
  76. void RuntimeDyldMachO::makeValueAddendPCRel(RelocationValueRef &Value,
  77. const relocation_iterator &RI,
  78. unsigned OffsetToNextPC) {
  79. auto &O = *cast<MachOObjectFile>(RI->getObject());
  80. section_iterator SecI = O.getRelocationRelocatedSection(RI);
  81. Value.Offset += RI->getOffset() + OffsetToNextPC + SecI->getAddress();
  82. }
  83. void RuntimeDyldMachO::dumpRelocationToResolve(const RelocationEntry &RE,
  84. uint64_t Value) const {
  85. const SectionEntry &Section = Sections[RE.SectionID];
  86. uint8_t *LocalAddress = Section.Address + RE.Offset;
  87. uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
  88. dbgs() << "resolveRelocation Section: " << RE.SectionID
  89. << " LocalAddress: " << format("%p", LocalAddress)
  90. << " FinalAddress: " << format("0x%016" PRIx64, FinalAddress)
  91. << " Value: " << format("0x%016" PRIx64, Value) << " Addend: " << RE.Addend
  92. << " isPCRel: " << RE.IsPCRel << " MachoType: " << RE.RelType
  93. << " Size: " << (1 << RE.Size) << "\n";
  94. }
  95. section_iterator
  96. RuntimeDyldMachO::getSectionByAddress(const MachOObjectFile &Obj,
  97. uint64_t Addr) {
  98. section_iterator SI = Obj.section_begin();
  99. section_iterator SE = Obj.section_end();
  100. for (; SI != SE; ++SI) {
  101. uint64_t SAddr = SI->getAddress();
  102. uint64_t SSize = SI->getSize();
  103. if ((Addr >= SAddr) && (Addr < SAddr + SSize))
  104. return SI;
  105. }
  106. return SE;
  107. }
  108. // Populate __pointers section.
  109. void RuntimeDyldMachO::populateIndirectSymbolPointersSection(
  110. const MachOObjectFile &Obj,
  111. const SectionRef &PTSection,
  112. unsigned PTSectionID) {
  113. assert(!Obj.is64Bit() &&
  114. "Pointer table section not supported in 64-bit MachO.");
  115. MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
  116. MachO::section Sec32 = Obj.getSection(PTSection.getRawDataRefImpl());
  117. uint32_t PTSectionSize = Sec32.size;
  118. unsigned FirstIndirectSymbol = Sec32.reserved1;
  119. const unsigned PTEntrySize = 4;
  120. unsigned NumPTEntries = PTSectionSize / PTEntrySize;
  121. unsigned PTEntryOffset = 0;
  122. assert((PTSectionSize % PTEntrySize) == 0 &&
  123. "Pointers section does not contain a whole number of stubs?");
  124. DEBUG(dbgs() << "Populating pointer table section "
  125. << Sections[PTSectionID].Name
  126. << ", Section ID " << PTSectionID << ", "
  127. << NumPTEntries << " entries, " << PTEntrySize
  128. << " bytes each:\n");
  129. for (unsigned i = 0; i < NumPTEntries; ++i) {
  130. unsigned SymbolIndex =
  131. Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
  132. symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
  133. ErrorOr<StringRef> IndirectSymbolNameOrErr = SI->getName();
  134. if (std::error_code EC = IndirectSymbolNameOrErr.getError())
  135. report_fatal_error(EC.message());
  136. StringRef IndirectSymbolName = *IndirectSymbolNameOrErr;
  137. DEBUG(dbgs() << " " << IndirectSymbolName << ": index " << SymbolIndex
  138. << ", PT offset: " << PTEntryOffset << "\n");
  139. RelocationEntry RE(PTSectionID, PTEntryOffset,
  140. MachO::GENERIC_RELOC_VANILLA, 0, false, 2);
  141. addRelocationForSymbol(RE, IndirectSymbolName);
  142. PTEntryOffset += PTEntrySize;
  143. }
  144. }
  145. bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile &Obj) const {
  146. return Obj.isMachO();
  147. }
  148. template <typename Impl>
  149. void RuntimeDyldMachOCRTPBase<Impl>::finalizeLoad(const ObjectFile &Obj,
  150. ObjSectionToIDMap &SectionMap) {
  151. unsigned EHFrameSID = RTDYLD_INVALID_SECTION_ID;
  152. unsigned TextSID = RTDYLD_INVALID_SECTION_ID;
  153. unsigned ExceptTabSID = RTDYLD_INVALID_SECTION_ID;
  154. for (const auto &Section : Obj.sections()) {
  155. StringRef Name;
  156. Section.getName(Name);
  157. // Force emission of the __text, __eh_frame, and __gcc_except_tab sections
  158. // if they're present. Otherwise call down to the impl to handle other
  159. // sections that have already been emitted.
  160. if (Name == "__text")
  161. TextSID = findOrEmitSection(Obj, Section, true, SectionMap);
  162. else if (Name == "__eh_frame")
  163. EHFrameSID = findOrEmitSection(Obj, Section, false, SectionMap);
  164. else if (Name == "__gcc_except_tab")
  165. ExceptTabSID = findOrEmitSection(Obj, Section, true, SectionMap);
  166. else {
  167. auto I = SectionMap.find(Section);
  168. if (I != SectionMap.end())
  169. impl().finalizeSection(Obj, I->second, Section);
  170. }
  171. }
  172. UnregisteredEHFrameSections.push_back(
  173. EHFrameRelatedSections(EHFrameSID, TextSID, ExceptTabSID));
  174. }
  175. template <typename Impl>
  176. unsigned char *RuntimeDyldMachOCRTPBase<Impl>::processFDE(unsigned char *P,
  177. int64_t DeltaForText,
  178. int64_t DeltaForEH) {
  179. typedef typename Impl::TargetPtrT TargetPtrT;
  180. DEBUG(dbgs() << "Processing FDE: Delta for text: " << DeltaForText
  181. << ", Delta for EH: " << DeltaForEH << "\n");
  182. uint32_t Length = readBytesUnaligned(P, 4);
  183. P += 4;
  184. unsigned char *Ret = P + Length;
  185. uint32_t Offset = readBytesUnaligned(P, 4);
  186. if (Offset == 0) // is a CIE
  187. return Ret;
  188. P += 4;
  189. TargetPtrT FDELocation = readBytesUnaligned(P, sizeof(TargetPtrT));
  190. TargetPtrT NewLocation = FDELocation - DeltaForText;
  191. writeBytesUnaligned(NewLocation, P, sizeof(TargetPtrT));
  192. P += sizeof(TargetPtrT);
  193. // Skip the FDE address range
  194. P += sizeof(TargetPtrT);
  195. uint8_t Augmentationsize = *P;
  196. P += 1;
  197. if (Augmentationsize != 0) {
  198. TargetPtrT LSDA = readBytesUnaligned(P, sizeof(TargetPtrT));
  199. TargetPtrT NewLSDA = LSDA - DeltaForEH;
  200. writeBytesUnaligned(NewLSDA, P, sizeof(TargetPtrT));
  201. }
  202. return Ret;
  203. }
  204. static int64_t computeDelta(SectionEntry *A, SectionEntry *B) {
  205. int64_t ObjDistance =
  206. static_cast<int64_t>(A->ObjAddress) - static_cast<int64_t>(B->ObjAddress);
  207. int64_t MemDistance = A->LoadAddress - B->LoadAddress;
  208. return ObjDistance - MemDistance;
  209. }
  210. template <typename Impl>
  211. void RuntimeDyldMachOCRTPBase<Impl>::registerEHFrames() {
  212. for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
  213. EHFrameRelatedSections &SectionInfo = UnregisteredEHFrameSections[i];
  214. if (SectionInfo.EHFrameSID == RTDYLD_INVALID_SECTION_ID ||
  215. SectionInfo.TextSID == RTDYLD_INVALID_SECTION_ID)
  216. continue;
  217. SectionEntry *Text = &Sections[SectionInfo.TextSID];
  218. SectionEntry *EHFrame = &Sections[SectionInfo.EHFrameSID];
  219. SectionEntry *ExceptTab = nullptr;
  220. if (SectionInfo.ExceptTabSID != RTDYLD_INVALID_SECTION_ID)
  221. ExceptTab = &Sections[SectionInfo.ExceptTabSID];
  222. int64_t DeltaForText = computeDelta(Text, EHFrame);
  223. int64_t DeltaForEH = 0;
  224. if (ExceptTab)
  225. DeltaForEH = computeDelta(ExceptTab, EHFrame);
  226. unsigned char *P = EHFrame->Address;
  227. unsigned char *End = P + EHFrame->Size;
  228. do {
  229. P = processFDE(P, DeltaForText, DeltaForEH);
  230. } while (P != End);
  231. MemMgr.registerEHFrames(EHFrame->Address, EHFrame->LoadAddress,
  232. EHFrame->Size);
  233. }
  234. UnregisteredEHFrameSections.clear();
  235. }
  236. std::unique_ptr<RuntimeDyldMachO>
  237. RuntimeDyldMachO::create(Triple::ArchType Arch,
  238. RuntimeDyld::MemoryManager &MemMgr,
  239. RuntimeDyld::SymbolResolver &Resolver) {
  240. switch (Arch) {
  241. default:
  242. llvm_unreachable("Unsupported target for RuntimeDyldMachO.");
  243. break;
  244. case Triple::arm:
  245. return make_unique<RuntimeDyldMachOARM>(MemMgr, Resolver);
  246. case Triple::aarch64:
  247. return make_unique<RuntimeDyldMachOAArch64>(MemMgr, Resolver);
  248. case Triple::x86:
  249. return make_unique<RuntimeDyldMachOI386>(MemMgr, Resolver);
  250. case Triple::x86_64:
  251. return make_unique<RuntimeDyldMachOX86_64>(MemMgr, Resolver);
  252. }
  253. }
  254. std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
  255. RuntimeDyldMachO::loadObject(const object::ObjectFile &O) {
  256. unsigned SectionStartIdx, SectionEndIdx;
  257. std::tie(SectionStartIdx, SectionEndIdx) = loadObjectImpl(O);
  258. return llvm::make_unique<LoadedMachOObjectInfo>(*this, SectionStartIdx,
  259. SectionEndIdx);
  260. }
  261. } // end namespace llvm