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/Object/MachOFormat.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Target/TargetAsmBackend.h"
25 #include "../Target/X86/X86FixupKinds.h"
29 using namespace llvm::object;
31 // FIXME: this has been copied from (or to) X86AsmBackend.cpp
32 static unsigned getFixupKindLog2Size(unsigned Kind) {
34 default: llvm_unreachable("invalid fixup kind!");
35 case X86::reloc_pcrel_1byte:
36 case FK_Data_1: return 0;
37 case X86::reloc_pcrel_2byte:
38 case FK_Data_2: return 1;
39 case X86::reloc_pcrel_4byte:
40 case X86::reloc_riprel_4byte:
41 case X86::reloc_riprel_4byte_movq_load:
42 case X86::reloc_signed_4byte:
43 case FK_Data_4: return 2;
44 case FK_Data_8: return 3;
48 static bool isFixupKindPCRel(unsigned Kind) {
52 case X86::reloc_pcrel_1byte:
53 case X86::reloc_pcrel_2byte:
54 case X86::reloc_pcrel_4byte:
55 case X86::reloc_riprel_4byte:
56 case X86::reloc_riprel_4byte_movq_load:
61 static bool isFixupKindRIPRel(unsigned Kind) {
62 return Kind == X86::reloc_riprel_4byte ||
63 Kind == X86::reloc_riprel_4byte_movq_load;
66 static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
67 // Undefined symbols are always extern.
68 if (SD->Symbol->isUndefined())
71 // References to weak definitions require external relocation entries; the
72 // definition may not always be the one in the same object file.
73 if (SD->getFlags() & SF_WeakDefinition)
76 // Otherwise, we can use an internal relocation.
80 static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
82 const MCSymbolData *BaseSymbol) {
83 // The effective fixup address is
84 // addr(atom(A)) + offset(A)
85 // - addr(atom(B)) - offset(B)
86 // - addr(BaseSymbol) + <fixup offset from base symbol>
87 // and the offsets are not relocatable, so the fixup is fully resolved when
88 // addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
90 // Note that "false" is almost always conservatively correct (it means we emit
91 // a relocation which is unnecessary), except when it would force us to emit a
92 // relocation which the target cannot encode.
94 const MCSymbolData *A_Base = 0, *B_Base = 0;
95 if (const MCSymbolRefExpr *A = Target.getSymA()) {
96 // Modified symbol references cannot be resolved.
97 if (A->getKind() != MCSymbolRefExpr::VK_None)
100 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
105 if (const MCSymbolRefExpr *B = Target.getSymB()) {
106 // Modified symbol references cannot be resolved.
107 if (B->getKind() != MCSymbolRefExpr::VK_None)
110 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
115 // If there is no base, A and B have to be the same atom for this fixup to be
118 return A_Base == B_Base;
120 // Otherwise, B must be missing and A must be the base.
121 return !B_Base && BaseSymbol == A_Base;
124 static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
125 const MCValue Target,
126 const MCSection *BaseSection) {
127 // The effective fixup address is
128 // addr(atom(A)) + offset(A)
129 // - addr(atom(B)) - offset(B)
130 // - addr(<base symbol>) + <fixup offset from base symbol>
131 // and the offsets are not relocatable, so the fixup is fully resolved when
132 // addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
134 // The simple (Darwin, except on x86_64) way of dealing with this was to
135 // assume that any reference to a temporary symbol *must* be a temporary
136 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
137 // relocation to a temporary symbol (in the same section) is fully
138 // resolved. This also works in conjunction with absolutized .set, which
139 // requires the compiler to use .set to absolutize the differences between
140 // symbols which the compiler knows to be assembly time constants, so we don't
141 // need to worry about considering symbol differences fully resolved.
143 // Non-relative fixups are only resolved if constant.
145 return Target.isAbsolute();
147 // Otherwise, relative fixups are only resolved if not a difference and the
148 // target is a temporary in the same section.
149 if (Target.isAbsolute() || Target.getSymB())
152 const MCSymbol *A = &Target.getSymA()->getSymbol();
153 if (!A->isTemporary() || !A->isInSection() ||
154 &A->getSection() != BaseSection)
162 class MachObjectWriter : public MCObjectWriter {
163 // See <mach-o/loader.h>.
164 enum HeaderFileType {
169 HF_SubsectionsViaSymbols = 0x2000
172 enum LoadCommandType {
179 // See <mach-o/nlist.h>.
180 enum SymbolTypeType {
181 STT_Undefined = 0x00,
186 enum SymbolTypeFlags {
187 // If any of these bits are set, then the entry is a stab entry number (see
188 // <mach-o/stab.h>. Otherwise the other masks apply.
189 STF_StabsEntryMask = 0xe0,
193 STF_PrivateExtern = 0x10
196 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
198 enum IndirectSymbolFlags {
199 ISF_Local = 0x80000000,
200 ISF_Absolute = 0x40000000
203 /// RelocationFlags - Special flags for addresses.
204 enum RelocationFlags {
205 RF_Scattered = 0x80000000
208 enum RelocationInfoType {
212 RIT_PreboundLazyPointer = 3,
213 RIT_LocalDifference = 4,
217 /// X86_64 uses its own relocation types.
218 enum RelocationInfoTypeX86_64 {
219 RIT_X86_64_Unsigned = 0,
220 RIT_X86_64_Signed = 1,
221 RIT_X86_64_Branch = 2,
222 RIT_X86_64_GOTLoad = 3,
224 RIT_X86_64_Subtractor = 5,
225 RIT_X86_64_Signed1 = 6,
226 RIT_X86_64_Signed2 = 7,
227 RIT_X86_64_Signed4 = 8,
231 /// MachSymbolData - Helper struct for containing some precomputed information
233 struct MachSymbolData {
234 MCSymbolData *SymbolData;
235 uint64_t StringIndex;
236 uint8_t SectionIndex;
238 // Support lexicographic sorting.
239 bool operator<(const MachSymbolData &RHS) const {
240 return SymbolData->getSymbol().getName() <
241 RHS.SymbolData->getSymbol().getName();
245 /// @name Relocation Data
248 struct MachRelocationEntry {
253 llvm::DenseMap<const MCSectionData*,
254 std::vector<MachRelocationEntry> > Relocations;
255 llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
258 /// @name Symbol Table Data
261 SmallString<256> StringTable;
262 std::vector<MachSymbolData> LocalSymbolData;
263 std::vector<MachSymbolData> ExternalSymbolData;
264 std::vector<MachSymbolData> UndefinedSymbolData;
268 unsigned Is64Bit : 1;
274 MachObjectWriter(raw_ostream &_OS,
275 bool _Is64Bit, uint32_t _CPUType, uint32_t _CPUSubtype,
276 bool _IsLittleEndian)
277 : MCObjectWriter(_OS, _IsLittleEndian),
278 Is64Bit(_Is64Bit), CPUType(_CPUType), CPUSubtype(_CPUSubtype) {
281 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
282 bool SubsectionsViaSymbols) {
285 if (SubsectionsViaSymbols)
286 Flags |= HF_SubsectionsViaSymbols;
288 // struct mach_header (28 bytes) or
289 // struct mach_header_64 (32 bytes)
291 uint64_t Start = OS.tell();
294 Write32(Is64Bit ? macho::HM_Object64 : macho::HM_Object32);
300 Write32(NumLoadCommands); // Object files have a single load command, the
302 Write32(LoadCommandsSize);
305 Write32(0); // reserved
307 assert(OS.tell() - Start == Is64Bit ?
308 macho::Header64Size : macho::Header32Size);
311 /// WriteSegmentLoadCommand - Write a segment load command.
313 /// \arg NumSections - The number of sections in this segment.
314 /// \arg SectionDataSize - The total size of the sections.
315 void WriteSegmentLoadCommand(unsigned NumSections,
317 uint64_t SectionDataStartOffset,
318 uint64_t SectionDataSize) {
319 // struct segment_command (56 bytes) or
320 // struct segment_command_64 (72 bytes)
322 uint64_t Start = OS.tell();
325 unsigned SegmentLoadCommandSize = Is64Bit ? macho::SegmentLoadCommand64Size:
326 macho::SegmentLoadCommand32Size;
327 Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
328 Write32(SegmentLoadCommandSize +
329 NumSections * (Is64Bit ? macho::Section64Size :
330 macho::Section32Size));
334 Write64(0); // vmaddr
335 Write64(VMSize); // vmsize
336 Write64(SectionDataStartOffset); // file offset
337 Write64(SectionDataSize); // file size
339 Write32(0); // vmaddr
340 Write32(VMSize); // vmsize
341 Write32(SectionDataStartOffset); // file offset
342 Write32(SectionDataSize); // file size
344 Write32(0x7); // maxprot
345 Write32(0x7); // initprot
346 Write32(NumSections);
349 assert(OS.tell() - Start == SegmentLoadCommandSize);
352 void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
353 const MCSectionData &SD, uint64_t FileOffset,
354 uint64_t RelocationsStart, unsigned NumRelocations) {
355 uint64_t SectionSize = Layout.getSectionSize(&SD);
357 // The offset is unused for virtual sections.
358 if (SD.getSection().isVirtualSection()) {
359 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
363 // struct section (68 bytes) or
364 // struct section_64 (80 bytes)
366 uint64_t Start = OS.tell();
369 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
370 WriteBytes(Section.getSectionName(), 16);
371 WriteBytes(Section.getSegmentName(), 16);
373 Write64(Layout.getSectionAddress(&SD)); // address
374 Write64(SectionSize); // size
376 Write32(Layout.getSectionAddress(&SD)); // address
377 Write32(SectionSize); // size
381 unsigned Flags = Section.getTypeAndAttributes();
382 if (SD.hasInstructions())
383 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
385 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
386 Write32(Log2_32(SD.getAlignment()));
387 Write32(NumRelocations ? RelocationsStart : 0);
388 Write32(NumRelocations);
390 Write32(IndirectSymBase.lookup(&SD)); // reserved1
391 Write32(Section.getStubSize()); // reserved2
393 Write32(0); // reserved3
395 assert(OS.tell() - Start == Is64Bit ? macho::Section64Size :
396 macho::Section32Size);
399 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
400 uint32_t StringTableOffset,
401 uint32_t StringTableSize) {
402 // struct symtab_command (24 bytes)
404 uint64_t Start = OS.tell();
408 Write32(macho::SymtabLoadCommandSize);
409 Write32(SymbolOffset);
411 Write32(StringTableOffset);
412 Write32(StringTableSize);
414 assert(OS.tell() - Start == macho::SymtabLoadCommandSize);
417 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
418 uint32_t NumLocalSymbols,
419 uint32_t FirstExternalSymbol,
420 uint32_t NumExternalSymbols,
421 uint32_t FirstUndefinedSymbol,
422 uint32_t NumUndefinedSymbols,
423 uint32_t IndirectSymbolOffset,
424 uint32_t NumIndirectSymbols) {
425 // struct dysymtab_command (80 bytes)
427 uint64_t Start = OS.tell();
430 Write32(LCT_Dysymtab);
431 Write32(macho::DysymtabLoadCommandSize);
432 Write32(FirstLocalSymbol);
433 Write32(NumLocalSymbols);
434 Write32(FirstExternalSymbol);
435 Write32(NumExternalSymbols);
436 Write32(FirstUndefinedSymbol);
437 Write32(NumUndefinedSymbols);
438 Write32(0); // tocoff
440 Write32(0); // modtaboff
441 Write32(0); // nmodtab
442 Write32(0); // extrefsymoff
443 Write32(0); // nextrefsyms
444 Write32(IndirectSymbolOffset);
445 Write32(NumIndirectSymbols);
446 Write32(0); // extreloff
447 Write32(0); // nextrel
448 Write32(0); // locreloff
449 Write32(0); // nlocrel
451 assert(OS.tell() - Start == macho::DysymtabLoadCommandSize);
454 void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
455 MCSymbolData &Data = *MSD.SymbolData;
456 const MCSymbol &Symbol = Data.getSymbol();
458 uint16_t Flags = Data.getFlags();
459 uint32_t Address = 0;
461 // Set the N_TYPE bits. See <mach-o/nlist.h>.
463 // FIXME: Are the prebound or indirect fields possible here?
464 if (Symbol.isUndefined())
465 Type = STT_Undefined;
466 else if (Symbol.isAbsolute())
471 // FIXME: Set STAB bits.
473 if (Data.isPrivateExtern())
474 Type |= STF_PrivateExtern;
477 if (Data.isExternal() || Symbol.isUndefined())
478 Type |= STF_External;
480 // Compute the symbol address.
481 if (Symbol.isDefined()) {
482 if (Symbol.isAbsolute()) {
483 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
485 Address = Layout.getSymbolAddress(&Data);
487 } else if (Data.isCommon()) {
488 // Common symbols are encoded with the size in the address
489 // field, and their alignment in the flags.
490 Address = Data.getCommonSize();
492 // Common alignment is packed into the 'desc' bits.
493 if (unsigned Align = Data.getCommonAlignment()) {
494 unsigned Log2Size = Log2_32(Align);
495 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
497 report_fatal_error("invalid 'common' alignment '" +
499 // FIXME: Keep this mask with the SymbolFlags enumeration.
500 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
504 // struct nlist (12 bytes)
506 Write32(MSD.StringIndex);
508 Write8(MSD.SectionIndex);
510 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
519 // FIXME: We really need to improve the relocation validation. Basically, we
520 // want to implement a separate computation which evaluates the relocation
521 // entry as the linker would, and verifies that the resultant fixup value is
522 // exactly what the encoder wanted. This will catch several classes of
525 // - Relocation entry bugs, the two algorithms are unlikely to have the same
528 // - Relaxation issues, where we forget to relax something.
530 // - Input errors, where something cannot be correctly encoded. 'as' allows
531 // these through in many cases.
533 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
534 const MCFragment *Fragment,
535 const MCFixup &Fixup, MCValue Target,
536 uint64_t &FixedValue) {
537 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
538 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
539 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
542 uint32_t FixupOffset =
543 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
544 uint32_t FixupAddress =
545 Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
548 unsigned IsExtern = 0;
551 Value = Target.getConstant();
554 // Compensate for the relocation offset, Darwin x86_64 relocations only
555 // have the addend and appear to have attempted to define it to be the
556 // actual expression addend without the PCrel bias. However, instructions
557 // with data following the relocation are not accomodated for (see comment
558 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
559 Value += 1LL << Log2Size;
562 if (Target.isAbsolute()) { // constant
563 // SymbolNum of 0 indicates the absolute section.
564 Type = RIT_X86_64_Unsigned;
567 // FIXME: I believe this is broken, I don't think the linker can
568 // understand it. I think it would require a local relocation, but I'm not
569 // sure if that would work either. The official way to get an absolute
570 // PCrel relocation is to use an absolute symbol (which we don't support
574 Type = RIT_X86_64_Branch;
576 } else if (Target.getSymB()) { // A - B + constant
577 const MCSymbol *A = &Target.getSymA()->getSymbol();
578 MCSymbolData &A_SD = Asm.getSymbolData(*A);
579 const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
581 const MCSymbol *B = &Target.getSymB()->getSymbol();
582 MCSymbolData &B_SD = Asm.getSymbolData(*B);
583 const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
585 // Neither symbol can be modified.
586 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
587 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
588 report_fatal_error("unsupported relocation of modified symbol");
590 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
591 // implement most of these correctly.
593 report_fatal_error("unsupported pc-relative relocation of difference");
595 // The support for the situation where one or both of the symbols would
596 // require a local relocation is handled just like if the symbols were
597 // external. This is certainly used in the case of debug sections where
598 // the section has only temporary symbols and thus the symbols don't have
599 // base symbols. This is encoded using the section ordinal and
600 // non-extern relocation entries.
602 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
603 // a single SIGNED relocation); reject it for now. Except the case where
604 // both symbols don't have a base, equal but both NULL.
605 if (A_Base == B_Base && A_Base)
606 report_fatal_error("unsupported relocation with identical base");
608 Value += Layout.getSymbolAddress(&A_SD) -
609 (A_Base == NULL ? 0 : Layout.getSymbolAddress(A_Base));
610 Value -= Layout.getSymbolAddress(&B_SD) -
611 (B_Base == NULL ? 0 : Layout.getSymbolAddress(B_Base));
614 Index = A_Base->getIndex();
618 Index = A_SD.getFragment()->getParent()->getOrdinal() + 1;
621 Type = RIT_X86_64_Unsigned;
623 MachRelocationEntry MRE;
624 MRE.Word0 = FixupOffset;
625 MRE.Word1 = ((Index << 0) |
630 Relocations[Fragment->getParent()].push_back(MRE);
633 Index = B_Base->getIndex();
637 Index = B_SD.getFragment()->getParent()->getOrdinal() + 1;
640 Type = RIT_X86_64_Subtractor;
642 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
643 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
644 const MCSymbolData *Base = Asm.getAtom(&SD);
646 // Relocations inside debug sections always use local relocations when
647 // possible. This seems to be done because the debugger doesn't fully
648 // understand x86_64 relocation entries, and expects to find values that
649 // have already been fixed up.
650 if (Symbol->isInSection()) {
651 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
652 Fragment->getParent()->getSection());
653 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
657 // x86_64 almost always uses external relocations, except when there is no
658 // symbol to use as a base address (a local symbol with no preceeding
659 // non-local symbol).
661 Index = Base->getIndex();
664 // Add the local offset, if needed.
666 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
667 } else if (Symbol->isInSection()) {
668 // The index is the section ordinal (1-based).
669 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
671 Value += Layout.getSymbolAddress(&SD);
674 Value -= FixupAddress + (1 << Log2Size);
676 report_fatal_error("unsupported relocation of undefined symbol '" +
677 Symbol->getName() + "'");
680 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
683 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
684 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
685 // rewrite the movq to an leaq at link time if the symbol ends up in
686 // the same linkage unit.
687 if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
688 Type = RIT_X86_64_GOTLoad;
690 Type = RIT_X86_64_GOT;
691 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
692 Type = RIT_X86_64_TLV;
693 } else if (Modifier != MCSymbolRefExpr::VK_None) {
694 report_fatal_error("unsupported symbol modifier in relocation");
696 Type = RIT_X86_64_Signed;
698 // The Darwin x86_64 relocation format has a problem where it cannot
699 // encode an address (L<foo> + <constant>) which is outside the atom
700 // containing L<foo>. Generally, this shouldn't occur but it does
701 // happen when we have a RIPrel instruction with data following the
702 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
703 // adjustment Darwin x86_64 uses, the offset is still negative and
704 // the linker has no way to recognize this.
706 // To work around this, Darwin uses several special relocation types
707 // to indicate the offsets. However, the specification or
708 // implementation of these seems to also be incomplete; they should
709 // adjust the addend as well based on the actual encoded instruction
710 // (the additional bias), but instead appear to just look at the
712 switch (-(Target.getConstant() + (1LL << Log2Size))) {
713 case 1: Type = RIT_X86_64_Signed1; break;
714 case 2: Type = RIT_X86_64_Signed2; break;
715 case 4: Type = RIT_X86_64_Signed4; break;
719 if (Modifier != MCSymbolRefExpr::VK_None)
720 report_fatal_error("unsupported symbol modifier in branch "
723 Type = RIT_X86_64_Branch;
726 if (Modifier == MCSymbolRefExpr::VK_GOT) {
727 Type = RIT_X86_64_GOT;
728 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
729 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
730 // which case all we do is set the PCrel bit in the relocation entry;
731 // this is used with exception handling, for example. The source is
732 // required to include any necessary offset directly.
733 Type = RIT_X86_64_GOT;
735 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
736 report_fatal_error("TLVP symbol modifier should have been rip-rel");
737 } else if (Modifier != MCSymbolRefExpr::VK_None)
738 report_fatal_error("unsupported symbol modifier in relocation");
740 Type = RIT_X86_64_Unsigned;
744 // x86_64 always writes custom values into the fixups.
747 // struct relocation_info (8 bytes)
748 MachRelocationEntry MRE;
749 MRE.Word0 = FixupOffset;
750 MRE.Word1 = ((Index << 0) |
755 Relocations[Fragment->getParent()].push_back(MRE);
758 void RecordScatteredRelocation(const MCAssembler &Asm,
759 const MCAsmLayout &Layout,
760 const MCFragment *Fragment,
761 const MCFixup &Fixup, MCValue Target,
762 uint64_t &FixedValue) {
763 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
764 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
765 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
766 unsigned Type = RIT_Vanilla;
769 const MCSymbol *A = &Target.getSymA()->getSymbol();
770 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
772 if (!A_SD->getFragment())
773 report_fatal_error("symbol '" + A->getName() +
774 "' can not be undefined in a subtraction expression");
776 uint32_t Value = Layout.getSymbolAddress(A_SD);
779 if (const MCSymbolRefExpr *B = Target.getSymB()) {
780 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
782 if (!B_SD->getFragment())
783 report_fatal_error("symbol '" + B->getSymbol().getName() +
784 "' can not be undefined in a subtraction expression");
786 // Select the appropriate difference relocation type.
788 // Note that there is no longer any semantic difference between these two
789 // relocation types from the linkers point of view, this is done solely
790 // for pedantic compatibility with 'as'.
791 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
792 Value2 = Layout.getSymbolAddress(B_SD);
795 // Relocations are written out in reverse order, so the PAIR comes first.
796 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
797 MachRelocationEntry MRE;
798 MRE.Word0 = ((0 << 0) |
804 Relocations[Fragment->getParent()].push_back(MRE);
807 MachRelocationEntry MRE;
808 MRE.Word0 = ((FixupOffset << 0) |
814 Relocations[Fragment->getParent()].push_back(MRE);
817 void RecordTLVPRelocation(const MCAssembler &Asm,
818 const MCAsmLayout &Layout,
819 const MCFragment *Fragment,
820 const MCFixup &Fixup, MCValue Target,
821 uint64_t &FixedValue) {
822 assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
824 "Should only be called with a 32-bit TLVP relocation!");
826 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
827 uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
828 unsigned IsPCRel = 0;
830 // Get the symbol data.
831 MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
832 unsigned Index = SD_A->getIndex();
834 // We're only going to have a second symbol in pic mode and it'll be a
835 // subtraction from the picbase. For 32-bit pic the addend is the difference
836 // between the picbase and the next address. For 32-bit static the addend
838 if (Target.getSymB()) {
839 // If this is a subtraction then we're pcrel.
840 uint32_t FixupAddress =
841 Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
842 MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
844 FixedValue = (FixupAddress - Layout.getSymbolAddress(SD_B) +
845 Target.getConstant());
846 FixedValue += 1ULL << Log2Size;
851 // struct relocation_info (8 bytes)
852 MachRelocationEntry MRE;
854 MRE.Word1 = ((Index << 0) |
857 (1 << 27) | // Extern
858 (RIT_TLV << 28)); // Type
859 Relocations[Fragment->getParent()].push_back(MRE);
862 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
863 const MCFragment *Fragment, const MCFixup &Fixup,
864 MCValue Target, uint64_t &FixedValue) {
866 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
870 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
871 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
873 // If this is a 32-bit TLVP reloc it's handled a bit differently.
874 if (Target.getSymA() &&
875 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
876 RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
880 // If this is a difference or a defined symbol plus an offset, then we need
881 // a scattered relocation entry.
882 // Differences always require scattered relocations.
883 if (Target.getSymB())
884 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
887 // Get the symbol data, if any.
888 MCSymbolData *SD = 0;
889 if (Target.getSymA())
890 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
892 // If this is an internal relocation with an offset, it also needs a
893 // scattered relocation entry.
894 uint32_t Offset = Target.getConstant();
896 Offset += 1 << Log2Size;
897 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
898 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
902 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
904 unsigned IsExtern = 0;
907 if (Target.isAbsolute()) { // constant
908 // SymbolNum of 0 indicates the absolute section.
910 // FIXME: Currently, these are never generated (see code below). I cannot
911 // find a case where they are actually emitted.
914 // Check whether we need an external or internal relocation.
915 if (doesSymbolRequireExternRelocation(SD)) {
917 Index = SD->getIndex();
918 // For external relocations, make sure to offset the fixup value to
919 // compensate for the addend of the symbol address, if it was
920 // undefined. This occurs with weak definitions, for example.
921 if (!SD->Symbol->isUndefined())
922 FixedValue -= Layout.getSymbolAddress(SD);
924 // The index is the section ordinal (1-based).
925 Index = SD->getFragment()->getParent()->getOrdinal() + 1;
931 // struct relocation_info (8 bytes)
932 MachRelocationEntry MRE;
933 MRE.Word0 = FixupOffset;
934 MRE.Word1 = ((Index << 0) |
939 Relocations[Fragment->getParent()].push_back(MRE);
942 void BindIndirectSymbols(MCAssembler &Asm) {
943 // This is the point where 'as' creates actual symbols for indirect symbols
944 // (in the following two passes). It would be easier for us to do this
945 // sooner when we see the attribute, but that makes getting the order in the
946 // symbol table much more complicated than it is worth.
948 // FIXME: Revisit this when the dust settles.
950 // Bind non lazy symbol pointers first.
951 unsigned IndirectIndex = 0;
952 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
953 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
954 const MCSectionMachO &Section =
955 cast<MCSectionMachO>(it->SectionData->getSection());
957 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
960 // Initialize the section indirect symbol base, if necessary.
961 if (!IndirectSymBase.count(it->SectionData))
962 IndirectSymBase[it->SectionData] = IndirectIndex;
964 Asm.getOrCreateSymbolData(*it->Symbol);
967 // Then lazy symbol pointers and symbol stubs.
969 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
970 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
971 const MCSectionMachO &Section =
972 cast<MCSectionMachO>(it->SectionData->getSection());
974 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
975 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
978 // Initialize the section indirect symbol base, if necessary.
979 if (!IndirectSymBase.count(it->SectionData))
980 IndirectSymBase[it->SectionData] = IndirectIndex;
982 // Set the symbol type to undefined lazy, but only on construction.
984 // FIXME: Do not hardcode.
986 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
988 Entry.setFlags(Entry.getFlags() | 0x0001);
992 /// ComputeSymbolTable - Compute the symbol table data
994 /// \param StringTable [out] - The string table data.
995 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
997 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
998 std::vector<MachSymbolData> &LocalSymbolData,
999 std::vector<MachSymbolData> &ExternalSymbolData,
1000 std::vector<MachSymbolData> &UndefinedSymbolData) {
1001 // Build section lookup table.
1002 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
1004 for (MCAssembler::iterator it = Asm.begin(),
1005 ie = Asm.end(); it != ie; ++it, ++Index)
1006 SectionIndexMap[&it->getSection()] = Index;
1007 assert(Index <= 256 && "Too many sections!");
1009 // Index 0 is always the empty string.
1010 StringMap<uint64_t> StringIndexMap;
1011 StringTable += '\x00';
1013 // Build the symbol arrays and the string table, but only for non-local
1016 // The particular order that we collect the symbols and create the string
1017 // table, then sort the symbols is chosen to match 'as'. Even though it
1018 // doesn't matter for correctness, this is important for letting us diff .o
1020 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1021 ie = Asm.symbol_end(); it != ie; ++it) {
1022 const MCSymbol &Symbol = it->getSymbol();
1024 // Ignore non-linker visible symbols.
1025 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1028 if (!it->isExternal() && !Symbol.isUndefined())
1031 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1033 Entry = StringTable.size();
1034 StringTable += Symbol.getName();
1035 StringTable += '\x00';
1039 MSD.SymbolData = it;
1040 MSD.StringIndex = Entry;
1042 if (Symbol.isUndefined()) {
1043 MSD.SectionIndex = 0;
1044 UndefinedSymbolData.push_back(MSD);
1045 } else if (Symbol.isAbsolute()) {
1046 MSD.SectionIndex = 0;
1047 ExternalSymbolData.push_back(MSD);
1049 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1050 assert(MSD.SectionIndex && "Invalid section index!");
1051 ExternalSymbolData.push_back(MSD);
1055 // Now add the data for local symbols.
1056 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1057 ie = Asm.symbol_end(); it != ie; ++it) {
1058 const MCSymbol &Symbol = it->getSymbol();
1060 // Ignore non-linker visible symbols.
1061 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1064 if (it->isExternal() || Symbol.isUndefined())
1067 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1069 Entry = StringTable.size();
1070 StringTable += Symbol.getName();
1071 StringTable += '\x00';
1075 MSD.SymbolData = it;
1076 MSD.StringIndex = Entry;
1078 if (Symbol.isAbsolute()) {
1079 MSD.SectionIndex = 0;
1080 LocalSymbolData.push_back(MSD);
1082 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1083 assert(MSD.SectionIndex && "Invalid section index!");
1084 LocalSymbolData.push_back(MSD);
1088 // External and undefined symbols are required to be in lexicographic order.
1089 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1090 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1092 // Set the symbol indices.
1094 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1095 LocalSymbolData[i].SymbolData->setIndex(Index++);
1096 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1097 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1098 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1099 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1101 // The string table is padded to a multiple of 4.
1102 while (StringTable.size() % 4)
1103 StringTable += '\x00';
1106 void ExecutePostLayoutBinding(MCAssembler &Asm) {
1107 // Create symbol data for any indirect symbols.
1108 BindIndirectSymbols(Asm);
1110 // Compute symbol table information and bind symbol indices.
1111 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1112 UndefinedSymbolData);
1116 bool IsFixupFullyResolved(const MCAssembler &Asm,
1117 const MCValue Target,
1119 const MCFragment *DF) const {
1120 // If we are using scattered symbols, determine whether this value is
1121 // actually resolved; scattering may cause atoms to move.
1122 if (Asm.getBackend().hasScatteredSymbols()) {
1123 if (Asm.getBackend().hasReliableSymbolDifference()) {
1124 // If this is a PCrel relocation, find the base atom (identified by its
1125 // symbol) that the fixup value is relative to.
1126 const MCSymbolData *BaseSymbol = 0;
1128 BaseSymbol = DF->getAtom();
1133 return isScatteredFixupFullyResolved(Asm, Target, BaseSymbol);
1135 const MCSection *BaseSection = 0;
1137 BaseSection = &DF->getParent()->getSection();
1139 return isScatteredFixupFullyResolvedSimple(Asm, Target, BaseSection);
1145 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
1146 unsigned NumSections = Asm.size();
1148 // The section data starts after the header, the segment load command (and
1149 // section headers) and the symbol table.
1150 unsigned NumLoadCommands = 1;
1151 uint64_t LoadCommandsSize = Is64Bit ?
1152 macho::SegmentLoadCommand64Size + NumSections * macho::Section64Size :
1153 macho::SegmentLoadCommand32Size + NumSections * macho::Section32Size;
1155 // Add the symbol table load command sizes, if used.
1156 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1157 UndefinedSymbolData.size();
1159 NumLoadCommands += 2;
1160 LoadCommandsSize += (macho::SymtabLoadCommandSize +
1161 macho::DysymtabLoadCommandSize);
1164 // Compute the total size of the section data, as well as its file size and
1166 uint64_t SectionDataStart = (Is64Bit ? macho::Header64Size :
1167 macho::Header32Size) + LoadCommandsSize;
1168 uint64_t SectionDataSize = 0;
1169 uint64_t SectionDataFileSize = 0;
1170 uint64_t VMSize = 0;
1171 for (MCAssembler::const_iterator it = Asm.begin(),
1172 ie = Asm.end(); it != ie; ++it) {
1173 const MCSectionData &SD = *it;
1174 uint64_t Address = Layout.getSectionAddress(&SD);
1175 uint64_t Size = Layout.getSectionSize(&SD);
1176 uint64_t FileSize = Layout.getSectionFileSize(&SD);
1178 VMSize = std::max(VMSize, Address + Size);
1180 if (SD.getSection().isVirtualSection())
1183 SectionDataSize = std::max(SectionDataSize, Address + Size);
1184 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
1187 // The section data is padded to 4 bytes.
1189 // FIXME: Is this machine dependent?
1190 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1191 SectionDataFileSize += SectionDataPadding;
1193 // Write the prolog, starting with the header and load command...
1194 WriteHeader(NumLoadCommands, LoadCommandsSize,
1195 Asm.getSubsectionsViaSymbols());
1196 WriteSegmentLoadCommand(NumSections, VMSize,
1197 SectionDataStart, SectionDataSize);
1199 // ... and then the section headers.
1200 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1201 for (MCAssembler::const_iterator it = Asm.begin(),
1202 ie = Asm.end(); it != ie; ++it) {
1203 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1204 unsigned NumRelocs = Relocs.size();
1205 uint64_t SectionStart = SectionDataStart + Layout.getSectionAddress(it);
1206 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
1207 RelocTableEnd += NumRelocs * macho::RelocationInfoSize;
1210 // Write the symbol table load command, if used.
1212 unsigned FirstLocalSymbol = 0;
1213 unsigned NumLocalSymbols = LocalSymbolData.size();
1214 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1215 unsigned NumExternalSymbols = ExternalSymbolData.size();
1216 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1217 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1218 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1219 unsigned NumSymTabSymbols =
1220 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1221 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1222 uint64_t IndirectSymbolOffset = 0;
1224 // If used, the indirect symbols are written after the section data.
1225 if (NumIndirectSymbols)
1226 IndirectSymbolOffset = RelocTableEnd;
1228 // The symbol table is written after the indirect symbol data.
1229 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1231 // The string table is written after symbol table.
1232 uint64_t StringTableOffset =
1233 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? macho::Nlist64Size :
1234 macho::Nlist32Size);
1235 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1236 StringTableOffset, StringTable.size());
1238 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1239 FirstExternalSymbol, NumExternalSymbols,
1240 FirstUndefinedSymbol, NumUndefinedSymbols,
1241 IndirectSymbolOffset, NumIndirectSymbols);
1244 // Write the actual section data.
1245 for (MCAssembler::const_iterator it = Asm.begin(),
1246 ie = Asm.end(); it != ie; ++it)
1247 Asm.WriteSectionData(it, Layout, this);
1249 // Write the extra padding.
1250 WriteZeros(SectionDataPadding);
1252 // Write the relocation entries.
1253 for (MCAssembler::const_iterator it = Asm.begin(),
1254 ie = Asm.end(); it != ie; ++it) {
1255 // Write the section relocation entries, in reverse order to match 'as'
1256 // (approximately, the exact algorithm is more complicated than this).
1257 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1258 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1259 Write32(Relocs[e - i - 1].Word0);
1260 Write32(Relocs[e - i - 1].Word1);
1264 // Write the symbol table data, if used.
1266 // Write the indirect symbol entries.
1267 for (MCAssembler::const_indirect_symbol_iterator
1268 it = Asm.indirect_symbol_begin(),
1269 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1270 // Indirect symbols in the non lazy symbol pointer section have some
1271 // special handling.
1272 const MCSectionMachO &Section =
1273 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1274 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1275 // If this symbol is defined and internal, mark it as such.
1276 if (it->Symbol->isDefined() &&
1277 !Asm.getSymbolData(*it->Symbol).isExternal()) {
1278 uint32_t Flags = ISF_Local;
1279 if (it->Symbol->isAbsolute())
1280 Flags |= ISF_Absolute;
1286 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1289 // FIXME: Check that offsets match computed ones.
1291 // Write the symbol table entries.
1292 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1293 WriteNlist(LocalSymbolData[i], Layout);
1294 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1295 WriteNlist(ExternalSymbolData[i], Layout);
1296 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1297 WriteNlist(UndefinedSymbolData[i], Layout);
1299 // Write the string table.
1300 OS << StringTable.str();
1307 MCObjectWriter *llvm::createMachObjectWriter(raw_ostream &OS, bool is64Bit,
1309 uint32_t CPUSubtype,
1310 bool IsLittleEndian) {
1311 return new MachObjectWriter(OS, is64Bit, CPUType, CPUSubtype, IsLittleEndian);