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/ADT/StringMap.h"
11 #include "llvm/ADT/Twine.h"
12 #include "llvm/MC/MCAssembler.h"
13 #include "llvm/MC/MCAsmLayout.h"
14 #include "llvm/MC/MCExpr.h"
15 #include "llvm/MC/MCObjectWriter.h"
16 #include "llvm/MC/MCSectionMachO.h"
17 #include "llvm/MC/MCSymbol.h"
18 #include "llvm/MC/MCMachOSymbolFlags.h"
19 #include "llvm/MC/MCValue.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/MachO.h"
22 #include "llvm/Target/TargetAsmBackend.h"
25 #include "../Target/X86/X86FixupKinds.h"
30 // FIXME: this has been copied from (or to) X86AsmBackend.cpp
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 X86::reloc_signed_4byte:
42 case FK_Data_4: return 2;
43 case FK_Data_8: return 3;
47 static bool isFixupKindPCRel(unsigned Kind) {
51 case X86::reloc_pcrel_1byte:
52 case X86::reloc_pcrel_2byte:
53 case X86::reloc_pcrel_4byte:
54 case X86::reloc_riprel_4byte:
55 case X86::reloc_riprel_4byte_movq_load:
60 static bool isFixupKindRIPRel(unsigned Kind) {
61 return Kind == X86::reloc_riprel_4byte ||
62 Kind == X86::reloc_riprel_4byte_movq_load;
65 static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
66 // Undefined symbols are always extern.
67 if (SD->Symbol->isUndefined())
70 // References to weak definitions require external relocation entries; the
71 // definition may not always be the one in the same object file.
72 if (SD->getFlags() & SF_WeakDefinition)
75 // Otherwise, we can use an internal relocation.
79 static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
81 const MCSymbolData *BaseSymbol) {
82 // The effective fixup address is
83 // addr(atom(A)) + offset(A)
84 // - addr(atom(B)) - offset(B)
85 // - addr(BaseSymbol) + <fixup offset from base symbol>
86 // and the offsets are not relocatable, so the fixup is fully resolved when
87 // addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
89 // Note that "false" is almost always conservatively correct (it means we emit
90 // a relocation which is unnecessary), except when it would force us to emit a
91 // relocation which the target cannot encode.
93 const MCSymbolData *A_Base = 0, *B_Base = 0;
94 if (const MCSymbolRefExpr *A = Target.getSymA()) {
95 // Modified symbol references cannot be resolved.
96 if (A->getKind() != MCSymbolRefExpr::VK_None)
99 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
104 if (const MCSymbolRefExpr *B = Target.getSymB()) {
105 // Modified symbol references cannot be resolved.
106 if (B->getKind() != MCSymbolRefExpr::VK_None)
109 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
114 // If there is no base, A and B have to be the same atom for this fixup to be
117 return A_Base == B_Base;
119 // Otherwise, B must be missing and A must be the base.
120 return !B_Base && BaseSymbol == A_Base;
123 static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
124 const MCValue Target,
125 const MCSection *BaseSection) {
126 // The effective fixup address is
127 // addr(atom(A)) + offset(A)
128 // - addr(atom(B)) - offset(B)
129 // - addr(<base symbol>) + <fixup offset from base symbol>
130 // and the offsets are not relocatable, so the fixup is fully resolved when
131 // addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
133 // The simple (Darwin, except on x86_64) way of dealing with this was to
134 // assume that any reference to a temporary symbol *must* be a temporary
135 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
136 // relocation to a temporary symbol (in the same section) is fully
137 // resolved. This also works in conjunction with absolutized .set, which
138 // requires the compiler to use .set to absolutize the differences between
139 // symbols which the compiler knows to be assembly time constants, so we don't
140 // need to worry about considering symbol differences fully resolved.
142 // Non-relative fixups are only resolved if constant.
144 return Target.isAbsolute();
146 // Otherwise, relative fixups are only resolved if not a difference and the
147 // target is a temporary in the same section.
148 if (Target.isAbsolute() || Target.getSymB())
151 const MCSymbol *A = &Target.getSymA()->getSymbol();
152 if (!A->isTemporary() || !A->isInSection() ||
153 &A->getSection() != BaseSection)
161 class MachObjectWriter : public MCObjectWriter {
162 // See <mach-o/loader.h>.
164 Header_Magic32 = 0xFEEDFACE,
165 Header_Magic64 = 0xFEEDFACF
171 SegmentLoadCommand32Size = 56,
172 SegmentLoadCommand64Size = 72,
175 SymtabLoadCommandSize = 24,
176 DysymtabLoadCommandSize = 80,
179 RelocationInfoSize = 8
182 enum HeaderFileType {
187 HF_SubsectionsViaSymbols = 0x2000
190 enum LoadCommandType {
197 // See <mach-o/nlist.h>.
198 enum SymbolTypeType {
199 STT_Undefined = 0x00,
204 enum SymbolTypeFlags {
205 // If any of these bits are set, then the entry is a stab entry number (see
206 // <mach-o/stab.h>. Otherwise the other masks apply.
207 STF_StabsEntryMask = 0xe0,
211 STF_PrivateExtern = 0x10
214 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
216 enum IndirectSymbolFlags {
217 ISF_Local = 0x80000000,
218 ISF_Absolute = 0x40000000
221 /// RelocationFlags - Special flags for addresses.
222 enum RelocationFlags {
223 RF_Scattered = 0x80000000
226 enum RelocationInfoType {
230 RIT_PreboundLazyPointer = 3,
231 RIT_LocalDifference = 4,
235 /// X86_64 uses its own relocation types.
236 enum RelocationInfoTypeX86_64 {
237 RIT_X86_64_Unsigned = 0,
238 RIT_X86_64_Signed = 1,
239 RIT_X86_64_Branch = 2,
240 RIT_X86_64_GOTLoad = 3,
242 RIT_X86_64_Subtractor = 5,
243 RIT_X86_64_Signed1 = 6,
244 RIT_X86_64_Signed2 = 7,
245 RIT_X86_64_Signed4 = 8,
249 /// MachSymbolData - Helper struct for containing some precomputed information
251 struct MachSymbolData {
252 MCSymbolData *SymbolData;
253 uint64_t StringIndex;
254 uint8_t SectionIndex;
256 // Support lexicographic sorting.
257 bool operator<(const MachSymbolData &RHS) const {
258 return SymbolData->getSymbol().getName() <
259 RHS.SymbolData->getSymbol().getName();
263 /// @name Relocation Data
266 struct MachRelocationEntry {
271 llvm::DenseMap<const MCSectionData*,
272 std::vector<MachRelocationEntry> > Relocations;
273 llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
276 /// @name Symbol Table Data
279 SmallString<256> StringTable;
280 std::vector<MachSymbolData> LocalSymbolData;
281 std::vector<MachSymbolData> ExternalSymbolData;
282 std::vector<MachSymbolData> UndefinedSymbolData;
286 unsigned Is64Bit : 1;
292 MachObjectWriter(raw_ostream &_OS,
293 bool _Is64Bit, uint32_t _CPUType, uint32_t _CPUSubtype,
294 bool _IsLittleEndian)
295 : MCObjectWriter(_OS, _IsLittleEndian),
296 Is64Bit(_Is64Bit), CPUType(_CPUType), CPUSubtype(_CPUSubtype) {
299 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
300 bool SubsectionsViaSymbols) {
303 if (SubsectionsViaSymbols)
304 Flags |= HF_SubsectionsViaSymbols;
306 // struct mach_header (28 bytes) or
307 // struct mach_header_64 (32 bytes)
309 uint64_t Start = OS.tell();
312 Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
318 Write32(NumLoadCommands); // Object files have a single load command, the
320 Write32(LoadCommandsSize);
323 Write32(0); // reserved
325 assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
328 /// WriteSegmentLoadCommand - Write a segment load command.
330 /// \arg NumSections - The number of sections in this segment.
331 /// \arg SectionDataSize - The total size of the sections.
332 void WriteSegmentLoadCommand(unsigned NumSections,
334 uint64_t SectionDataStartOffset,
335 uint64_t SectionDataSize) {
336 // struct segment_command (56 bytes) or
337 // struct segment_command_64 (72 bytes)
339 uint64_t Start = OS.tell();
342 unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
343 SegmentLoadCommand32Size;
344 Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
345 Write32(SegmentLoadCommandSize +
346 NumSections * (Is64Bit ? Section64Size : Section32Size));
350 Write64(0); // vmaddr
351 Write64(VMSize); // vmsize
352 Write64(SectionDataStartOffset); // file offset
353 Write64(SectionDataSize); // file size
355 Write32(0); // vmaddr
356 Write32(VMSize); // vmsize
357 Write32(SectionDataStartOffset); // file offset
358 Write32(SectionDataSize); // file size
360 Write32(0x7); // maxprot
361 Write32(0x7); // initprot
362 Write32(NumSections);
365 assert(OS.tell() - Start == SegmentLoadCommandSize);
368 void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
369 const MCSectionData &SD, uint64_t FileOffset,
370 uint64_t RelocationsStart, unsigned NumRelocations) {
371 uint64_t SectionSize = Layout.getSectionSize(&SD);
373 // The offset is unused for virtual sections.
374 if (SD.getSection().isVirtualSection()) {
375 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
379 // struct section (68 bytes) or
380 // struct section_64 (80 bytes)
382 uint64_t Start = OS.tell();
385 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
386 WriteBytes(Section.getSectionName(), 16);
387 WriteBytes(Section.getSegmentName(), 16);
389 Write64(Layout.getSectionAddress(&SD)); // address
390 Write64(SectionSize); // size
392 Write32(Layout.getSectionAddress(&SD)); // address
393 Write32(SectionSize); // size
397 unsigned Flags = Section.getTypeAndAttributes();
398 if (SD.hasInstructions())
399 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
401 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
402 Write32(Log2_32(SD.getAlignment()));
403 Write32(NumRelocations ? RelocationsStart : 0);
404 Write32(NumRelocations);
406 Write32(IndirectSymBase.lookup(&SD)); // reserved1
407 Write32(Section.getStubSize()); // reserved2
409 Write32(0); // reserved3
411 assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
414 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
415 uint32_t StringTableOffset,
416 uint32_t StringTableSize) {
417 // struct symtab_command (24 bytes)
419 uint64_t Start = OS.tell();
423 Write32(SymtabLoadCommandSize);
424 Write32(SymbolOffset);
426 Write32(StringTableOffset);
427 Write32(StringTableSize);
429 assert(OS.tell() - Start == SymtabLoadCommandSize);
432 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
433 uint32_t NumLocalSymbols,
434 uint32_t FirstExternalSymbol,
435 uint32_t NumExternalSymbols,
436 uint32_t FirstUndefinedSymbol,
437 uint32_t NumUndefinedSymbols,
438 uint32_t IndirectSymbolOffset,
439 uint32_t NumIndirectSymbols) {
440 // struct dysymtab_command (80 bytes)
442 uint64_t Start = OS.tell();
445 Write32(LCT_Dysymtab);
446 Write32(DysymtabLoadCommandSize);
447 Write32(FirstLocalSymbol);
448 Write32(NumLocalSymbols);
449 Write32(FirstExternalSymbol);
450 Write32(NumExternalSymbols);
451 Write32(FirstUndefinedSymbol);
452 Write32(NumUndefinedSymbols);
453 Write32(0); // tocoff
455 Write32(0); // modtaboff
456 Write32(0); // nmodtab
457 Write32(0); // extrefsymoff
458 Write32(0); // nextrefsyms
459 Write32(IndirectSymbolOffset);
460 Write32(NumIndirectSymbols);
461 Write32(0); // extreloff
462 Write32(0); // nextrel
463 Write32(0); // locreloff
464 Write32(0); // nlocrel
466 assert(OS.tell() - Start == DysymtabLoadCommandSize);
469 void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
470 MCSymbolData &Data = *MSD.SymbolData;
471 const MCSymbol &Symbol = Data.getSymbol();
473 uint16_t Flags = Data.getFlags();
474 uint32_t Address = 0;
476 // Set the N_TYPE bits. See <mach-o/nlist.h>.
478 // FIXME: Are the prebound or indirect fields possible here?
479 if (Symbol.isUndefined())
480 Type = STT_Undefined;
481 else if (Symbol.isAbsolute())
486 // FIXME: Set STAB bits.
488 if (Data.isPrivateExtern())
489 Type |= STF_PrivateExtern;
492 if (Data.isExternal() || Symbol.isUndefined())
493 Type |= STF_External;
495 // Compute the symbol address.
496 if (Symbol.isDefined()) {
497 if (Symbol.isAbsolute()) {
498 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
500 Address = Layout.getSymbolAddress(&Data);
502 } else if (Data.isCommon()) {
503 // Common symbols are encoded with the size in the address
504 // field, and their alignment in the flags.
505 Address = Data.getCommonSize();
507 // Common alignment is packed into the 'desc' bits.
508 if (unsigned Align = Data.getCommonAlignment()) {
509 unsigned Log2Size = Log2_32(Align);
510 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
512 report_fatal_error("invalid 'common' alignment '" +
514 // FIXME: Keep this mask with the SymbolFlags enumeration.
515 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
519 // struct nlist (12 bytes)
521 Write32(MSD.StringIndex);
523 Write8(MSD.SectionIndex);
525 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
534 // FIXME: We really need to improve the relocation validation. Basically, we
535 // want to implement a separate computation which evaluates the relocation
536 // entry as the linker would, and verifies that the resultant fixup value is
537 // exactly what the encoder wanted. This will catch several classes of
540 // - Relocation entry bugs, the two algorithms are unlikely to have the same
543 // - Relaxation issues, where we forget to relax something.
545 // - Input errors, where something cannot be correctly encoded. 'as' allows
546 // these through in many cases.
548 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
549 const MCFragment *Fragment,
550 const MCFixup &Fixup, MCValue Target,
551 uint64_t &FixedValue) {
552 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
553 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
554 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
557 uint32_t FixupOffset =
558 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
559 uint32_t FixupAddress =
560 Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
563 unsigned IsExtern = 0;
566 Value = Target.getConstant();
569 // Compensate for the relocation offset, Darwin x86_64 relocations only
570 // have the addend and appear to have attempted to define it to be the
571 // actual expression addend without the PCrel bias. However, instructions
572 // with data following the relocation are not accomodated for (see comment
573 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
574 Value += 1LL << Log2Size;
577 if (Target.isAbsolute()) { // constant
578 // SymbolNum of 0 indicates the absolute section.
579 Type = RIT_X86_64_Unsigned;
582 // FIXME: I believe this is broken, I don't think the linker can
583 // understand it. I think it would require a local relocation, but I'm not
584 // sure if that would work either. The official way to get an absolute
585 // PCrel relocation is to use an absolute symbol (which we don't support
589 Type = RIT_X86_64_Branch;
591 } else if (Target.getSymB()) { // A - B + constant
592 const MCSymbol *A = &Target.getSymA()->getSymbol();
593 MCSymbolData &A_SD = Asm.getSymbolData(*A);
594 const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
596 const MCSymbol *B = &Target.getSymB()->getSymbol();
597 MCSymbolData &B_SD = Asm.getSymbolData(*B);
598 const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
600 // Neither symbol can be modified.
601 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
602 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
603 report_fatal_error("unsupported relocation of modified symbol");
605 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
606 // implement most of these correctly.
608 report_fatal_error("unsupported pc-relative relocation of difference");
610 // The support for the situation where one or both of the symbols would
611 // require a local relocation is handled just like if the symbols were
612 // external. This is certainly used in the case of debug sections where
613 // the section has only temporary symbols and thus the symbols don't have
614 // base symbols. This is encoded using the section ordinal and
615 // non-extern relocation entries.
617 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
618 // a single SIGNED relocation); reject it for now. Except the case where
619 // both symbols don't have a base, equal but both NULL.
620 if (A_Base == B_Base && A_Base)
621 report_fatal_error("unsupported relocation with identical base");
623 Value += Layout.getSymbolAddress(&A_SD) -
624 (A_Base == NULL ? 0 : Layout.getSymbolAddress(A_Base));
625 Value -= Layout.getSymbolAddress(&B_SD) -
626 (B_Base == NULL ? 0 : Layout.getSymbolAddress(B_Base));
629 Index = A_Base->getIndex();
633 Index = A_SD.getFragment()->getParent()->getOrdinal() + 1;
636 Type = RIT_X86_64_Unsigned;
638 MachRelocationEntry MRE;
639 MRE.Word0 = FixupOffset;
640 MRE.Word1 = ((Index << 0) |
645 Relocations[Fragment->getParent()].push_back(MRE);
648 Index = B_Base->getIndex();
652 Index = B_SD.getFragment()->getParent()->getOrdinal() + 1;
655 Type = RIT_X86_64_Subtractor;
657 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
658 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
659 const MCSymbolData *Base = Asm.getAtom(&SD);
661 // Relocations inside debug sections always use local relocations when
662 // possible. This seems to be done because the debugger doesn't fully
663 // understand x86_64 relocation entries, and expects to find values that
664 // have already been fixed up.
665 if (Symbol->isInSection()) {
666 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
667 Fragment->getParent()->getSection());
668 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
672 // x86_64 almost always uses external relocations, except when there is no
673 // symbol to use as a base address (a local symbol with no preceeding
674 // non-local symbol).
676 Index = Base->getIndex();
679 // Add the local offset, if needed.
681 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
682 } else if (Symbol->isInSection()) {
683 // The index is the section ordinal (1-based).
684 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
686 Value += Layout.getSymbolAddress(&SD);
689 Value -= FixupAddress + (1 << Log2Size);
691 report_fatal_error("unsupported relocation of undefined symbol '" +
692 Symbol->getName() + "'");
695 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
698 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
699 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
700 // rewrite the movq to an leaq at link time if the symbol ends up in
701 // the same linkage unit.
702 if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
703 Type = RIT_X86_64_GOTLoad;
705 Type = RIT_X86_64_GOT;
706 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
707 Type = RIT_X86_64_TLV;
708 } else if (Modifier != MCSymbolRefExpr::VK_None) {
709 report_fatal_error("unsupported symbol modifier in relocation");
711 Type = RIT_X86_64_Signed;
713 // The Darwin x86_64 relocation format has a problem where it cannot
714 // encode an address (L<foo> + <constant>) which is outside the atom
715 // containing L<foo>. Generally, this shouldn't occur but it does
716 // happen when we have a RIPrel instruction with data following the
717 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
718 // adjustment Darwin x86_64 uses, the offset is still negative and
719 // the linker has no way to recognize this.
721 // To work around this, Darwin uses several special relocation types
722 // to indicate the offsets. However, the specification or
723 // implementation of these seems to also be incomplete; they should
724 // adjust the addend as well based on the actual encoded instruction
725 // (the additional bias), but instead appear to just look at the
727 switch (-(Target.getConstant() + (1LL << Log2Size))) {
728 case 1: Type = RIT_X86_64_Signed1; break;
729 case 2: Type = RIT_X86_64_Signed2; break;
730 case 4: Type = RIT_X86_64_Signed4; break;
734 if (Modifier != MCSymbolRefExpr::VK_None)
735 report_fatal_error("unsupported symbol modifier in branch "
738 Type = RIT_X86_64_Branch;
741 if (Modifier == MCSymbolRefExpr::VK_GOT) {
742 Type = RIT_X86_64_GOT;
743 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
744 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
745 // which case all we do is set the PCrel bit in the relocation entry;
746 // this is used with exception handling, for example. The source is
747 // required to include any necessary offset directly.
748 Type = RIT_X86_64_GOT;
750 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
751 report_fatal_error("TLVP symbol modifier should have been rip-rel");
752 } else if (Modifier != MCSymbolRefExpr::VK_None)
753 report_fatal_error("unsupported symbol modifier in relocation");
755 Type = RIT_X86_64_Unsigned;
759 // x86_64 always writes custom values into the fixups.
762 // struct relocation_info (8 bytes)
763 MachRelocationEntry MRE;
764 MRE.Word0 = FixupOffset;
765 MRE.Word1 = ((Index << 0) |
770 Relocations[Fragment->getParent()].push_back(MRE);
773 void RecordScatteredRelocation(const MCAssembler &Asm,
774 const MCAsmLayout &Layout,
775 const MCFragment *Fragment,
776 const MCFixup &Fixup, MCValue Target,
777 uint64_t &FixedValue) {
778 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
779 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
780 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
781 unsigned Type = RIT_Vanilla;
784 const MCSymbol *A = &Target.getSymA()->getSymbol();
785 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
787 if (!A_SD->getFragment())
788 report_fatal_error("symbol '" + A->getName() +
789 "' can not be undefined in a subtraction expression");
791 uint32_t Value = Layout.getSymbolAddress(A_SD);
794 if (const MCSymbolRefExpr *B = Target.getSymB()) {
795 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
797 if (!B_SD->getFragment())
798 report_fatal_error("symbol '" + B->getSymbol().getName() +
799 "' can not be undefined in a subtraction expression");
801 // Select the appropriate difference relocation type.
803 // Note that there is no longer any semantic difference between these two
804 // relocation types from the linkers point of view, this is done solely
805 // for pedantic compatibility with 'as'.
806 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
807 Value2 = Layout.getSymbolAddress(B_SD);
810 // Relocations are written out in reverse order, so the PAIR comes first.
811 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
812 MachRelocationEntry MRE;
813 MRE.Word0 = ((0 << 0) |
819 Relocations[Fragment->getParent()].push_back(MRE);
822 MachRelocationEntry MRE;
823 MRE.Word0 = ((FixupOffset << 0) |
829 Relocations[Fragment->getParent()].push_back(MRE);
832 void RecordTLVPRelocation(const MCAssembler &Asm,
833 const MCAsmLayout &Layout,
834 const MCFragment *Fragment,
835 const MCFixup &Fixup, MCValue Target,
836 uint64_t &FixedValue) {
837 assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
839 "Should only be called with a 32-bit TLVP relocation!");
841 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
842 uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
843 unsigned IsPCRel = 0;
845 // Get the symbol data.
846 MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
847 unsigned Index = SD_A->getIndex();
849 // We're only going to have a second symbol in pic mode and it'll be a
850 // subtraction from the picbase. For 32-bit pic the addend is the difference
851 // between the picbase and the next address. For 32-bit static the addend
853 if (Target.getSymB()) {
854 // If this is a subtraction then we're pcrel.
855 uint32_t FixupAddress =
856 Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
857 MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
859 FixedValue = (FixupAddress - Layout.getSymbolAddress(SD_B) +
860 Target.getConstant());
861 FixedValue += 1ULL << Log2Size;
866 // struct relocation_info (8 bytes)
867 MachRelocationEntry MRE;
869 MRE.Word1 = ((Index << 0) |
872 (1 << 27) | // Extern
873 (RIT_TLV << 28)); // Type
874 Relocations[Fragment->getParent()].push_back(MRE);
877 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
878 const MCFragment *Fragment, const MCFixup &Fixup,
879 MCValue Target, uint64_t &FixedValue) {
881 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
885 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
886 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
888 // If this is a 32-bit TLVP reloc it's handled a bit differently.
889 if (Target.getSymA() &&
890 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
891 RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
895 // If this is a difference or a defined symbol plus an offset, then we need
896 // a scattered relocation entry.
897 // Differences always require scattered relocations.
898 if (Target.getSymB())
899 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
902 // Get the symbol data, if any.
903 MCSymbolData *SD = 0;
904 if (Target.getSymA())
905 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
907 // If this is an internal relocation with an offset, it also needs a
908 // scattered relocation entry.
909 uint32_t Offset = Target.getConstant();
911 Offset += 1 << Log2Size;
912 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
913 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
917 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
919 unsigned IsExtern = 0;
922 if (Target.isAbsolute()) { // constant
923 // SymbolNum of 0 indicates the absolute section.
925 // FIXME: Currently, these are never generated (see code below). I cannot
926 // find a case where they are actually emitted.
929 // Check whether we need an external or internal relocation.
930 if (doesSymbolRequireExternRelocation(SD)) {
932 Index = SD->getIndex();
933 // For external relocations, make sure to offset the fixup value to
934 // compensate for the addend of the symbol address, if it was
935 // undefined. This occurs with weak definitions, for example.
936 if (!SD->Symbol->isUndefined())
937 FixedValue -= Layout.getSymbolAddress(SD);
939 // The index is the section ordinal (1-based).
940 Index = SD->getFragment()->getParent()->getOrdinal() + 1;
946 // struct relocation_info (8 bytes)
947 MachRelocationEntry MRE;
948 MRE.Word0 = FixupOffset;
949 MRE.Word1 = ((Index << 0) |
954 Relocations[Fragment->getParent()].push_back(MRE);
957 void BindIndirectSymbols(MCAssembler &Asm) {
958 // This is the point where 'as' creates actual symbols for indirect symbols
959 // (in the following two passes). It would be easier for us to do this
960 // sooner when we see the attribute, but that makes getting the order in the
961 // symbol table much more complicated than it is worth.
963 // FIXME: Revisit this when the dust settles.
965 // Bind non lazy symbol pointers first.
966 unsigned IndirectIndex = 0;
967 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
968 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
969 const MCSectionMachO &Section =
970 cast<MCSectionMachO>(it->SectionData->getSection());
972 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
975 // Initialize the section indirect symbol base, if necessary.
976 if (!IndirectSymBase.count(it->SectionData))
977 IndirectSymBase[it->SectionData] = IndirectIndex;
979 Asm.getOrCreateSymbolData(*it->Symbol);
982 // Then lazy symbol pointers and symbol stubs.
984 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
985 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
986 const MCSectionMachO &Section =
987 cast<MCSectionMachO>(it->SectionData->getSection());
989 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
990 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
993 // Initialize the section indirect symbol base, if necessary.
994 if (!IndirectSymBase.count(it->SectionData))
995 IndirectSymBase[it->SectionData] = IndirectIndex;
997 // Set the symbol type to undefined lazy, but only on construction.
999 // FIXME: Do not hardcode.
1001 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
1003 Entry.setFlags(Entry.getFlags() | 0x0001);
1007 /// ComputeSymbolTable - Compute the symbol table data
1009 /// \param StringTable [out] - The string table data.
1010 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
1012 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
1013 std::vector<MachSymbolData> &LocalSymbolData,
1014 std::vector<MachSymbolData> &ExternalSymbolData,
1015 std::vector<MachSymbolData> &UndefinedSymbolData) {
1016 // Build section lookup table.
1017 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
1019 for (MCAssembler::iterator it = Asm.begin(),
1020 ie = Asm.end(); it != ie; ++it, ++Index)
1021 SectionIndexMap[&it->getSection()] = Index;
1022 assert(Index <= 256 && "Too many sections!");
1024 // Index 0 is always the empty string.
1025 StringMap<uint64_t> StringIndexMap;
1026 StringTable += '\x00';
1028 // Build the symbol arrays and the string table, but only for non-local
1031 // The particular order that we collect the symbols and create the string
1032 // table, then sort the symbols is chosen to match 'as'. Even though it
1033 // doesn't matter for correctness, this is important for letting us diff .o
1035 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1036 ie = Asm.symbol_end(); it != ie; ++it) {
1037 const MCSymbol &Symbol = it->getSymbol();
1039 // Ignore non-linker visible symbols.
1040 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1043 if (!it->isExternal() && !Symbol.isUndefined())
1046 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1048 Entry = StringTable.size();
1049 StringTable += Symbol.getName();
1050 StringTable += '\x00';
1054 MSD.SymbolData = it;
1055 MSD.StringIndex = Entry;
1057 if (Symbol.isUndefined()) {
1058 MSD.SectionIndex = 0;
1059 UndefinedSymbolData.push_back(MSD);
1060 } else if (Symbol.isAbsolute()) {
1061 MSD.SectionIndex = 0;
1062 ExternalSymbolData.push_back(MSD);
1064 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1065 assert(MSD.SectionIndex && "Invalid section index!");
1066 ExternalSymbolData.push_back(MSD);
1070 // Now add the data for local symbols.
1071 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1072 ie = Asm.symbol_end(); it != ie; ++it) {
1073 const MCSymbol &Symbol = it->getSymbol();
1075 // Ignore non-linker visible symbols.
1076 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1079 if (it->isExternal() || Symbol.isUndefined())
1082 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1084 Entry = StringTable.size();
1085 StringTable += Symbol.getName();
1086 StringTable += '\x00';
1090 MSD.SymbolData = it;
1091 MSD.StringIndex = Entry;
1093 if (Symbol.isAbsolute()) {
1094 MSD.SectionIndex = 0;
1095 LocalSymbolData.push_back(MSD);
1097 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1098 assert(MSD.SectionIndex && "Invalid section index!");
1099 LocalSymbolData.push_back(MSD);
1103 // External and undefined symbols are required to be in lexicographic order.
1104 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1105 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1107 // Set the symbol indices.
1109 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1110 LocalSymbolData[i].SymbolData->setIndex(Index++);
1111 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1112 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1113 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1114 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1116 // The string table is padded to a multiple of 4.
1117 while (StringTable.size() % 4)
1118 StringTable += '\x00';
1121 void ExecutePostLayoutBinding(MCAssembler &Asm) {
1122 // Create symbol data for any indirect symbols.
1123 BindIndirectSymbols(Asm);
1125 // Compute symbol table information and bind symbol indices.
1126 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1127 UndefinedSymbolData);
1131 bool IsFixupFullyResolved(const MCAssembler &Asm,
1132 const MCValue Target,
1134 const MCFragment *DF) const {
1135 // If we are using scattered symbols, determine whether this value is
1136 // actually resolved; scattering may cause atoms to move.
1137 if (Asm.getBackend().hasScatteredSymbols()) {
1138 if (Asm.getBackend().hasReliableSymbolDifference()) {
1139 // If this is a PCrel relocation, find the base atom (identified by its
1140 // symbol) that the fixup value is relative to.
1141 const MCSymbolData *BaseSymbol = 0;
1143 BaseSymbol = DF->getAtom();
1148 return isScatteredFixupFullyResolved(Asm, Target, BaseSymbol);
1150 const MCSection *BaseSection = 0;
1152 BaseSection = &DF->getParent()->getSection();
1154 return isScatteredFixupFullyResolvedSimple(Asm, Target, BaseSection);
1160 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
1161 unsigned NumSections = Asm.size();
1163 // The section data starts after the header, the segment load command (and
1164 // section headers) and the symbol table.
1165 unsigned NumLoadCommands = 1;
1166 uint64_t LoadCommandsSize = Is64Bit ?
1167 SegmentLoadCommand64Size + NumSections * Section64Size :
1168 SegmentLoadCommand32Size + NumSections * Section32Size;
1170 // Add the symbol table load command sizes, if used.
1171 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1172 UndefinedSymbolData.size();
1174 NumLoadCommands += 2;
1175 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
1178 // Compute the total size of the section data, as well as its file size and
1180 uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
1182 uint64_t SectionDataSize = 0;
1183 uint64_t SectionDataFileSize = 0;
1184 uint64_t VMSize = 0;
1185 for (MCAssembler::const_iterator it = Asm.begin(),
1186 ie = Asm.end(); it != ie; ++it) {
1187 const MCSectionData &SD = *it;
1188 uint64_t Address = Layout.getSectionAddress(&SD);
1189 uint64_t Size = Layout.getSectionSize(&SD);
1190 uint64_t FileSize = Layout.getSectionFileSize(&SD);
1192 VMSize = std::max(VMSize, Address + Size);
1194 if (SD.getSection().isVirtualSection())
1197 SectionDataSize = std::max(SectionDataSize, Address + Size);
1198 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
1201 // The section data is padded to 4 bytes.
1203 // FIXME: Is this machine dependent?
1204 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1205 SectionDataFileSize += SectionDataPadding;
1207 // Write the prolog, starting with the header and load command...
1208 WriteHeader(NumLoadCommands, LoadCommandsSize,
1209 Asm.getSubsectionsViaSymbols());
1210 WriteSegmentLoadCommand(NumSections, VMSize,
1211 SectionDataStart, SectionDataSize);
1213 // ... and then the section headers.
1214 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1215 for (MCAssembler::const_iterator it = Asm.begin(),
1216 ie = Asm.end(); it != ie; ++it) {
1217 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1218 unsigned NumRelocs = Relocs.size();
1219 uint64_t SectionStart = SectionDataStart + Layout.getSectionAddress(it);
1220 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
1221 RelocTableEnd += NumRelocs * RelocationInfoSize;
1224 // Write the symbol table load command, if used.
1226 unsigned FirstLocalSymbol = 0;
1227 unsigned NumLocalSymbols = LocalSymbolData.size();
1228 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1229 unsigned NumExternalSymbols = ExternalSymbolData.size();
1230 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1231 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1232 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1233 unsigned NumSymTabSymbols =
1234 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1235 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1236 uint64_t IndirectSymbolOffset = 0;
1238 // If used, the indirect symbols are written after the section data.
1239 if (NumIndirectSymbols)
1240 IndirectSymbolOffset = RelocTableEnd;
1242 // The symbol table is written after the indirect symbol data.
1243 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1245 // The string table is written after symbol table.
1246 uint64_t StringTableOffset =
1247 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
1249 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1250 StringTableOffset, StringTable.size());
1252 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1253 FirstExternalSymbol, NumExternalSymbols,
1254 FirstUndefinedSymbol, NumUndefinedSymbols,
1255 IndirectSymbolOffset, NumIndirectSymbols);
1258 // Write the actual section data.
1259 for (MCAssembler::const_iterator it = Asm.begin(),
1260 ie = Asm.end(); it != ie; ++it)
1261 Asm.WriteSectionData(it, Layout, this);
1263 // Write the extra padding.
1264 WriteZeros(SectionDataPadding);
1266 // Write the relocation entries.
1267 for (MCAssembler::const_iterator it = Asm.begin(),
1268 ie = Asm.end(); it != ie; ++it) {
1269 // Write the section relocation entries, in reverse order to match 'as'
1270 // (approximately, the exact algorithm is more complicated than this).
1271 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1272 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1273 Write32(Relocs[e - i - 1].Word0);
1274 Write32(Relocs[e - i - 1].Word1);
1278 // Write the symbol table data, if used.
1280 // Write the indirect symbol entries.
1281 for (MCAssembler::const_indirect_symbol_iterator
1282 it = Asm.indirect_symbol_begin(),
1283 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1284 // Indirect symbols in the non lazy symbol pointer section have some
1285 // special handling.
1286 const MCSectionMachO &Section =
1287 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1288 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1289 // If this symbol is defined and internal, mark it as such.
1290 if (it->Symbol->isDefined() &&
1291 !Asm.getSymbolData(*it->Symbol).isExternal()) {
1292 uint32_t Flags = ISF_Local;
1293 if (it->Symbol->isAbsolute())
1294 Flags |= ISF_Absolute;
1300 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1303 // FIXME: Check that offsets match computed ones.
1305 // Write the symbol table entries.
1306 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1307 WriteNlist(LocalSymbolData[i], Layout);
1308 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1309 WriteNlist(ExternalSymbolData[i], Layout);
1310 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1311 WriteNlist(UndefinedSymbolData[i], Layout);
1313 // Write the string table.
1314 OS << StringTable.str();
1321 MCObjectWriter *llvm::createMachObjectWriter(raw_ostream &OS, bool is64Bit,
1323 uint32_t CPUSubtype,
1324 bool IsLittleEndian) {
1325 return new MachObjectWriter(OS, is64Bit, CPUType, CPUSubtype, IsLittleEndian);