1 //===- lib/MC/MachObjectWriter.cpp - Mach-O File 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 "llvm/MC/MachObjectWriter.h"
11 #include "llvm/ADT/StringMap.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAssembler.h"
14 #include "llvm/MC/MCAsmLayout.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCObjectWriter.h"
17 #include "llvm/MC/MCSectionMachO.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/MC/MCMachOSymbolFlags.h"
20 #include "llvm/MC/MCValue.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MachO.h"
23 #include "llvm/Target/TargetAsmBackend.h"
26 #include "../Target/X86/X86FixupKinds.h"
31 static unsigned getFixupKindLog2Size(unsigned Kind) {
33 default: llvm_unreachable("invalid fixup kind!");
34 case X86::reloc_pcrel_1byte:
35 case FK_Data_1: return 0;
36 case X86::reloc_pcrel_2byte:
37 case FK_Data_2: return 1;
38 case X86::reloc_pcrel_4byte:
39 case X86::reloc_riprel_4byte:
40 case X86::reloc_riprel_4byte_movq_load:
41 case FK_Data_4: return 2;
42 case FK_Data_8: return 3;
46 static bool isFixupKindPCRel(unsigned Kind) {
50 case X86::reloc_pcrel_1byte:
51 case X86::reloc_pcrel_2byte:
52 case X86::reloc_pcrel_4byte:
53 case X86::reloc_riprel_4byte:
54 case X86::reloc_riprel_4byte_movq_load:
59 static bool isFixupKindRIPRel(unsigned Kind) {
60 return Kind == X86::reloc_riprel_4byte ||
61 Kind == X86::reloc_riprel_4byte_movq_load;
64 static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
65 // Undefined symbols are always extern.
66 if (SD->Symbol->isUndefined())
69 // References to weak definitions require external relocation entries; the
70 // definition may not always be the one in the same object file.
71 if (SD->getFlags() & SF_WeakDefinition)
74 // Otherwise, we can use an internal relocation.
78 static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
80 const MCSymbolData *BaseSymbol) {
81 // The effective fixup address is
82 // addr(atom(A)) + offset(A)
83 // - addr(atom(B)) - offset(B)
84 // - addr(BaseSymbol) + <fixup offset from base symbol>
85 // and the offsets are not relocatable, so the fixup is fully resolved when
86 // addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
88 // Note that "false" is almost always conservatively correct (it means we emit
89 // a relocation which is unnecessary), except when it would force us to emit a
90 // relocation which the target cannot encode.
92 const MCSymbolData *A_Base = 0, *B_Base = 0;
93 if (const MCSymbolRefExpr *A = Target.getSymA()) {
94 // Modified symbol references cannot be resolved.
95 if (A->getKind() != MCSymbolRefExpr::VK_None)
98 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
103 if (const MCSymbolRefExpr *B = Target.getSymB()) {
104 // Modified symbol references cannot be resolved.
105 if (B->getKind() != MCSymbolRefExpr::VK_None)
108 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
113 // If there is no base, A and B have to be the same atom for this fixup to be
116 return A_Base == B_Base;
118 // Otherwise, B must be missing and A must be the base.
119 return !B_Base && BaseSymbol == A_Base;
122 static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
123 const MCValue Target,
124 const MCSection *BaseSection) {
125 // The effective fixup address is
126 // addr(atom(A)) + offset(A)
127 // - addr(atom(B)) - offset(B)
128 // - addr(<base symbol>) + <fixup offset from base symbol>
129 // and the offsets are not relocatable, so the fixup is fully resolved when
130 // addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
132 // The simple (Darwin, except on x86_64) way of dealing with this was to
133 // assume that any reference to a temporary symbol *must* be a temporary
134 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
135 // relocation to a temporary symbol (in the same section) is fully
136 // resolved. This also works in conjunction with absolutized .set, which
137 // requires the compiler to use .set to absolutize the differences between
138 // symbols which the compiler knows to be assembly time constants, so we don't
139 // need to worry about considering symbol differences fully resolved.
141 // Non-relative fixups are only resolved if constant.
143 return Target.isAbsolute();
145 // Otherwise, relative fixups are only resolved if not a difference and the
146 // target is a temporary in the same section.
147 if (Target.isAbsolute() || Target.getSymB())
150 const MCSymbol *A = &Target.getSymA()->getSymbol();
151 if (!A->isTemporary() || !A->isInSection() ||
152 &A->getSection() != BaseSection)
160 class MachObjectWriterImpl {
161 // See <mach-o/loader.h>.
163 Header_Magic32 = 0xFEEDFACE,
164 Header_Magic64 = 0xFEEDFACF
170 SegmentLoadCommand32Size = 56,
171 SegmentLoadCommand64Size = 72,
174 SymtabLoadCommandSize = 24,
175 DysymtabLoadCommandSize = 80,
178 RelocationInfoSize = 8
181 enum HeaderFileType {
186 HF_SubsectionsViaSymbols = 0x2000
189 enum LoadCommandType {
196 // See <mach-o/nlist.h>.
197 enum SymbolTypeType {
198 STT_Undefined = 0x00,
203 enum SymbolTypeFlags {
204 // If any of these bits are set, then the entry is a stab entry number (see
205 // <mach-o/stab.h>. Otherwise the other masks apply.
206 STF_StabsEntryMask = 0xe0,
210 STF_PrivateExtern = 0x10
213 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
215 enum IndirectSymbolFlags {
216 ISF_Local = 0x80000000,
217 ISF_Absolute = 0x40000000
220 /// RelocationFlags - Special flags for addresses.
221 enum RelocationFlags {
222 RF_Scattered = 0x80000000
225 enum RelocationInfoType {
229 RIT_PreboundLazyPointer = 3,
230 RIT_LocalDifference = 4,
234 /// X86_64 uses its own relocation types.
235 enum RelocationInfoTypeX86_64 {
236 RIT_X86_64_Unsigned = 0,
237 RIT_X86_64_Signed = 1,
238 RIT_X86_64_Branch = 2,
239 RIT_X86_64_GOTLoad = 3,
241 RIT_X86_64_Subtractor = 5,
242 RIT_X86_64_Signed1 = 6,
243 RIT_X86_64_Signed2 = 7,
244 RIT_X86_64_Signed4 = 8,
248 /// MachSymbolData - Helper struct for containing some precomputed information
250 struct MachSymbolData {
251 MCSymbolData *SymbolData;
252 uint64_t StringIndex;
253 uint8_t SectionIndex;
255 // Support lexicographic sorting.
256 bool operator<(const MachSymbolData &RHS) const {
257 return SymbolData->getSymbol().getName() <
258 RHS.SymbolData->getSymbol().getName();
262 /// @name Relocation Data
265 struct MachRelocationEntry {
270 llvm::DenseMap<const MCSectionData*,
271 std::vector<MachRelocationEntry> > Relocations;
272 llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
275 /// @name Symbol Table Data
278 SmallString<256> StringTable;
279 std::vector<MachSymbolData> LocalSymbolData;
280 std::vector<MachSymbolData> ExternalSymbolData;
281 std::vector<MachSymbolData> UndefinedSymbolData;
285 MachObjectWriter *Writer;
289 unsigned Is64Bit : 1;
292 MachObjectWriterImpl(MachObjectWriter *_Writer, bool _Is64Bit)
293 : Writer(_Writer), OS(Writer->getStream()), Is64Bit(_Is64Bit) {
296 void Write8(uint8_t Value) { Writer->Write8(Value); }
297 void Write16(uint16_t Value) { Writer->Write16(Value); }
298 void Write32(uint32_t Value) { Writer->Write32(Value); }
299 void Write64(uint64_t Value) { Writer->Write64(Value); }
300 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
301 void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
302 Writer->WriteBytes(Str, ZeroFillSize);
305 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
306 bool SubsectionsViaSymbols) {
309 if (SubsectionsViaSymbols)
310 Flags |= HF_SubsectionsViaSymbols;
312 // struct mach_header (28 bytes) or
313 // struct mach_header_64 (32 bytes)
315 uint64_t Start = OS.tell();
318 Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
320 // FIXME: Support cputype.
321 Write32(Is64Bit ? MachO::CPUTypeX86_64 : MachO::CPUTypeI386);
322 // FIXME: Support cpusubtype.
323 Write32(MachO::CPUSubType_I386_ALL);
325 Write32(NumLoadCommands); // Object files have a single load command, the
327 Write32(LoadCommandsSize);
330 Write32(0); // reserved
332 assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
335 /// WriteSegmentLoadCommand - Write a segment load command.
337 /// \arg NumSections - The number of sections in this segment.
338 /// \arg SectionDataSize - The total size of the sections.
339 void WriteSegmentLoadCommand(unsigned NumSections,
341 uint64_t SectionDataStartOffset,
342 uint64_t SectionDataSize) {
343 // struct segment_command (56 bytes) or
344 // struct segment_command_64 (72 bytes)
346 uint64_t Start = OS.tell();
349 unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
350 SegmentLoadCommand32Size;
351 Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
352 Write32(SegmentLoadCommandSize +
353 NumSections * (Is64Bit ? Section64Size : Section32Size));
357 Write64(0); // vmaddr
358 Write64(VMSize); // vmsize
359 Write64(SectionDataStartOffset); // file offset
360 Write64(SectionDataSize); // file size
362 Write32(0); // vmaddr
363 Write32(VMSize); // vmsize
364 Write32(SectionDataStartOffset); // file offset
365 Write32(SectionDataSize); // file size
367 Write32(0x7); // maxprot
368 Write32(0x7); // initprot
369 Write32(NumSections);
372 assert(OS.tell() - Start == SegmentLoadCommandSize);
375 void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
376 const MCSectionData &SD, uint64_t FileOffset,
377 uint64_t RelocationsStart, unsigned NumRelocations) {
378 uint64_t SectionSize = Layout.getSectionSize(&SD);
380 // The offset is unused for virtual sections.
381 if (Asm.getBackend().isVirtualSection(SD.getSection())) {
382 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
386 // struct section (68 bytes) or
387 // struct section_64 (80 bytes)
389 uint64_t Start = OS.tell();
392 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
393 WriteBytes(Section.getSectionName(), 16);
394 WriteBytes(Section.getSegmentName(), 16);
396 Write64(Layout.getSectionAddress(&SD)); // address
397 Write64(SectionSize); // size
399 Write32(Layout.getSectionAddress(&SD)); // address
400 Write32(SectionSize); // size
404 unsigned Flags = Section.getTypeAndAttributes();
405 if (SD.hasInstructions())
406 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
408 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
409 Write32(Log2_32(SD.getAlignment()));
410 Write32(NumRelocations ? RelocationsStart : 0);
411 Write32(NumRelocations);
413 Write32(IndirectSymBase.lookup(&SD)); // reserved1
414 Write32(Section.getStubSize()); // reserved2
416 Write32(0); // reserved3
418 assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
421 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
422 uint32_t StringTableOffset,
423 uint32_t StringTableSize) {
424 // struct symtab_command (24 bytes)
426 uint64_t Start = OS.tell();
430 Write32(SymtabLoadCommandSize);
431 Write32(SymbolOffset);
433 Write32(StringTableOffset);
434 Write32(StringTableSize);
436 assert(OS.tell() - Start == SymtabLoadCommandSize);
439 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
440 uint32_t NumLocalSymbols,
441 uint32_t FirstExternalSymbol,
442 uint32_t NumExternalSymbols,
443 uint32_t FirstUndefinedSymbol,
444 uint32_t NumUndefinedSymbols,
445 uint32_t IndirectSymbolOffset,
446 uint32_t NumIndirectSymbols) {
447 // struct dysymtab_command (80 bytes)
449 uint64_t Start = OS.tell();
452 Write32(LCT_Dysymtab);
453 Write32(DysymtabLoadCommandSize);
454 Write32(FirstLocalSymbol);
455 Write32(NumLocalSymbols);
456 Write32(FirstExternalSymbol);
457 Write32(NumExternalSymbols);
458 Write32(FirstUndefinedSymbol);
459 Write32(NumUndefinedSymbols);
460 Write32(0); // tocoff
462 Write32(0); // modtaboff
463 Write32(0); // nmodtab
464 Write32(0); // extrefsymoff
465 Write32(0); // nextrefsyms
466 Write32(IndirectSymbolOffset);
467 Write32(NumIndirectSymbols);
468 Write32(0); // extreloff
469 Write32(0); // nextrel
470 Write32(0); // locreloff
471 Write32(0); // nlocrel
473 assert(OS.tell() - Start == DysymtabLoadCommandSize);
476 void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
477 MCSymbolData &Data = *MSD.SymbolData;
478 const MCSymbol &Symbol = Data.getSymbol();
480 uint16_t Flags = Data.getFlags();
481 uint32_t Address = 0;
483 // Set the N_TYPE bits. See <mach-o/nlist.h>.
485 // FIXME: Are the prebound or indirect fields possible here?
486 if (Symbol.isUndefined())
487 Type = STT_Undefined;
488 else if (Symbol.isAbsolute())
493 // FIXME: Set STAB bits.
495 if (Data.isPrivateExtern())
496 Type |= STF_PrivateExtern;
499 if (Data.isExternal() || Symbol.isUndefined())
500 Type |= STF_External;
502 // Compute the symbol address.
503 if (Symbol.isDefined()) {
504 if (Symbol.isAbsolute()) {
505 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
507 Address = Layout.getSymbolAddress(&Data);
509 } else if (Data.isCommon()) {
510 // Common symbols are encoded with the size in the address
511 // field, and their alignment in the flags.
512 Address = Data.getCommonSize();
514 // Common alignment is packed into the 'desc' bits.
515 if (unsigned Align = Data.getCommonAlignment()) {
516 unsigned Log2Size = Log2_32(Align);
517 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
519 report_fatal_error("invalid 'common' alignment '" +
521 // FIXME: Keep this mask with the SymbolFlags enumeration.
522 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
526 // struct nlist (12 bytes)
528 Write32(MSD.StringIndex);
530 Write8(MSD.SectionIndex);
532 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
541 // FIXME: We really need to improve the relocation validation. Basically, we
542 // want to implement a separate computation which evaluates the relocation
543 // entry as the linker would, and verifies that the resultant fixup value is
544 // exactly what the encoder wanted. This will catch several classes of
547 // - Relocation entry bugs, the two algorithms are unlikely to have the same
550 // - Relaxation issues, where we forget to relax something.
552 // - Input errors, where something cannot be correctly encoded. 'as' allows
553 // these through in many cases.
555 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
556 const MCFragment *Fragment,
557 const MCFixup &Fixup, MCValue Target,
558 uint64_t &FixedValue) {
559 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
560 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
561 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
564 uint32_t FixupOffset =
565 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
566 uint32_t FixupAddress =
567 Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
570 unsigned IsExtern = 0;
573 Value = Target.getConstant();
576 // Compensate for the relocation offset, Darwin x86_64 relocations only
577 // have the addend and appear to have attempted to define it to be the
578 // actual expression addend without the PCrel bias. However, instructions
579 // with data following the relocation are not accomodated for (see comment
580 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
581 Value += 1LL << Log2Size;
584 if (Target.isAbsolute()) { // constant
585 // SymbolNum of 0 indicates the absolute section.
586 Type = RIT_X86_64_Unsigned;
589 // FIXME: I believe this is broken, I don't think the linker can
590 // understand it. I think it would require a local relocation, but I'm not
591 // sure if that would work either. The official way to get an absolute
592 // PCrel relocation is to use an absolute symbol (which we don't support
596 Type = RIT_X86_64_Branch;
598 } else if (Target.getSymB()) { // A - B + constant
599 const MCSymbol *A = &Target.getSymA()->getSymbol();
600 MCSymbolData &A_SD = Asm.getSymbolData(*A);
601 const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
603 const MCSymbol *B = &Target.getSymB()->getSymbol();
604 MCSymbolData &B_SD = Asm.getSymbolData(*B);
605 const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
607 // Neither symbol can be modified.
608 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
609 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
610 report_fatal_error("unsupported relocation of modified symbol");
612 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
613 // implement most of these correctly.
615 report_fatal_error("unsupported pc-relative relocation of difference");
617 // We don't currently support any situation where one or both of the
618 // symbols would require a local relocation. This is almost certainly
619 // unused and may not be possible to encode correctly.
620 if (!A_Base || !B_Base)
621 report_fatal_error("unsupported local relocations in difference");
623 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
624 // a single SIGNED relocation); reject it for now.
625 if (A_Base == B_Base)
626 report_fatal_error("unsupported relocation with identical base");
628 Value += Layout.getSymbolAddress(&A_SD) - Layout.getSymbolAddress(A_Base);
629 Value -= Layout.getSymbolAddress(&B_SD) - Layout.getSymbolAddress(B_Base);
631 Index = A_Base->getIndex();
633 Type = RIT_X86_64_Unsigned;
635 MachRelocationEntry MRE;
636 MRE.Word0 = FixupOffset;
637 MRE.Word1 = ((Index << 0) |
642 Relocations[Fragment->getParent()].push_back(MRE);
644 Index = B_Base->getIndex();
646 Type = RIT_X86_64_Subtractor;
648 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
649 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
650 const MCSymbolData *Base = Asm.getAtom(&SD);
652 // Relocations inside debug sections always use local relocations when
653 // possible. This seems to be done because the debugger doesn't fully
654 // understand x86_64 relocation entries, and expects to find values that
655 // have already been fixed up.
656 if (Symbol->isInSection()) {
657 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
658 Fragment->getParent()->getSection());
659 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
663 // x86_64 almost always uses external relocations, except when there is no
664 // symbol to use as a base address (a local symbol with no preceeding
665 // non-local symbol).
667 Index = Base->getIndex();
670 // Add the local offset, if needed.
672 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
673 } else if (Symbol->isInSection()) {
674 // The index is the section ordinal (1-based).
675 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
677 Value += Layout.getSymbolAddress(&SD);
680 Value -= FixupAddress + (1 << Log2Size);
682 report_fatal_error("unsupported relocation of undefined symbol '" +
683 Symbol->getName() + "'");
686 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
689 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
690 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
691 // rewrite the movq to an leaq at link time if the symbol ends up in
692 // the same linkage unit.
693 if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
694 Type = RIT_X86_64_GOTLoad;
696 Type = RIT_X86_64_GOT;
697 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
698 Type = RIT_X86_64_TLV;
699 } else if (Modifier != MCSymbolRefExpr::VK_None) {
700 report_fatal_error("unsupported symbol modifier in relocation");
702 Type = RIT_X86_64_Signed;
704 // The Darwin x86_64 relocation format has a problem where it cannot
705 // encode an address (L<foo> + <constant>) which is outside the atom
706 // containing L<foo>. Generally, this shouldn't occur but it does
707 // happen when we have a RIPrel instruction with data following the
708 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
709 // adjustment Darwin x86_64 uses, the offset is still negative and
710 // the linker has no way to recognize this.
712 // To work around this, Darwin uses several special relocation types
713 // to indicate the offsets. However, the specification or
714 // implementation of these seems to also be incomplete; they should
715 // adjust the addend as well based on the actual encoded instruction
716 // (the additional bias), but instead appear to just look at the
718 switch (-(Target.getConstant() + (1LL << Log2Size))) {
719 case 1: Type = RIT_X86_64_Signed1; break;
720 case 2: Type = RIT_X86_64_Signed2; break;
721 case 4: Type = RIT_X86_64_Signed4; break;
725 if (Modifier != MCSymbolRefExpr::VK_None)
726 report_fatal_error("unsupported symbol modifier in branch "
729 Type = RIT_X86_64_Branch;
732 if (Modifier == MCSymbolRefExpr::VK_GOT) {
733 Type = RIT_X86_64_GOT;
734 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
735 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
736 // which case all we do is set the PCrel bit in the relocation entry;
737 // this is used with exception handling, for example. The source is
738 // required to include any necessary offset directly.
739 Type = RIT_X86_64_GOT;
741 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
742 report_fatal_error("TLVP symbol modifier should have been rip-rel");
743 } else if (Modifier != MCSymbolRefExpr::VK_None)
744 report_fatal_error("unsupported symbol modifier in relocation");
746 Type = RIT_X86_64_Unsigned;
750 // x86_64 always writes custom values into the fixups.
753 // struct relocation_info (8 bytes)
754 MachRelocationEntry MRE;
755 MRE.Word0 = FixupOffset;
756 MRE.Word1 = ((Index << 0) |
761 Relocations[Fragment->getParent()].push_back(MRE);
764 void RecordScatteredRelocation(const MCAssembler &Asm,
765 const MCAsmLayout &Layout,
766 const MCFragment *Fragment,
767 const MCFixup &Fixup, MCValue Target,
768 uint64_t &FixedValue) {
769 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
770 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
771 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
772 unsigned Type = RIT_Vanilla;
775 const MCSymbol *A = &Target.getSymA()->getSymbol();
776 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
778 if (!A_SD->getFragment())
779 report_fatal_error("symbol '" + A->getName() +
780 "' can not be undefined in a subtraction expression");
782 uint32_t Value = Layout.getSymbolAddress(A_SD);
785 if (const MCSymbolRefExpr *B = Target.getSymB()) {
786 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
788 if (!B_SD->getFragment())
789 report_fatal_error("symbol '" + B->getSymbol().getName() +
790 "' can not be undefined in a subtraction expression");
792 // Select the appropriate difference relocation type.
794 // Note that there is no longer any semantic difference between these two
795 // relocation types from the linkers point of view, this is done solely
796 // for pedantic compatibility with 'as'.
797 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
798 Value2 = Layout.getSymbolAddress(B_SD);
801 // Relocations are written out in reverse order, so the PAIR comes first.
802 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
803 MachRelocationEntry MRE;
804 MRE.Word0 = ((0 << 0) |
810 Relocations[Fragment->getParent()].push_back(MRE);
813 MachRelocationEntry MRE;
814 MRE.Word0 = ((FixupOffset << 0) |
820 Relocations[Fragment->getParent()].push_back(MRE);
823 void RecordTLVPRelocation(const MCAssembler &Asm,
824 const MCAsmLayout &Layout,
825 const MCFragment *Fragment,
826 const MCFixup &Fixup, MCValue Target,
827 uint64_t &FixedValue) {
828 assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
830 "Should only be called with a 32-bit TLVP relocation!");
832 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
833 uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
834 unsigned IsPCRel = 0;
836 // Get the symbol data.
837 MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
838 unsigned Index = SD_A->getIndex();
840 // We're only going to have a second symbol in pic mode and it'll be a
841 // subtraction from the picbase. For 32-bit pic the addend is the difference
842 // between the picbase and the next address. For 32-bit static the addend
844 if (Target.getSymB()) {
845 // If this is a subtraction then we're pcrel.
846 uint32_t FixupAddress =
847 Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
848 MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
850 FixedValue = (FixupAddress - Layout.getSymbolAddress(SD_B) +
851 Target.getConstant());
852 FixedValue += 1ULL << Log2Size;
857 // struct relocation_info (8 bytes)
858 MachRelocationEntry MRE;
860 MRE.Word1 = ((Index << 0) |
863 (1 << 27) | // Extern
864 (RIT_TLV << 28)); // Type
865 Relocations[Fragment->getParent()].push_back(MRE);
868 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
869 const MCFragment *Fragment, const MCFixup &Fixup,
870 MCValue Target, uint64_t &FixedValue) {
872 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
876 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
877 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
879 // If this is a 32-bit TLVP reloc it's handled a bit differently.
880 if (Target.getSymA() &&
881 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
882 RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
886 // If this is a difference or a defined symbol plus an offset, then we need
887 // a scattered relocation entry.
888 // Differences always require scattered relocations.
889 if (Target.getSymB())
890 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
893 // Get the symbol data, if any.
894 MCSymbolData *SD = 0;
895 if (Target.getSymA())
896 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
898 // If this is an internal relocation with an offset, it also needs a
899 // scattered relocation entry.
900 uint32_t Offset = Target.getConstant();
902 Offset += 1 << Log2Size;
903 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
904 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
908 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
910 unsigned IsExtern = 0;
913 if (Target.isAbsolute()) { // constant
914 // SymbolNum of 0 indicates the absolute section.
916 // FIXME: Currently, these are never generated (see code below). I cannot
917 // find a case where they are actually emitted.
920 // Check whether we need an external or internal relocation.
921 if (doesSymbolRequireExternRelocation(SD)) {
923 Index = SD->getIndex();
924 // For external relocations, make sure to offset the fixup value to
925 // compensate for the addend of the symbol address, if it was
926 // undefined. This occurs with weak definitions, for example.
927 if (!SD->Symbol->isUndefined())
928 FixedValue -= Layout.getSymbolAddress(SD);
930 // The index is the section ordinal (1-based).
931 Index = SD->getFragment()->getParent()->getOrdinal() + 1;
937 // struct relocation_info (8 bytes)
938 MachRelocationEntry MRE;
939 MRE.Word0 = FixupOffset;
940 MRE.Word1 = ((Index << 0) |
945 Relocations[Fragment->getParent()].push_back(MRE);
948 void BindIndirectSymbols(MCAssembler &Asm) {
949 // This is the point where 'as' creates actual symbols for indirect symbols
950 // (in the following two passes). It would be easier for us to do this
951 // sooner when we see the attribute, but that makes getting the order in the
952 // symbol table much more complicated than it is worth.
954 // FIXME: Revisit this when the dust settles.
956 // Bind non lazy symbol pointers first.
957 unsigned IndirectIndex = 0;
958 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
959 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
960 const MCSectionMachO &Section =
961 cast<MCSectionMachO>(it->SectionData->getSection());
963 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
966 // Initialize the section indirect symbol base, if necessary.
967 if (!IndirectSymBase.count(it->SectionData))
968 IndirectSymBase[it->SectionData] = IndirectIndex;
970 Asm.getOrCreateSymbolData(*it->Symbol);
973 // Then lazy symbol pointers and symbol stubs.
975 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
976 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
977 const MCSectionMachO &Section =
978 cast<MCSectionMachO>(it->SectionData->getSection());
980 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
981 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
984 // Initialize the section indirect symbol base, if necessary.
985 if (!IndirectSymBase.count(it->SectionData))
986 IndirectSymBase[it->SectionData] = IndirectIndex;
988 // Set the symbol type to undefined lazy, but only on construction.
990 // FIXME: Do not hardcode.
992 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
994 Entry.setFlags(Entry.getFlags() | 0x0001);
998 /// ComputeSymbolTable - Compute the symbol table data
1000 /// \param StringTable [out] - The string table data.
1001 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
1003 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
1004 std::vector<MachSymbolData> &LocalSymbolData,
1005 std::vector<MachSymbolData> &ExternalSymbolData,
1006 std::vector<MachSymbolData> &UndefinedSymbolData) {
1007 // Build section lookup table.
1008 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
1010 for (MCAssembler::iterator it = Asm.begin(),
1011 ie = Asm.end(); it != ie; ++it, ++Index)
1012 SectionIndexMap[&it->getSection()] = Index;
1013 assert(Index <= 256 && "Too many sections!");
1015 // Index 0 is always the empty string.
1016 StringMap<uint64_t> StringIndexMap;
1017 StringTable += '\x00';
1019 // Build the symbol arrays and the string table, but only for non-local
1022 // The particular order that we collect the symbols and create the string
1023 // table, then sort the symbols is chosen to match 'as'. Even though it
1024 // doesn't matter for correctness, this is important for letting us diff .o
1026 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1027 ie = Asm.symbol_end(); it != ie; ++it) {
1028 const MCSymbol &Symbol = it->getSymbol();
1030 // Ignore non-linker visible symbols.
1031 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1034 if (!it->isExternal() && !Symbol.isUndefined())
1037 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1039 Entry = StringTable.size();
1040 StringTable += Symbol.getName();
1041 StringTable += '\x00';
1045 MSD.SymbolData = it;
1046 MSD.StringIndex = Entry;
1048 if (Symbol.isUndefined()) {
1049 MSD.SectionIndex = 0;
1050 UndefinedSymbolData.push_back(MSD);
1051 } else if (Symbol.isAbsolute()) {
1052 MSD.SectionIndex = 0;
1053 ExternalSymbolData.push_back(MSD);
1055 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1056 assert(MSD.SectionIndex && "Invalid section index!");
1057 ExternalSymbolData.push_back(MSD);
1061 // Now add the data for local symbols.
1062 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1063 ie = Asm.symbol_end(); it != ie; ++it) {
1064 const MCSymbol &Symbol = it->getSymbol();
1066 // Ignore non-linker visible symbols.
1067 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1070 if (it->isExternal() || Symbol.isUndefined())
1073 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1075 Entry = StringTable.size();
1076 StringTable += Symbol.getName();
1077 StringTable += '\x00';
1081 MSD.SymbolData = it;
1082 MSD.StringIndex = Entry;
1084 if (Symbol.isAbsolute()) {
1085 MSD.SectionIndex = 0;
1086 LocalSymbolData.push_back(MSD);
1088 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1089 assert(MSD.SectionIndex && "Invalid section index!");
1090 LocalSymbolData.push_back(MSD);
1094 // External and undefined symbols are required to be in lexicographic order.
1095 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1096 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1098 // Set the symbol indices.
1100 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1101 LocalSymbolData[i].SymbolData->setIndex(Index++);
1102 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1103 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1104 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1105 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1107 // The string table is padded to a multiple of 4.
1108 while (StringTable.size() % 4)
1109 StringTable += '\x00';
1112 void ExecutePostLayoutBinding(MCAssembler &Asm) {
1113 // Create symbol data for any indirect symbols.
1114 BindIndirectSymbols(Asm);
1116 // Compute symbol table information and bind symbol indices.
1117 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1118 UndefinedSymbolData);
1122 bool IsFixupFullyResolved(const MCAssembler &Asm,
1123 const MCValue Target,
1125 const MCFragment *DF) const {
1126 // If we are using scattered symbols, determine whether this value is
1127 // actually resolved; scattering may cause atoms to move.
1128 if (Asm.getBackend().hasScatteredSymbols()) {
1129 if (Asm.getBackend().hasReliableSymbolDifference()) {
1130 // If this is a PCrel relocation, find the base atom (identified by its
1131 // symbol) that the fixup value is relative to.
1132 const MCSymbolData *BaseSymbol = 0;
1134 BaseSymbol = DF->getAtom();
1139 return isScatteredFixupFullyResolved(Asm, Target, BaseSymbol);
1141 const MCSection *BaseSection = 0;
1143 BaseSection = &DF->getParent()->getSection();
1145 return isScatteredFixupFullyResolvedSimple(Asm, Target, BaseSection);
1151 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout) {
1152 unsigned NumSections = Asm.size();
1154 // The section data starts after the header, the segment load command (and
1155 // section headers) and the symbol table.
1156 unsigned NumLoadCommands = 1;
1157 uint64_t LoadCommandsSize = Is64Bit ?
1158 SegmentLoadCommand64Size + NumSections * Section64Size :
1159 SegmentLoadCommand32Size + NumSections * Section32Size;
1161 // Add the symbol table load command sizes, if used.
1162 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1163 UndefinedSymbolData.size();
1165 NumLoadCommands += 2;
1166 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
1169 // Compute the total size of the section data, as well as its file size and
1171 uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
1173 uint64_t SectionDataSize = 0;
1174 uint64_t SectionDataFileSize = 0;
1175 uint64_t VMSize = 0;
1176 for (MCAssembler::const_iterator it = Asm.begin(),
1177 ie = Asm.end(); it != ie; ++it) {
1178 const MCSectionData &SD = *it;
1179 uint64_t Address = Layout.getSectionAddress(&SD);
1180 uint64_t Size = Layout.getSectionSize(&SD);
1181 uint64_t FileSize = Layout.getSectionFileSize(&SD);
1183 VMSize = std::max(VMSize, Address + Size);
1185 if (Asm.getBackend().isVirtualSection(SD.getSection()))
1188 SectionDataSize = std::max(SectionDataSize, Address + Size);
1189 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
1192 // The section data is padded to 4 bytes.
1194 // FIXME: Is this machine dependent?
1195 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1196 SectionDataFileSize += SectionDataPadding;
1198 // Write the prolog, starting with the header and load command...
1199 WriteHeader(NumLoadCommands, LoadCommandsSize,
1200 Asm.getSubsectionsViaSymbols());
1201 WriteSegmentLoadCommand(NumSections, VMSize,
1202 SectionDataStart, SectionDataSize);
1204 // ... and then the section headers.
1205 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1206 for (MCAssembler::const_iterator it = Asm.begin(),
1207 ie = Asm.end(); it != ie; ++it) {
1208 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1209 unsigned NumRelocs = Relocs.size();
1210 uint64_t SectionStart = SectionDataStart + Layout.getSectionAddress(it);
1211 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
1212 RelocTableEnd += NumRelocs * RelocationInfoSize;
1215 // Write the symbol table load command, if used.
1217 unsigned FirstLocalSymbol = 0;
1218 unsigned NumLocalSymbols = LocalSymbolData.size();
1219 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1220 unsigned NumExternalSymbols = ExternalSymbolData.size();
1221 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1222 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1223 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1224 unsigned NumSymTabSymbols =
1225 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1226 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1227 uint64_t IndirectSymbolOffset = 0;
1229 // If used, the indirect symbols are written after the section data.
1230 if (NumIndirectSymbols)
1231 IndirectSymbolOffset = RelocTableEnd;
1233 // The symbol table is written after the indirect symbol data.
1234 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1236 // The string table is written after symbol table.
1237 uint64_t StringTableOffset =
1238 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
1240 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1241 StringTableOffset, StringTable.size());
1243 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1244 FirstExternalSymbol, NumExternalSymbols,
1245 FirstUndefinedSymbol, NumUndefinedSymbols,
1246 IndirectSymbolOffset, NumIndirectSymbols);
1249 // Write the actual section data.
1250 for (MCAssembler::const_iterator it = Asm.begin(),
1251 ie = Asm.end(); it != ie; ++it)
1252 Asm.WriteSectionData(it, Layout, Writer);
1254 // Write the extra padding.
1255 WriteZeros(SectionDataPadding);
1257 // Write the relocation entries.
1258 for (MCAssembler::const_iterator it = Asm.begin(),
1259 ie = Asm.end(); it != ie; ++it) {
1260 // Write the section relocation entries, in reverse order to match 'as'
1261 // (approximately, the exact algorithm is more complicated than this).
1262 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1263 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1264 Write32(Relocs[e - i - 1].Word0);
1265 Write32(Relocs[e - i - 1].Word1);
1269 // Write the symbol table data, if used.
1271 // Write the indirect symbol entries.
1272 for (MCAssembler::const_indirect_symbol_iterator
1273 it = Asm.indirect_symbol_begin(),
1274 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1275 // Indirect symbols in the non lazy symbol pointer section have some
1276 // special handling.
1277 const MCSectionMachO &Section =
1278 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1279 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1280 // If this symbol is defined and internal, mark it as such.
1281 if (it->Symbol->isDefined() &&
1282 !Asm.getSymbolData(*it->Symbol).isExternal()) {
1283 uint32_t Flags = ISF_Local;
1284 if (it->Symbol->isAbsolute())
1285 Flags |= ISF_Absolute;
1291 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1294 // FIXME: Check that offsets match computed ones.
1296 // Write the symbol table entries.
1297 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1298 WriteNlist(LocalSymbolData[i], Layout);
1299 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1300 WriteNlist(ExternalSymbolData[i], Layout);
1301 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1302 WriteNlist(UndefinedSymbolData[i], Layout);
1304 // Write the string table.
1305 OS << StringTable.str();
1312 MachObjectWriter::MachObjectWriter(raw_ostream &OS,
1314 bool IsLittleEndian)
1315 : MCObjectWriter(OS, IsLittleEndian)
1317 Impl = new MachObjectWriterImpl(this, Is64Bit);
1320 MachObjectWriter::~MachObjectWriter() {
1321 delete (MachObjectWriterImpl*) Impl;
1324 void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1325 ((MachObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1328 void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
1329 const MCAsmLayout &Layout,
1330 const MCFragment *Fragment,
1331 const MCFixup &Fixup, MCValue Target,
1332 uint64_t &FixedValue) {
1333 ((MachObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1334 Target, FixedValue);
1337 bool MachObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1338 const MCValue Target,
1340 const MCFragment *DF) const {
1341 return ((MachObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1345 void MachObjectWriter::WriteObject(const MCAssembler &Asm,
1346 const MCAsmLayout &Layout) {
1347 ((MachObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);