LLVM  6.0.0svn
RuntimeDyldMachOARM.h
Go to the documentation of this file.
1 //===----- RuntimeDyldMachOARM.h ---- MachO/ARM 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_RUNTIMEDYLDMACHOARM_H
11 #define LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_TARGETS_RUNTIMEDYLDMACHOARM_H
12 
13 #include "../RuntimeDyldMachO.h"
14 #include <string>
15 
16 #define DEBUG_TYPE "dyld"
17 
18 namespace llvm {
19 
21  : public RuntimeDyldMachOCRTPBase<RuntimeDyldMachOARM> {
22 private:
24 
25 public:
26 
28 
31  : RuntimeDyldMachOCRTPBase(MM, Resolver) {}
32 
33  unsigned getMaxStubSize() override { return 8; }
34 
35  unsigned getStubAlignment() override { return 4; }
36 
38  auto Flags = RuntimeDyldImpl::getJITSymbolFlags(SR);
39  Flags.getTargetFlags() = ARMJITSymbolFlags::fromObjectSymbol(SR);
40  return Flags;
41  }
42 
43  uint64_t modifyAddressBasedOnFlags(uint64_t Addr,
44  JITSymbolFlags Flags) const override {
46  Addr |= 0x1;
47  return Addr;
48  }
49 
52  uint8_t *LocalAddress = Section.getAddressWithOffset(RE.Offset);
53 
54  switch (RE.RelType) {
55  default:
56  return memcpyAddend(RE);
57  case MachO::ARM_RELOC_BR24: {
58  uint32_t Temp = readBytesUnaligned(LocalAddress, 4);
59  Temp &= 0x00ffffff; // Mask out the opcode.
60  // Now we've got the shifted immediate, shift by 2, sign extend and ret.
61  return SignExtend32<26>(Temp << 2);
62  }
63 
65  // This is a pair of instructions whose operands combine to provide 22
66  // bits of displacement:
67  // Encoding for high bits 1111 0XXX XXXX XXXX
68  // Encoding for low bits 1111 1XXX XXXX XXXX
69  uint16_t HighInsn = readBytesUnaligned(LocalAddress, 2);
70  if ((HighInsn & 0xf800) != 0xf000)
71  return make_error<StringError>("Unrecognized thumb branch encoding "
72  "(BR22 high bits)",
74 
75  uint16_t LowInsn = readBytesUnaligned(LocalAddress + 2, 2);
76  if ((LowInsn & 0xf800) != 0xf800)
77  return make_error<StringError>("Unrecognized thumb branch encoding "
78  "(BR22 low bits)",
80 
81  return SignExtend64<23>(((HighInsn & 0x7ff) << 12) |
82  ((LowInsn & 0x7ff) << 1));
83  }
84  }
85  }
86 
88  processRelocationRef(unsigned SectionID, relocation_iterator RelI,
89  const ObjectFile &BaseObjT,
90  ObjSectionToIDMap &ObjSectionToID,
91  StubMap &Stubs) override {
92  const MachOObjectFile &Obj =
93  static_cast<const MachOObjectFile &>(BaseObjT);
95  Obj.getRelocation(RelI->getRawDataRefImpl());
96  uint32_t RelType = Obj.getAnyRelocationType(RelInfo);
97 
98  // Set to true for thumb functions in this (or previous) TUs.
99  // Will be used to set the TargetIsThumbFunc member on the relocation entry.
100  bool TargetIsLocalThumbFunc = false;
101  if (Obj.getPlainRelocationExternal(RelInfo)) {
102  auto Symbol = RelI->getSymbol();
103  StringRef TargetName;
104  if (auto TargetNameOrErr = Symbol->getName())
105  TargetName = *TargetNameOrErr;
106  else
107  return TargetNameOrErr.takeError();
108 
109  // If the target is external but the value doesn't have a name then we've
110  // converted the value to a section/offset pair, but we still need to set
111  // the IsTargetThumbFunc bit, so look the value up in the globla symbol table.
112  auto EntryItr = GlobalSymbolTable.find(TargetName);
113  if (EntryItr != GlobalSymbolTable.end()) {
114  TargetIsLocalThumbFunc =
115  EntryItr->second.getFlags().getTargetFlags() &
117  }
118  }
119 
120  if (Obj.isRelocationScattered(RelInfo)) {
121  if (RelType == MachO::ARM_RELOC_HALF_SECTDIFF)
122  return processHALFSECTDIFFRelocation(SectionID, RelI, Obj,
123  ObjSectionToID);
124  else if (RelType == MachO::GENERIC_RELOC_VANILLA)
125  return processScatteredVANILLA(SectionID, RelI, Obj, ObjSectionToID,
126  TargetIsLocalThumbFunc);
127  else
128  return ++RelI;
129  }
130 
131  // Sanity check relocation type.
132  switch (RelType) {
139  default:
140  if (RelType > MachO::ARM_RELOC_HALF_SECTDIFF)
141  return make_error<RuntimeDyldError>(("MachO ARM relocation type " +
142  Twine(RelType) +
143  " is out of range").str());
144  break;
145  }
146 
147  RelocationEntry RE(getRelocationEntry(SectionID, Obj, RelI));
148  if (auto AddendOrErr = decodeAddend(RE))
149  RE.Addend = *AddendOrErr;
150  else
151  return AddendOrErr.takeError();
152  RE.IsTargetThumbFunc = TargetIsLocalThumbFunc;
153 
155  if (auto ValueOrErr = getRelocationValueRef(Obj, RelI, RE, ObjSectionToID))
156  Value = *ValueOrErr;
157  else
158  return ValueOrErr.takeError();
159 
160  // If this is a branch from a thumb function (BR22) then make sure we mark
161  // the value as being a thumb stub: we don't want to mix it up with an ARM
162  // stub targeting the same function.
164  Value.IsStubThumb = TargetIsLocalThumbFunc;
165 
166  if (RE.IsPCRel)
167  makeValueAddendPCRel(Value, RelI,
168  (RE.RelType == MachO::ARM_THUMB_RELOC_BR22) ? 4 : 8);
169 
170  if (RE.RelType == MachO::ARM_RELOC_BR24 ||
172  processBranchRelocation(RE, Value, Stubs);
173  else {
174  RE.Addend = Value.Offset;
175  if (Value.SymbolName)
177  else
179  }
180 
181  return ++RelI;
182  }
183 
184  void resolveRelocation(const RelocationEntry &RE, uint64_t Value) override {
185  DEBUG(dumpRelocationToResolve(RE, Value));
186  const SectionEntry &Section = Sections[RE.SectionID];
187  uint8_t *LocalAddress = Section.getAddressWithOffset(RE.Offset);
188 
189  // If the relocation is PC-relative, the value to be encoded is the
190  // pointer difference.
191  if (RE.IsPCRel) {
192  uint64_t FinalAddress = Section.getLoadAddressWithOffset(RE.Offset);
193  Value -= FinalAddress;
194  // ARM PCRel relocations have an effective-PC offset of two instructions
195  // (four bytes in Thumb mode, 8 bytes in ARM mode).
196  Value -= (RE.RelType == MachO::ARM_THUMB_RELOC_BR22) ? 4 : 8;
197  }
198 
199  switch (RE.RelType) {
201  Value += RE.Addend;
202  uint16_t HighInsn = readBytesUnaligned(LocalAddress, 2);
203  assert((HighInsn & 0xf800) == 0xf000 &&
204  "Unrecognized thumb branch encoding (BR22 high bits)");
205  HighInsn = (HighInsn & 0xf800) | ((Value >> 12) & 0x7ff);
206 
207  uint16_t LowInsn = readBytesUnaligned(LocalAddress + 2, 2);
208  assert((LowInsn & 0xf800) != 0xf8000 &&
209  "Unrecognized thumb branch encoding (BR22 low bits)");
210  LowInsn = (LowInsn & 0xf800) | ((Value >> 1) & 0x7ff);
211 
212  writeBytesUnaligned(HighInsn, LocalAddress, 2);
213  writeBytesUnaligned(LowInsn, LocalAddress + 2, 2);
214  break;
215  }
216 
218  if (RE.IsTargetThumbFunc)
219  Value |= 0x01;
220  writeBytesUnaligned(Value + RE.Addend, LocalAddress, 1 << RE.Size);
221  break;
222  case MachO::ARM_RELOC_BR24: {
223  // Mask the value into the target address. We know instructions are
224  // 32-bit aligned, so we can do it all at once.
225  Value += RE.Addend;
226  // The low two bits of the value are not encoded.
227  Value >>= 2;
228  // Mask the value to 24 bits.
229  uint64_t FinalValue = Value & 0xffffff;
230  // FIXME: If the destination is a Thumb function (and the instruction
231  // is a non-predicated BL instruction), we need to change it to a BLX
232  // instruction instead.
233 
234  // Insert the value into the instruction.
235  uint32_t Temp = readBytesUnaligned(LocalAddress, 4);
236  writeBytesUnaligned((Temp & ~0xffffff) | FinalValue, LocalAddress, 4);
237 
238  break;
239  }
241  uint64_t SectionABase = Sections[RE.Sections.SectionA].getLoadAddress();
242  uint64_t SectionBBase = Sections[RE.Sections.SectionB].getLoadAddress();
243  assert((Value == SectionABase || Value == SectionBBase) &&
244  "Unexpected HALFSECTDIFF relocation value.");
245  Value = SectionABase - SectionBBase + RE.Addend;
246  if (RE.Size & 0x1) // :upper16:
247  Value = (Value >> 16);
248 
249  bool IsThumb = RE.Size & 0x2;
250 
251  Value &= 0xffff;
252 
253  uint32_t Insn = readBytesUnaligned(LocalAddress, 4);
254 
255  if (IsThumb)
256  Insn = (Insn & 0x8f00fbf0) | ((Value & 0xf000) >> 12) |
257  ((Value & 0x0800) >> 1) | ((Value & 0x0700) << 20) |
258  ((Value & 0x00ff) << 16);
259  else
260  Insn = (Insn & 0xfff0f000) | ((Value & 0xf000) << 4) | (Value & 0x0fff);
261  writeBytesUnaligned(Insn, LocalAddress, 4);
262  break;
263  }
264 
265  default:
266  llvm_unreachable("Invalid relocation type");
267  }
268  }
269 
270  Error finalizeSection(const ObjectFile &Obj, unsigned SectionID,
271  const SectionRef &Section) {
272  StringRef Name;
273  Section.getName(Name);
274 
275  if (Name == "__nl_symbol_ptr")
276  return populateIndirectSymbolPointersSection(cast<MachOObjectFile>(Obj),
277  Section, SectionID);
278  return Error::success();
279  }
280 
281 private:
282 
283  void processBranchRelocation(const RelocationEntry &RE,
284  const RelocationValueRef &Value,
285  StubMap &Stubs) {
286  // This is an ARM branch relocation, need to use a stub function.
287  // Look up for existing stub.
289  RuntimeDyldMachO::StubMap::const_iterator i = Stubs.find(Value);
290  uint8_t *Addr;
291  if (i != Stubs.end()) {
292  Addr = Section.getAddressWithOffset(i->second);
293  } else {
294  // Create a new stub function.
295  assert(Section.getStubOffset() % 4 == 0 && "Misaligned stub");
296  Stubs[Value] = Section.getStubOffset();
297  uint32_t StubOpcode = 0;
298  if (RE.RelType == MachO::ARM_RELOC_BR24)
299  StubOpcode = 0xe51ff004; // ldr pc, [pc, #-4]
300  else if (RE.RelType == MachO::ARM_THUMB_RELOC_BR22)
301  StubOpcode = 0xf000f8df; // ldr pc, [pc]
302  else
303  llvm_unreachable("Unrecognized relocation");
304  Addr = Section.getAddressWithOffset(Section.getStubOffset());
305  writeBytesUnaligned(StubOpcode, Addr, 4);
306  uint8_t *StubTargetAddr = Addr + 4;
307  RelocationEntry StubRE(
308  RE.SectionID, StubTargetAddr - Section.getAddress(),
309  MachO::GENERIC_RELOC_VANILLA, Value.Offset, false, 2);
311  if (Value.SymbolName)
312  addRelocationForSymbol(StubRE, Value.SymbolName);
313  else
314  addRelocationForSection(StubRE, Value.SectionID);
316  }
317  RelocationEntry TargetRE(RE.SectionID, RE.Offset, RE.RelType, 0,
318  RE.IsPCRel, RE.Size);
319  resolveRelocation(TargetRE, (uint64_t)Addr);
320  }
321 
323  processHALFSECTDIFFRelocation(unsigned SectionID, relocation_iterator RelI,
324  const ObjectFile &BaseTObj,
325  ObjSectionToIDMap &ObjSectionToID) {
326  const MachOObjectFile &MachO =
327  static_cast<const MachOObjectFile&>(BaseTObj);
329  MachO.getRelocation(RelI->getRawDataRefImpl());
330 
331  // For a half-diff relocation the length bits actually record whether this
332  // is a movw/movt, and whether this is arm or thumb.
333  // Bit 0 indicates movw (b0 == 0) or movt (b0 == 1).
334  // Bit 1 indicates arm (b1 == 0) or thumb (b1 == 1).
335  unsigned HalfDiffKindBits = MachO.getAnyRelocationLength(RE);
336  bool IsThumb = HalfDiffKindBits & 0x2;
337 
338  SectionEntry &Section = Sections[SectionID];
339  uint32_t RelocType = MachO.getAnyRelocationType(RE);
340  bool IsPCRel = MachO.getAnyRelocationPCRel(RE);
341  uint64_t Offset = RelI->getOffset();
342  uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
343  int64_t Immediate = readBytesUnaligned(LocalAddress, 4); // Copy the whole instruction out.
344 
345  if (IsThumb)
346  Immediate = ((Immediate & 0x0000000f) << 12) |
347  ((Immediate & 0x00000400) << 1) |
348  ((Immediate & 0x70000000) >> 20) |
349  ((Immediate & 0x00ff0000) >> 16);
350  else
351  Immediate = ((Immediate >> 4) & 0xf000) | (Immediate & 0xfff);
352 
353  ++RelI;
355  MachO.getRelocation(RelI->getRawDataRefImpl());
356  uint32_t AddrA = MachO.getScatteredRelocationValue(RE);
357  section_iterator SAI = getSectionByAddress(MachO, AddrA);
358  assert(SAI != MachO.section_end() && "Can't find section for address A");
359  uint64_t SectionABase = SAI->getAddress();
360  uint64_t SectionAOffset = AddrA - SectionABase;
361  SectionRef SectionA = *SAI;
362  bool IsCode = SectionA.isText();
363  uint32_t SectionAID = ~0U;
364  if (auto SectionAIDOrErr =
365  findOrEmitSection(MachO, SectionA, IsCode, ObjSectionToID))
366  SectionAID = *SectionAIDOrErr;
367  else
368  return SectionAIDOrErr.takeError();
369 
370  uint32_t AddrB = MachO.getScatteredRelocationValue(RE2);
371  section_iterator SBI = getSectionByAddress(MachO, AddrB);
372  assert(SBI != MachO.section_end() && "Can't find section for address B");
373  uint64_t SectionBBase = SBI->getAddress();
374  uint64_t SectionBOffset = AddrB - SectionBBase;
375  SectionRef SectionB = *SBI;
376  uint32_t SectionBID = ~0U;
377  if (auto SectionBIDOrErr =
378  findOrEmitSection(MachO, SectionB, IsCode, ObjSectionToID))
379  SectionBID = *SectionBIDOrErr;
380  else
381  return SectionBIDOrErr.takeError();
382 
383  uint32_t OtherHalf = MachO.getAnyRelocationAddress(RE2) & 0xffff;
384  unsigned Shift = (HalfDiffKindBits & 0x1) ? 16 : 0;
385  uint32_t FullImmVal = (Immediate << Shift) | (OtherHalf << (16 - Shift));
386  int64_t Addend = FullImmVal - (AddrA - AddrB);
387 
388  // addend = Encoded - Expected
389  // = Encoded - (AddrA - AddrB)
390 
391  DEBUG(dbgs() << "Found SECTDIFF: AddrA: " << AddrA << ", AddrB: " << AddrB
392  << ", Addend: " << Addend << ", SectionA ID: " << SectionAID
393  << ", SectionAOffset: " << SectionAOffset
394  << ", SectionB ID: " << SectionBID
395  << ", SectionBOffset: " << SectionBOffset << "\n");
396  RelocationEntry R(SectionID, Offset, RelocType, Addend, SectionAID,
397  SectionAOffset, SectionBID, SectionBOffset, IsPCRel,
398  HalfDiffKindBits);
399 
400  addRelocationForSection(R, SectionAID);
401 
402  return ++RelI;
403  }
404 
405 };
406 }
407 
408 #undef DEBUG_TYPE
409 
410 #endif
unsigned getStubAlignment() override
RelocationEntry - used to represent relocations internally in the dynamic linker. ...
unsigned getAnyRelocationAddress(const MachO::any_relocation_info &RE) const
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
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.
bool getPlainRelocationExternal(const MachO::any_relocation_info &RE) const
iterator find(StringRef Key)
Definition: StringMap.h:337
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
unsigned getMaxStubSize() override
uint8_t * getAddress() const
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.
uint64_t modifyAddressBasedOnFlags(uint64_t Addr, JITSymbolFlags Flags) const override
Modify the given target address based on the given symbol flags.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
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 ...
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...
RuntimeDyldMachOARM(RuntimeDyld::MemoryManager &MM, JITSymbolResolver &Resolver)
unsigned getAnyRelocationType(const MachO::any_relocation_info &RE) const
RuntimeDyldMachOTarget - Templated base class for generic MachO linker algorithms and data structures...
Error finalizeSection(const ObjectFile &Obj, unsigned SectionID, const SectionRef &Section)
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...
void addRelocationForSection(const RelocationEntry &RE, unsigned SectionID)
MachO::any_relocation_info getRelocation(DataRefImpl Rel) const
Flags for symbols in the JIT.
Definition: JITSymbol.h:40
Symbol resolution.
Definition: JITSymbol.h:260
virtual JITSymbolFlags getJITSymbolFlags(const BasicSymbolRef &Sym)
Generate JITSymbolFlags from a libObject symbol.
Expected< unsigned > findOrEmitSection(const ObjectFile &Obj, const SectionRef &Section, bool IsCode, ObjSectionToIDMap &LocalSections)
Find Section in LocalSections.
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
Expected< int64_t > decodeAddend(const RelocationEntry &RE) const
static ErrorSuccess success()
Create a success value.
Definition: Error.h:313
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.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
uintptr_t getStubOffset() const
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.
This is a value type class that represents a single symbol in the list of symbols in the object file...
Definition: SymbolicFile.h:99
TargetFlagsType & getTargetFlags()
Return a reference to the target-specific flags.
Definition: JITSymbol.h:97
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
void resolveRelocation(const RelocationEntry &RE, uint64_t Value) override
A object file specific relocation resolver.
RTDyldSymbolTable GlobalSymbolTable
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)
JITSymbolFlags getJITSymbolFlags(const BasicSymbolRef &SR) override
Generate JITSymbolFlags from a libObject symbol.
void advanceStubOffset(unsigned StubSize)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
static ARMJITSymbolFlags fromObjectSymbol(const object::BasicSymbolRef &Symbol)
Definition: JITSymbol.cpp:43
void makeValueAddendPCRel(RelocationValueRef &Value, const relocation_iterator &RI, unsigned OffsetToNextPC)
Make the RelocationValueRef addend PC-relative.
uint32_t getScatteredRelocationValue(const MachO::any_relocation_info &RE) const
iterator end()
Definition: StringMap.h:322
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:80
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:73