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