[MCJIT] Remove redundant architecture check from RuntimeDyldMachOI386.
[oota-llvm.git] / lib / ExecutionEngine / RuntimeDyld / Targets / RuntimeDyldMachOI386.h
1 //===---- RuntimeDyldMachOI386.h ---- MachO/I386 specific code. ---*- 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 #ifndef LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_TARGETS_RUNTIMEDYLDMACHOI386_H
11 #define LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_TARGETS_RUNTIMEDYLDMACHOI386_H
12
13 #include "../RuntimeDyldMachO.h"
14
15 #define DEBUG_TYPE "dyld"
16
17 namespace llvm {
18
19 class RuntimeDyldMachOI386
20     : public RuntimeDyldMachOCRTPBase<RuntimeDyldMachOI386> {
21 public:
22
23   typedef uint32_t TargetPtrT;
24
25   RuntimeDyldMachOI386(RTDyldMemoryManager *MM)
26       : RuntimeDyldMachOCRTPBase(MM) {}
27
28   unsigned getMaxStubSize() override { return 0; }
29
30   unsigned getStubAlignment() override { return 1; }
31
32   relocation_iterator
33   processRelocationRef(unsigned SectionID, relocation_iterator RelI,
34                        ObjectImage &ObjImg, ObjSectionToIDMap &ObjSectionToID,
35                        const SymbolTableMap &Symbols, StubMap &Stubs) override {
36     const MachOObjectFile &Obj =
37         static_cast<const MachOObjectFile &>(*ObjImg.getObjectFile());
38     MachO::any_relocation_info RelInfo =
39         Obj.getRelocation(RelI->getRawDataRefImpl());
40     uint32_t RelType = Obj.getAnyRelocationType(RelInfo);
41
42     if (Obj.isRelocationScattered(RelInfo)) {
43       if (RelType == MachO::GENERIC_RELOC_SECTDIFF ||
44           RelType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)
45         return processSECTDIFFRelocation(SectionID, RelI, ObjImg,
46                                          ObjSectionToID);
47       else if (RelType == MachO::GENERIC_RELOC_VANILLA)
48         return processI386ScatteredVANILLA(SectionID, RelI, ObjImg,
49                                            ObjSectionToID);
50       llvm_unreachable("Unhandled scattered relocation.");
51     }
52
53     RelocationEntry RE(getRelocationEntry(SectionID, ObjImg, RelI));
54     RE.Addend = memcpyAddend(RE);
55     RelocationValueRef Value(
56         getRelocationValueRef(ObjImg, RelI, RE, ObjSectionToID, Symbols));
57
58     // Addends for external, PC-rel relocations on i386 point back to the zero
59     // offset. Calculate the final offset from the relocation target instead.
60     // This allows us to use the same logic for both external and internal
61     // relocations in resolveI386RelocationRef.
62     // bool IsExtern = Obj.getPlainRelocationExternal(RelInfo);
63     // if (IsExtern && RE.IsPCRel) {
64     //   uint64_t RelocAddr = 0;
65     //   RelI->getAddress(RelocAddr);
66     //   Value.Addend += RelocAddr + 4;
67     // }
68     if (RE.IsPCRel)
69       makeValueAddendPCRel(Value, ObjImg, RelI, 1 << RE.Size);
70
71     RE.Addend = Value.Offset;
72
73     if (Value.SymbolName)
74       addRelocationForSymbol(RE, Value.SymbolName);
75     else
76       addRelocationForSection(RE, Value.SectionID);
77
78     return ++RelI;
79   }
80
81   void resolveRelocation(const RelocationEntry &RE, uint64_t Value) override {
82     DEBUG(dumpRelocationToResolve(RE, Value));
83
84     const SectionEntry &Section = Sections[RE.SectionID];
85     uint8_t *LocalAddress = Section.Address + RE.Offset;
86
87     if (RE.IsPCRel) {
88       uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
89       Value -= FinalAddress + 4; // see MachOX86_64::resolveRelocation.
90     }
91
92     switch (RE.RelType) {
93     default:
94       llvm_unreachable("Invalid relocation type!");
95     case MachO::GENERIC_RELOC_VANILLA:
96       writeBytesUnaligned(Value + RE.Addend, LocalAddress, 1 << RE.Size);
97       break;
98     case MachO::GENERIC_RELOC_SECTDIFF:
99     case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
100       uint64_t SectionABase = Sections[RE.Sections.SectionA].LoadAddress;
101       uint64_t SectionBBase = Sections[RE.Sections.SectionB].LoadAddress;
102       assert((Value == SectionABase || Value == SectionBBase) &&
103              "Unexpected SECTDIFF relocation value.");
104       Value = SectionABase - SectionBBase + RE.Addend;
105       writeBytesUnaligned(Value, LocalAddress, 1 << RE.Size);
106       break;
107     }
108     case MachO::GENERIC_RELOC_PB_LA_PTR:
109       Error("Relocation type not implemented yet!");
110     }
111   }
112
113   void finalizeSection(ObjectImage &ObjImg, unsigned SectionID,
114                        const SectionRef &Section) {
115     StringRef Name;
116     Section.getName(Name);
117
118     if (Name == "__jump_table")
119       populateJumpTable(cast<MachOObjectFile>(*ObjImg.getObjectFile()), Section,
120                         SectionID);
121     else if (Name == "__pointers")
122       populatePointersSection(cast<MachOObjectFile>(*ObjImg.getObjectFile()),
123                               Section, SectionID);
124   }
125
126 private:
127   relocation_iterator
128   processSECTDIFFRelocation(unsigned SectionID, relocation_iterator RelI,
129                             ObjectImage &Obj,
130                             ObjSectionToIDMap &ObjSectionToID) {
131     const MachOObjectFile *MachO =
132         static_cast<const MachOObjectFile *>(Obj.getObjectFile());
133     MachO::any_relocation_info RE =
134         MachO->getRelocation(RelI->getRawDataRefImpl());
135
136     SectionEntry &Section = Sections[SectionID];
137     uint32_t RelocType = MachO->getAnyRelocationType(RE);
138     bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
139     unsigned Size = MachO->getAnyRelocationLength(RE);
140     uint64_t Offset;
141     RelI->getOffset(Offset);
142     uint8_t *LocalAddress = Section.Address + Offset;
143     unsigned NumBytes = 1 << Size;
144     int64_t Addend = 0;
145     memcpy(&Addend, LocalAddress, NumBytes);
146
147     ++RelI;
148     MachO::any_relocation_info RE2 =
149         MachO->getRelocation(RelI->getRawDataRefImpl());
150
151     uint32_t AddrA = MachO->getScatteredRelocationValue(RE);
152     section_iterator SAI = getSectionByAddress(*MachO, AddrA);
153     assert(SAI != MachO->section_end() && "Can't find section for address A");
154     uint64_t SectionABase;
155     SAI->getAddress(SectionABase);
156     uint64_t SectionAOffset = AddrA - SectionABase;
157     SectionRef SectionA = *SAI;
158     bool IsCode;
159     SectionA.isText(IsCode);
160     uint32_t SectionAID =
161         findOrEmitSection(Obj, SectionA, IsCode, ObjSectionToID);
162
163     uint32_t AddrB = MachO->getScatteredRelocationValue(RE2);
164     section_iterator SBI = getSectionByAddress(*MachO, AddrB);
165     assert(SBI != MachO->section_end() && "Can't find section for address B");
166     uint64_t SectionBBase;
167     SBI->getAddress(SectionBBase);
168     uint64_t SectionBOffset = AddrB - SectionBBase;
169     SectionRef SectionB = *SBI;
170     uint32_t SectionBID =
171         findOrEmitSection(Obj, SectionB, IsCode, ObjSectionToID);
172
173     if (Addend != AddrA - AddrB)
174       Error("Unexpected SECTDIFF relocation addend.");
175
176     DEBUG(dbgs() << "Found SECTDIFF: AddrA: " << AddrA << ", AddrB: " << AddrB
177                  << ", Addend: " << Addend << ", SectionA ID: " << SectionAID
178                  << ", SectionAOffset: " << SectionAOffset
179                  << ", SectionB ID: " << SectionBID
180                  << ", SectionBOffset: " << SectionBOffset << "\n");
181     RelocationEntry R(SectionID, Offset, RelocType, 0, SectionAID,
182                       SectionAOffset, SectionBID, SectionBOffset, IsPCRel,
183                       Size);
184
185     addRelocationForSection(R, SectionAID);
186     addRelocationForSection(R, SectionBID);
187
188     return ++RelI;
189   }
190
191   relocation_iterator processI386ScatteredVANILLA(
192       unsigned SectionID, relocation_iterator RelI, ObjectImage &Obj,
193       RuntimeDyldMachO::ObjSectionToIDMap &ObjSectionToID) {
194     const MachOObjectFile *MachO =
195         static_cast<const MachOObjectFile *>(Obj.getObjectFile());
196     MachO::any_relocation_info RE =
197         MachO->getRelocation(RelI->getRawDataRefImpl());
198
199     SectionEntry &Section = Sections[SectionID];
200     uint32_t RelocType = MachO->getAnyRelocationType(RE);
201     bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
202     unsigned Size = MachO->getAnyRelocationLength(RE);
203     uint64_t Offset;
204     RelI->getOffset(Offset);
205     uint8_t *LocalAddress = Section.Address + Offset;
206     unsigned NumBytes = 1 << Size;
207     int64_t Addend = 0;
208     memcpy(&Addend, LocalAddress, NumBytes);
209
210     unsigned SymbolBaseAddr = MachO->getScatteredRelocationValue(RE);
211     section_iterator TargetSI = getSectionByAddress(*MachO, SymbolBaseAddr);
212     assert(TargetSI != MachO->section_end() && "Can't find section for symbol");
213     uint64_t SectionBaseAddr;
214     TargetSI->getAddress(SectionBaseAddr);
215     SectionRef TargetSection = *TargetSI;
216     bool IsCode;
217     TargetSection.isText(IsCode);
218     uint32_t TargetSectionID =
219         findOrEmitSection(Obj, TargetSection, IsCode, ObjSectionToID);
220
221     Addend -= SectionBaseAddr;
222     RelocationEntry R(SectionID, Offset, RelocType, Addend, IsPCRel, Size);
223
224     addRelocationForSection(R, TargetSectionID);
225
226     return ++RelI;
227   }
228
229   // Populate stubs in __jump_table section.
230   void populateJumpTable(MachOObjectFile &Obj, const SectionRef &JTSection,
231                          unsigned JTSectionID) {
232     assert(!Obj.is64Bit() &&
233            "__jump_table section not supported in 64-bit MachO.");
234
235     MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
236     MachO::section Sec32 = Obj.getSection(JTSection.getRawDataRefImpl());
237     uint32_t JTSectionSize = Sec32.size;
238     unsigned FirstIndirectSymbol = Sec32.reserved1;
239     unsigned JTEntrySize = Sec32.reserved2;
240     unsigned NumJTEntries = JTSectionSize / JTEntrySize;
241     uint8_t *JTSectionAddr = getSectionAddress(JTSectionID);
242     unsigned JTEntryOffset = 0;
243
244     assert((JTSectionSize % JTEntrySize) == 0 &&
245            "Jump-table section does not contain a whole number of stubs?");
246
247     for (unsigned i = 0; i < NumJTEntries; ++i) {
248       unsigned SymbolIndex =
249           Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
250       symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
251       StringRef IndirectSymbolName;
252       SI->getName(IndirectSymbolName);
253       uint8_t *JTEntryAddr = JTSectionAddr + JTEntryOffset;
254       createStubFunction(JTEntryAddr);
255       RelocationEntry RE(JTSectionID, JTEntryOffset + 1,
256                          MachO::GENERIC_RELOC_VANILLA, 0, true, 2);
257       addRelocationForSymbol(RE, IndirectSymbolName);
258       JTEntryOffset += JTEntrySize;
259     }
260   }
261
262   // Populate __pointers section.
263   void populatePointersSection(MachOObjectFile &Obj,
264                                const SectionRef &PTSection,
265                                unsigned PTSectionID) {
266     assert(!Obj.is64Bit() &&
267            "__pointers section not supported in 64-bit MachO.");
268
269     MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
270     MachO::section Sec32 = Obj.getSection(PTSection.getRawDataRefImpl());
271     uint32_t PTSectionSize = Sec32.size;
272     unsigned FirstIndirectSymbol = Sec32.reserved1;
273     const unsigned PTEntrySize = 4;
274     unsigned NumPTEntries = PTSectionSize / PTEntrySize;
275     unsigned PTEntryOffset = 0;
276
277     assert((PTSectionSize % PTEntrySize) == 0 &&
278            "Pointers section does not contain a whole number of stubs?");
279
280     DEBUG(dbgs() << "Populating __pointers, Section ID " << PTSectionID << ", "
281                  << NumPTEntries << " entries, " << PTEntrySize
282                  << " bytes each:\n");
283
284     for (unsigned i = 0; i < NumPTEntries; ++i) {
285       unsigned SymbolIndex =
286           Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
287       symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
288       StringRef IndirectSymbolName;
289       SI->getName(IndirectSymbolName);
290       DEBUG(dbgs() << "  " << IndirectSymbolName << ": index " << SymbolIndex
291                    << ", PT offset: " << PTEntryOffset << "\n");
292       RelocationEntry RE(PTSectionID, PTEntryOffset,
293                          MachO::GENERIC_RELOC_VANILLA, 0, false, 2);
294       addRelocationForSymbol(RE, IndirectSymbolName);
295       PTEntryOffset += PTEntrySize;
296     }
297   }
298
299   static section_iterator getSectionByAddress(const MachOObjectFile &Obj,
300                                               uint64_t Addr) {
301     section_iterator SI = Obj.section_begin();
302     section_iterator SE = Obj.section_end();
303
304     for (; SI != SE; ++SI) {
305       uint64_t SAddr, SSize;
306       SI->getAddress(SAddr);
307       SI->getSize(SSize);
308       if ((Addr >= SAddr) && (Addr < SAddr + SSize))
309         return SI;
310     }
311
312     return SE;
313   }
314 };
315 }
316
317 #undef DEBUG_TYPE
318
319 #endif