1 //===-- X86MachObjectWriter.cpp - X86 Mach-O Writer -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "MCTargetDesc/X86MCTargetDesc.h"
11 #include "MCTargetDesc/X86FixupKinds.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAsmInfo.h"
14 #include "llvm/MC/MCAsmLayout.h"
15 #include "llvm/MC/MCAssembler.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCMachObjectWriter.h"
18 #include "llvm/MC/MCSectionMachO.h"
19 #include "llvm/MC/MCValue.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/MachO.h"
27 class X86MachObjectWriter : public MCMachObjectTargetWriter {
28 bool RecordScatteredRelocation(MachObjectWriter *Writer,
29 const MCAssembler &Asm,
30 const MCAsmLayout &Layout,
31 const MCFragment *Fragment,
35 uint64_t &FixedValue);
36 void RecordTLVPRelocation(MachObjectWriter *Writer,
37 const MCAssembler &Asm,
38 const MCAsmLayout &Layout,
39 const MCFragment *Fragment,
42 uint64_t &FixedValue);
44 void RecordX86Relocation(MachObjectWriter *Writer,
45 const MCAssembler &Asm,
46 const MCAsmLayout &Layout,
47 const MCFragment *Fragment,
50 uint64_t &FixedValue);
51 void RecordX86_64Relocation(MachObjectWriter *Writer, MCAssembler &Asm,
52 const MCAsmLayout &Layout,
53 const MCFragment *Fragment, const MCFixup &Fixup,
54 MCValue Target, uint64_t &FixedValue);
57 X86MachObjectWriter(bool Is64Bit, uint32_t CPUType,
59 : MCMachObjectTargetWriter(Is64Bit, CPUType, CPUSubtype,
60 /*UseAggressiveSymbolFolding=*/Is64Bit) {}
62 void RecordRelocation(MachObjectWriter *Writer, MCAssembler &Asm,
63 const MCAsmLayout &Layout, const MCFragment *Fragment,
64 const MCFixup &Fixup, MCValue Target,
65 uint64_t &FixedValue) override {
66 if (Writer->is64Bit())
67 RecordX86_64Relocation(Writer, Asm, Layout, Fragment, Fixup, Target,
70 RecordX86Relocation(Writer, Asm, Layout, Fragment, Fixup, Target,
76 static bool isFixupKindRIPRel(unsigned Kind) {
77 return Kind == X86::reloc_riprel_4byte ||
78 Kind == X86::reloc_riprel_4byte_movq_load;
81 static unsigned getFixupKindLog2Size(unsigned Kind) {
84 llvm_unreachable("invalid fixup kind!");
86 case FK_Data_1: return 0;
88 case FK_Data_2: return 1;
90 // FIXME: Remove these!!!
91 case X86::reloc_riprel_4byte:
92 case X86::reloc_riprel_4byte_movq_load:
93 case X86::reloc_signed_4byte:
94 case FK_Data_4: return 2;
95 case FK_Data_8: return 3;
99 void X86MachObjectWriter::RecordX86_64Relocation(
100 MachObjectWriter *Writer, MCAssembler &Asm, const MCAsmLayout &Layout,
101 const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target,
102 uint64_t &FixedValue) {
103 unsigned IsPCRel = Writer->isFixupKindPCRel(Asm, Fixup.getKind());
104 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
105 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
108 uint32_t FixupOffset =
109 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
110 uint32_t FixupAddress =
111 Writer->getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
114 unsigned IsExtern = 0;
116 const MCSymbol *RelSymbol = nullptr;
118 Value = Target.getConstant();
121 // Compensate for the relocation offset, Darwin x86_64 relocations only have
122 // the addend and appear to have attempted to define it to be the actual
123 // expression addend without the PCrel bias. However, instructions with data
124 // following the relocation are not accommodated for (see comment below
125 // regarding SIGNED{1,2,4}), so it isn't exactly that either.
126 Value += 1LL << Log2Size;
129 if (Target.isAbsolute()) { // constant
130 // SymbolNum of 0 indicates the absolute section.
131 Type = MachO::X86_64_RELOC_UNSIGNED;
133 // FIXME: I believe this is broken, I don't think the linker can understand
134 // it. I think it would require a local relocation, but I'm not sure if that
135 // would work either. The official way to get an absolute PCrel relocation
136 // is to use an absolute symbol (which we don't support yet).
139 Type = MachO::X86_64_RELOC_BRANCH;
141 } else if (Target.getSymB()) { // A - B + constant
142 const MCSymbol *A = &Target.getSymA()->getSymbol();
143 if (A->isTemporary())
144 A = &Writer->findAliasedSymbol(*A);
145 const MCSymbol *A_Base = Asm.getAtom(*A);
147 const MCSymbol *B = &Target.getSymB()->getSymbol();
148 if (B->isTemporary())
149 B = &Writer->findAliasedSymbol(*B);
150 const MCSymbol *B_Base = Asm.getAtom(*B);
152 // Neither symbol can be modified.
153 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
154 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
155 report_fatal_error("unsupported relocation of modified symbol", false);
157 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
158 // implement most of these correctly.
160 report_fatal_error("unsupported pc-relative relocation of difference",
163 // The support for the situation where one or both of the symbols would
164 // require a local relocation is handled just like if the symbols were
165 // external. This is certainly used in the case of debug sections where the
166 // section has only temporary symbols and thus the symbols don't have base
167 // symbols. This is encoded using the section ordinal and non-extern
168 // relocation entries.
170 // Darwin 'as' doesn't emit correct relocations for this (it ends up with a
171 // single SIGNED relocation); reject it for now. Except the case where both
172 // symbols don't have a base, equal but both NULL.
173 if (A_Base == B_Base && A_Base)
174 report_fatal_error("unsupported relocation with identical base", false);
176 // A subtraction expression where either symbol is undefined is a
177 // non-relocatable expression.
178 if (A->isUndefined() || B->isUndefined()) {
179 StringRef Name = A->isUndefined() ? A->getName() : B->getName();
180 Asm.getContext().reportFatalError(Fixup.getLoc(),
181 "unsupported relocation with subtraction expression, symbol '" +
182 Name + "' can not be undefined in a subtraction expression");
185 Value += Writer->getSymbolAddress(*A, Layout) -
186 (!A_Base ? 0 : Writer->getSymbolAddress(*A_Base, Layout));
187 Value -= Writer->getSymbolAddress(*B, Layout) -
188 (!B_Base ? 0 : Writer->getSymbolAddress(*B_Base, Layout));
191 Index = A->getFragment()->getParent()->getOrdinal() + 1;
192 Type = MachO::X86_64_RELOC_UNSIGNED;
194 MachO::any_relocation_info MRE;
195 MRE.r_word0 = FixupOffset;
197 (Index << 0) | (IsPCRel << 24) | (Log2Size << 25) | (Type << 28);
198 Writer->addRelocation(A_Base, Fragment->getParent(), MRE);
203 Index = B->getFragment()->getParent()->getOrdinal() + 1;
204 Type = MachO::X86_64_RELOC_SUBTRACTOR;
206 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
207 if (Symbol->isTemporary() && Value) {
208 const MCSection &Sec = Symbol->getSection();
209 if (!Asm.getContext().getAsmInfo()->isSectionAtomizableBySymbols(Sec))
210 Asm.addLocalUsedInReloc(*Symbol);
212 RelSymbol = Asm.getAtom(*Symbol);
214 // Relocations inside debug sections always use local relocations when
215 // possible. This seems to be done because the debugger doesn't fully
216 // understand x86_64 relocation entries, and expects to find values that
217 // have already been fixed up.
218 if (Symbol->isInSection()) {
219 const MCSectionMachO &Section =
220 static_cast<const MCSectionMachO &>(*Fragment->getParent());
221 if (Section.hasAttribute(MachO::S_ATTR_DEBUG))
225 // x86_64 almost always uses external relocations, except when there is no
226 // symbol to use as a base address (a local symbol with no preceding
227 // non-local symbol).
229 // Add the local offset, if needed.
230 if (RelSymbol != Symbol)
231 Value += Layout.getSymbolOffset(*Symbol) -
232 Layout.getSymbolOffset(*RelSymbol);
233 } else if (Symbol->isInSection() && !Symbol->isVariable()) {
234 // The index is the section ordinal (1-based).
235 Index = Symbol->getFragment()->getParent()->getOrdinal() + 1;
236 Value += Writer->getSymbolAddress(*Symbol, Layout);
239 Value -= FixupAddress + (1 << Log2Size);
240 } else if (Symbol->isVariable()) {
241 const MCExpr *Value = Symbol->getVariableValue();
243 bool isAbs = Value->evaluateAsAbsolute(Res, Layout,
244 Writer->getSectionAddressMap());
249 report_fatal_error("unsupported relocation of variable '" +
250 Symbol->getName() + "'", false);
253 report_fatal_error("unsupported relocation of undefined symbol '" +
254 Symbol->getName() + "'", false);
257 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
260 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
261 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
262 // rewrite the movq to an leaq at link time if the symbol ends up in
263 // the same linkage unit.
264 if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
265 Type = MachO::X86_64_RELOC_GOT_LOAD;
267 Type = MachO::X86_64_RELOC_GOT;
268 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
269 Type = MachO::X86_64_RELOC_TLV;
270 } else if (Modifier != MCSymbolRefExpr::VK_None) {
271 report_fatal_error("unsupported symbol modifier in relocation",
274 Type = MachO::X86_64_RELOC_SIGNED;
276 // The Darwin x86_64 relocation format has a problem where it cannot
277 // encode an address (L<foo> + <constant>) which is outside the atom
278 // containing L<foo>. Generally, this shouldn't occur but it does
279 // happen when we have a RIPrel instruction with data following the
280 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
281 // adjustment Darwin x86_64 uses, the offset is still negative and the
282 // linker has no way to recognize this.
284 // To work around this, Darwin uses several special relocation types
285 // to indicate the offsets. However, the specification or
286 // implementation of these seems to also be incomplete; they should
287 // adjust the addend as well based on the actual encoded instruction
288 // (the additional bias), but instead appear to just look at the final
290 switch (-(Target.getConstant() + (1LL << Log2Size))) {
291 case 1: Type = MachO::X86_64_RELOC_SIGNED_1; break;
292 case 2: Type = MachO::X86_64_RELOC_SIGNED_2; break;
293 case 4: Type = MachO::X86_64_RELOC_SIGNED_4; break;
297 if (Modifier != MCSymbolRefExpr::VK_None)
298 report_fatal_error("unsupported symbol modifier in branch "
299 "relocation", false);
301 Type = MachO::X86_64_RELOC_BRANCH;
304 if (Modifier == MCSymbolRefExpr::VK_GOT) {
305 Type = MachO::X86_64_RELOC_GOT;
306 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
307 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in which
308 // case all we do is set the PCrel bit in the relocation entry; this is
309 // used with exception handling, for example. The source is required to
310 // include any necessary offset directly.
311 Type = MachO::X86_64_RELOC_GOT;
313 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
314 report_fatal_error("TLVP symbol modifier should have been rip-rel",
316 } else if (Modifier != MCSymbolRefExpr::VK_None)
317 report_fatal_error("unsupported symbol modifier in relocation", false);
319 Type = MachO::X86_64_RELOC_UNSIGNED;
320 unsigned Kind = Fixup.getKind();
321 if (Kind == X86::reloc_signed_4byte)
322 report_fatal_error("32-bit absolute addressing is not supported in "
323 "64-bit mode", false);
328 // x86_64 always writes custom values into the fixups.
331 // struct relocation_info (8 bytes)
332 MachO::any_relocation_info MRE;
333 MRE.r_word0 = FixupOffset;
334 MRE.r_word1 = (Index << 0) | (IsPCRel << 24) | (Log2Size << 25) |
335 (IsExtern << 27) | (Type << 28);
336 Writer->addRelocation(RelSymbol, Fragment->getParent(), MRE);
339 bool X86MachObjectWriter::RecordScatteredRelocation(MachObjectWriter *Writer,
340 const MCAssembler &Asm,
341 const MCAsmLayout &Layout,
342 const MCFragment *Fragment,
343 const MCFixup &Fixup,
346 uint64_t &FixedValue) {
347 uint64_t OriginalFixedValue = FixedValue;
348 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
349 unsigned IsPCRel = Writer->isFixupKindPCRel(Asm, Fixup.getKind());
350 unsigned Type = MachO::GENERIC_RELOC_VANILLA;
353 const MCSymbol *A = &Target.getSymA()->getSymbol();
355 if (!A->getFragment())
356 report_fatal_error("symbol '" + A->getName() +
357 "' can not be undefined in a subtraction expression",
360 uint32_t Value = Writer->getSymbolAddress(*A, Layout);
361 uint64_t SecAddr = Writer->getSectionAddress(A->getFragment()->getParent());
362 FixedValue += SecAddr;
365 if (const MCSymbolRefExpr *B = Target.getSymB()) {
366 const MCSymbol *SB = &B->getSymbol();
368 if (!SB->getFragment())
369 report_fatal_error("symbol '" + B->getSymbol().getName() +
370 "' can not be undefined in a subtraction expression",
373 // Select the appropriate difference relocation type.
375 // Note that there is no longer any semantic difference between these two
376 // relocation types from the linkers point of view, this is done solely for
377 // pedantic compatibility with 'as'.
378 Type = A->isExternal() ? (unsigned)MachO::GENERIC_RELOC_SECTDIFF
379 : (unsigned)MachO::GENERIC_RELOC_LOCAL_SECTDIFF;
380 Value2 = Writer->getSymbolAddress(B->getSymbol(), Layout);
381 FixedValue -= Writer->getSectionAddress(SB->getFragment()->getParent());
384 // Relocations are written out in reverse order, so the PAIR comes first.
385 if (Type == MachO::GENERIC_RELOC_SECTDIFF ||
386 Type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
387 // If the offset is too large to fit in a scattered relocation,
388 // we're hosed. It's an unfortunate limitation of the MachO format.
389 if (FixupOffset > 0xffffff) {
391 format("0x%x", FixupOffset).print(Buffer, sizeof(Buffer));
392 Asm.getContext().reportFatalError(Fixup.getLoc(),
393 Twine("Section too large, can't encode "
394 "r_address (") + Buffer +
395 ") into 24 bits of scattered "
396 "relocation entry.");
397 llvm_unreachable("fatal error returned?!");
400 MachO::any_relocation_info MRE;
401 MRE.r_word0 = ((0 << 0) | // r_address
402 (MachO::GENERIC_RELOC_PAIR << 24) | // r_type
406 MRE.r_word1 = Value2;
407 Writer->addRelocation(nullptr, Fragment->getParent(), MRE);
409 // If the offset is more than 24-bits, it won't fit in a scattered
410 // relocation offset field, so we fall back to using a non-scattered
411 // relocation. This is a bit risky, as if the offset reaches out of
412 // the block and the linker is doing scattered loading on this
413 // symbol, things can go badly.
415 // Required for 'as' compatibility.
416 if (FixupOffset > 0xffffff) {
417 FixedValue = OriginalFixedValue;
422 MachO::any_relocation_info MRE;
423 MRE.r_word0 = ((FixupOffset << 0) |
429 Writer->addRelocation(nullptr, Fragment->getParent(), MRE);
433 void X86MachObjectWriter::RecordTLVPRelocation(MachObjectWriter *Writer,
434 const MCAssembler &Asm,
435 const MCAsmLayout &Layout,
436 const MCFragment *Fragment,
437 const MCFixup &Fixup,
439 uint64_t &FixedValue) {
440 assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
442 "Should only be called with a 32-bit TLVP relocation!");
444 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
445 uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
446 unsigned IsPCRel = 0;
448 // We're only going to have a second symbol in pic mode and it'll be a
449 // subtraction from the picbase. For 32-bit pic the addend is the difference
450 // between the picbase and the next address. For 32-bit static the addend is
452 if (Target.getSymB()) {
453 // If this is a subtraction then we're pcrel.
454 uint32_t FixupAddress =
455 Writer->getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
459 Writer->getSymbolAddress(Target.getSymB()->getSymbol(), Layout) +
460 Target.getConstant();
461 FixedValue += 1ULL << Log2Size;
466 // struct relocation_info (8 bytes)
467 MachO::any_relocation_info MRE;
470 (IsPCRel << 24) | (Log2Size << 25) | (MachO::GENERIC_RELOC_TLV << 28);
471 Writer->addRelocation(&Target.getSymA()->getSymbol(), Fragment->getParent(),
475 void X86MachObjectWriter::RecordX86Relocation(MachObjectWriter *Writer,
476 const MCAssembler &Asm,
477 const MCAsmLayout &Layout,
478 const MCFragment *Fragment,
479 const MCFixup &Fixup,
481 uint64_t &FixedValue) {
482 unsigned IsPCRel = Writer->isFixupKindPCRel(Asm, Fixup.getKind());
483 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
485 // If this is a 32-bit TLVP reloc it's handled a bit differently.
486 if (Target.getSymA() &&
487 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
488 RecordTLVPRelocation(Writer, Asm, Layout, Fragment, Fixup, Target,
493 // If this is a difference or a defined symbol plus an offset, then we need a
494 // scattered relocation entry. Differences always require scattered
496 if (Target.getSymB()) {
497 RecordScatteredRelocation(Writer, Asm, Layout, Fragment, Fixup,
498 Target, Log2Size, FixedValue);
502 // Get the symbol data, if any.
503 const MCSymbol *A = nullptr;
504 if (Target.getSymA())
505 A = &Target.getSymA()->getSymbol();
507 // If this is an internal relocation with an offset, it also needs a scattered
509 uint32_t Offset = Target.getConstant();
511 Offset += 1 << Log2Size;
512 // Try to record the scattered relocation if needed. Fall back to non
513 // scattered if necessary (see comments in RecordScatteredRelocation()
515 if (Offset && A && !Writer->doesSymbolRequireExternRelocation(*A) &&
516 RecordScatteredRelocation(Writer, Asm, Layout, Fragment, Fixup, Target,
517 Log2Size, FixedValue))
521 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
524 const MCSymbol *RelSymbol = nullptr;
526 if (Target.isAbsolute()) { // constant
527 // SymbolNum of 0 indicates the absolute section.
529 // FIXME: Currently, these are never generated (see code below). I cannot
530 // find a case where they are actually emitted.
531 Type = MachO::GENERIC_RELOC_VANILLA;
533 // Resolve constant variables.
534 if (A->isVariable()) {
536 if (A->getVariableValue()->evaluateAsAbsolute(
537 Res, Layout, Writer->getSectionAddressMap())) {
543 // Check whether we need an external or internal relocation.
544 if (Writer->doesSymbolRequireExternRelocation(*A)) {
546 // For external relocations, make sure to offset the fixup value to
547 // compensate for the addend of the symbol address, if it was
548 // undefined. This occurs with weak definitions, for example.
549 if (!A->isUndefined())
550 FixedValue -= Layout.getSymbolOffset(*A);
552 // The index is the section ordinal (1-based).
553 const MCSection &Sec = A->getSection();
554 Index = Sec.getOrdinal() + 1;
555 FixedValue += Writer->getSectionAddress(&Sec);
558 FixedValue -= Writer->getSectionAddress(Fragment->getParent());
560 Type = MachO::GENERIC_RELOC_VANILLA;
563 // struct relocation_info (8 bytes)
564 MachO::any_relocation_info MRE;
565 MRE.r_word0 = FixupOffset;
567 (Index << 0) | (IsPCRel << 24) | (Log2Size << 25) | (Type << 28);
568 Writer->addRelocation(RelSymbol, Fragment->getParent(), MRE);
571 MCObjectWriter *llvm::createX86MachObjectWriter(raw_pwrite_stream &OS,
572 bool Is64Bit, uint32_t CPUType,
573 uint32_t CPUSubtype) {
574 return createMachObjectWriter(new X86MachObjectWriter(Is64Bit,
577 OS, /*IsLittleEndian=*/true);