LLVM  6.0.0svn
RuntimeDyldMachOI386.h
Go to the documentation of this file.
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 #include <string>
15 
16 #define DEBUG_TYPE "dyld"
17 
18 namespace llvm {
19 
21  : public RuntimeDyldMachOCRTPBase<RuntimeDyldMachOI386> {
22 public:
23 
25 
28  : RuntimeDyldMachOCRTPBase(MM, Resolver) {}
29 
30  unsigned getMaxStubSize() override { return 0; }
31 
32  unsigned getStubAlignment() override { return 1; }
33 
35  processRelocationRef(unsigned SectionID, relocation_iterator RelI,
36  const ObjectFile &BaseObjT,
37  ObjSectionToIDMap &ObjSectionToID,
38  StubMap &Stubs) override {
39  const MachOObjectFile &Obj =
40  static_cast<const MachOObjectFile &>(BaseObjT);
42  Obj.getRelocation(RelI->getRawDataRefImpl());
43  uint32_t RelType = Obj.getAnyRelocationType(RelInfo);
44 
45  if (Obj.isRelocationScattered(RelInfo)) {
46  if (RelType == MachO::GENERIC_RELOC_SECTDIFF ||
48  return processSECTDIFFRelocation(SectionID, RelI, Obj,
49  ObjSectionToID);
50  else if (RelType == MachO::GENERIC_RELOC_VANILLA)
51  return processScatteredVANILLA(SectionID, RelI, Obj, ObjSectionToID);
52  return make_error<RuntimeDyldError>(("Unhandled I386 scattered relocation "
53  "type: " + Twine(RelType)).str());
54  }
55 
56  switch (RelType) {
60  default:
61  if (RelType > MachO::GENERIC_RELOC_TLV)
62  return make_error<RuntimeDyldError>(("MachO I386 relocation type " +
63  Twine(RelType) +
64  " is out of range").str());
65  break;
66  }
67 
68  RelocationEntry RE(getRelocationEntry(SectionID, Obj, RelI));
69  RE.Addend = memcpyAddend(RE);
71  if (auto ValueOrErr = getRelocationValueRef(Obj, RelI, RE, ObjSectionToID))
72  Value = *ValueOrErr;
73  else
74  return ValueOrErr.takeError();
75 
76  // Addends for external, PC-rel relocations on i386 point back to the zero
77  // offset. Calculate the final offset from the relocation target instead.
78  // This allows us to use the same logic for both external and internal
79  // relocations in resolveI386RelocationRef.
80  // bool IsExtern = Obj.getPlainRelocationExternal(RelInfo);
81  // if (IsExtern && RE.IsPCRel) {
82  // uint64_t RelocAddr = 0;
83  // RelI->getAddress(RelocAddr);
84  // Value.Addend += RelocAddr + 4;
85  // }
86  if (RE.IsPCRel)
87  makeValueAddendPCRel(Value, RelI, 1 << RE.Size);
88 
89  RE.Addend = Value.Offset;
90 
91  if (Value.SymbolName)
93  else
95 
96  return ++RelI;
97  }
98 
99  void resolveRelocation(const RelocationEntry &RE, uint64_t Value) override {
100  DEBUG(dumpRelocationToResolve(RE, Value));
101 
102  const SectionEntry &Section = Sections[RE.SectionID];
103  uint8_t *LocalAddress = Section.getAddressWithOffset(RE.Offset);
104 
105  if (RE.IsPCRel) {
106  uint64_t FinalAddress = Section.getLoadAddressWithOffset(RE.Offset);
107  Value -= FinalAddress + 4; // see MachOX86_64::resolveRelocation.
108  }
109 
110  switch (RE.RelType) {
112  writeBytesUnaligned(Value + RE.Addend, LocalAddress, 1 << RE.Size);
113  break;
116  uint64_t SectionABase = Sections[RE.Sections.SectionA].getLoadAddress();
117  uint64_t SectionBBase = Sections[RE.Sections.SectionB].getLoadAddress();
118  assert((Value == SectionABase || Value == SectionBBase) &&
119  "Unexpected SECTDIFF relocation value.");
120  Value = SectionABase - SectionBBase + RE.Addend;
121  writeBytesUnaligned(Value, LocalAddress, 1 << RE.Size);
122  break;
123  }
124  default:
125  llvm_unreachable("Invalid relocation type!");
126  }
127  }
128 
129  Error finalizeSection(const ObjectFile &Obj, unsigned SectionID,
130  const SectionRef &Section) {
131  StringRef Name;
132  Section.getName(Name);
133 
134  if (Name == "__jump_table")
135  return populateJumpTable(cast<MachOObjectFile>(Obj), Section, SectionID);
136  else if (Name == "__pointers")
137  return populateIndirectSymbolPointersSection(cast<MachOObjectFile>(Obj),
138  Section, SectionID);
139  return Error::success();
140  }
141 
142 private:
144  processSECTDIFFRelocation(unsigned SectionID, relocation_iterator RelI,
145  const ObjectFile &BaseObjT,
146  ObjSectionToIDMap &ObjSectionToID) {
147  const MachOObjectFile &Obj =
148  static_cast<const MachOObjectFile&>(BaseObjT);
150  Obj.getRelocation(RelI->getRawDataRefImpl());
151 
152  SectionEntry &Section = Sections[SectionID];
153  uint32_t RelocType = Obj.getAnyRelocationType(RE);
154  bool IsPCRel = Obj.getAnyRelocationPCRel(RE);
155  unsigned Size = Obj.getAnyRelocationLength(RE);
156  uint64_t Offset = RelI->getOffset();
157  uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
158  unsigned NumBytes = 1 << Size;
159  uint64_t Addend = readBytesUnaligned(LocalAddress, NumBytes);
160 
161  ++RelI;
163  Obj.getRelocation(RelI->getRawDataRefImpl());
164 
165  uint32_t AddrA = Obj.getScatteredRelocationValue(RE);
166  section_iterator SAI = getSectionByAddress(Obj, AddrA);
167  assert(SAI != Obj.section_end() && "Can't find section for address A");
168  uint64_t SectionABase = SAI->getAddress();
169  uint64_t SectionAOffset = AddrA - SectionABase;
170  SectionRef SectionA = *SAI;
171  bool IsCode = SectionA.isText();
172  uint32_t SectionAID = ~0U;
173  if (auto SectionAIDOrErr =
174  findOrEmitSection(Obj, SectionA, IsCode, ObjSectionToID))
175  SectionAID = *SectionAIDOrErr;
176  else
177  return SectionAIDOrErr.takeError();
178 
179  uint32_t AddrB = Obj.getScatteredRelocationValue(RE2);
180  section_iterator SBI = getSectionByAddress(Obj, AddrB);
181  assert(SBI != Obj.section_end() && "Can't find section for address B");
182  uint64_t SectionBBase = SBI->getAddress();
183  uint64_t SectionBOffset = AddrB - SectionBBase;
184  SectionRef SectionB = *SBI;
185  uint32_t SectionBID = ~0U;
186  if (auto SectionBIDOrErr =
187  findOrEmitSection(Obj, SectionB, IsCode, ObjSectionToID))
188  SectionBID = *SectionBIDOrErr;
189  else
190  return SectionBIDOrErr.takeError();
191 
192  // Compute the addend 'C' from the original expression 'A - B + C'.
193  Addend -= AddrA - AddrB;
194 
195  DEBUG(dbgs() << "Found SECTDIFF: AddrA: " << AddrA << ", AddrB: " << AddrB
196  << ", Addend: " << Addend << ", SectionA ID: " << SectionAID
197  << ", SectionAOffset: " << SectionAOffset
198  << ", SectionB ID: " << SectionBID
199  << ", SectionBOffset: " << SectionBOffset << "\n");
200  RelocationEntry R(SectionID, Offset, RelocType, Addend, SectionAID,
201  SectionAOffset, SectionBID, SectionBOffset,
202  IsPCRel, Size);
203 
204  addRelocationForSection(R, SectionAID);
205 
206  return ++RelI;
207  }
208 
209  // Populate stubs in __jump_table section.
210  Error populateJumpTable(const MachOObjectFile &Obj,
211  const SectionRef &JTSection,
212  unsigned JTSectionID) {
214  MachO::section Sec32 = Obj.getSection(JTSection.getRawDataRefImpl());
215  uint32_t JTSectionSize = Sec32.size;
216  unsigned FirstIndirectSymbol = Sec32.reserved1;
217  unsigned JTEntrySize = Sec32.reserved2;
218  unsigned NumJTEntries = JTSectionSize / JTEntrySize;
219  uint8_t *JTSectionAddr = getSectionAddress(JTSectionID);
220  unsigned JTEntryOffset = 0;
221 
222  if (JTSectionSize % JTEntrySize != 0)
223  return make_error<RuntimeDyldError>("Jump-table section does not contain "
224  "a whole number of stubs?");
225 
226  for (unsigned i = 0; i < NumJTEntries; ++i) {
227  unsigned SymbolIndex =
228  Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
229  symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
230  Expected<StringRef> IndirectSymbolName = SI->getName();
231  if (!IndirectSymbolName)
232  return IndirectSymbolName.takeError();
233  uint8_t *JTEntryAddr = JTSectionAddr + JTEntryOffset;
234  createStubFunction(JTEntryAddr);
235  RelocationEntry RE(JTSectionID, JTEntryOffset + 1,
236  MachO::GENERIC_RELOC_VANILLA, 0, true, 2);
237  addRelocationForSymbol(RE, *IndirectSymbolName);
238  JTEntryOffset += JTEntrySize;
239  }
240 
241  return Error::success();
242  }
243 
244 };
245 }
246 
247 #undef DEBUG_TYPE
248 
249 #endif
RelocationEntry - used to represent relocations internally in the dynamic linker. ...
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
Expected< StringRef > getName() const
Definition: ObjectFile.h:343
unsigned getAnyRelocationPCRel(const MachO::any_relocation_info &RE) const
uint64_t readBytesUnaligned(uint8_t *Src, unsigned Size) const
Endian-aware read Read the least significant Size bytes from Src.
uint64_t getLoadAddressWithOffset(unsigned OffsetBytes) const
Return the load address of this section with an offset.
void resolveRelocation(const RelocationEntry &RE, uint64_t Value) override
A object file specific relocation resolver.
uint32_t reserved1
Definition: MachO.h:561
void dumpRelocationToResolve(const RelocationEntry &RE, uint64_t Value) const
Dump information about the relocation entry (RE) and resolved value.
This class is the base class for all object file types.
Definition: ObjectFile.h:189
uint32_t size
Definition: MachO.h:555
Error takeError()
Take ownership of the stored error.
Definition: Error.h:537
unsigned getMaxStubSize() override
void writeBytesUnaligned(uint64_t Value, uint8_t *Dst, unsigned Size) const
Endian-aware write.
bool IsPCRel
True if this is a PCRel relocation (MachO specific).
unsigned SectionID
SectionID - the section this relocation points to.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
std::map< RelocationValueRef, uintptr_t > StubMap
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
int64_t memcpyAddend(const RelocationEntry &RE) const
This convenience method uses memcpy to extract a contiguous addend (the addend size and offset are ta...
unsigned getAnyRelocationType(const MachO::any_relocation_info &RE) const
RuntimeDyldMachOTarget - Templated base class for generic MachO linker algorithms and data structures...
Expected< RelocationValueRef > getRelocationValueRef(const ObjectFile &BaseTObj, const relocation_iterator &RI, const RelocationEntry &RE, ObjSectionToIDMap &ObjSectionToID)
Construct a RelocationValueRef representing the relocation target.
void addRelocationForSymbol(const RelocationEntry &RE, StringRef SymbolName)
RelocationEntry getRelocationEntry(unsigned SectionID, const ObjectFile &BaseTObj, const relocation_iterator &RI) const
Given a relocation_iterator for a non-scattered relocation, construct a RelocationEntry and fill in t...
basic_symbol_iterator getSymbolByIndex(unsigned Index) const
void addRelocationForSection(const RelocationEntry &RE, unsigned SectionID)
MachO::any_relocation_info getRelocation(DataRefImpl Rel) const
Symbol resolution.
Definition: JITSymbol.h:260
Expected< unsigned > findOrEmitSection(const ObjectFile &Obj, const SectionRef &Section, bool IsCode, ObjSectionToIDMap &LocalSections)
Find Section in LocalSections.
uint8_t * getSectionAddress(unsigned SectionID) const
DataRefImpl getRawDataRefImpl() const
Definition: ObjectFile.h:462
static section_iterator getSectionByAddress(const MachOObjectFile &Obj, uint64_t Addr)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isRelocationScattered(const MachO::any_relocation_info &RE) const
MachO::section getSection(DataRefImpl DRI) const
static ErrorSuccess success()
Create a success value.
Definition: Error.h:313
RuntimeDyldMachOI386(RuntimeDyld::MemoryManager &MM, JITSymbolResolver &Resolver)
Expected< relocation_iterator > processRelocationRef(unsigned SectionID, relocation_iterator RelI, const ObjectFile &BaseObjT, ObjSectionToIDMap &ObjSectionToID, StubMap &Stubs) override
Parses one or more object file relocations (some object files use relocation pairs) and stores it to ...
int64_t Addend
Addend - the relocation addend encoded in the instruction itself.
std::error_code getName(StringRef &Result) const
Definition: ObjectFile.h:398
uint32_t RelType
RelType - relocation type.
JITSymbolResolver & Resolver
Expected< relocation_iterator > processScatteredVANILLA(unsigned SectionID, relocation_iterator RelI, const ObjectFile &BaseObjT, RuntimeDyldMachO::ObjSectionToIDMap &ObjSectionToID, bool TargetIsLocalThumbFunc=false)
Process a scattered vanilla relocation.
uint8_t * createStubFunction(uint8_t *Addr, unsigned AbiVariant=0)
Emits long jump instruction to Addr.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
unsigned getAnyRelocationLength(const MachO::any_relocation_info &RE) const
uint64_t Offset
Offset - offset into the section.
std::map< SectionRef, unsigned > ObjSectionToIDMap
uint8_t * getAddressWithOffset(unsigned OffsetBytes) const
Return the address of this section with an offset.
unsigned getStubAlignment() override
SectionEntry - represents a section emitted into memory by the dynamic linker.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
unsigned Size
The size of this relocation (MachO specific).
section_iterator section_end() const override
#define UNIMPLEMENTED_RELOC(RelType)
#define DEBUG(X)
Definition: Debug.h:118
Error populateIndirectSymbolPointersSection(const MachOObjectFile &Obj, const SectionRef &PTSection, unsigned PTSectionID)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
uint32_t reserved2
Definition: MachO.h:562
void makeValueAddendPCRel(RelocationValueRef &Value, const relocation_iterator &RI, unsigned OffsetToNextPC)
Make the RelocationValueRef addend PC-relative.
uint32_t getIndirectSymbolTableEntry(const MachO::dysymtab_command &DLC, unsigned Index) const
uint32_t getScatteredRelocationValue(const MachO::any_relocation_info &RE) const
Error finalizeSection(const ObjectFile &Obj, unsigned SectionID, const SectionRef &Section)
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:80
MachO::dysymtab_command getDysymtabLoadCommand() const