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/MCMachObjectWriter.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/Object/MachOFormat.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Target/TargetAsmBackend.h"
26 #include "../Target/X86/X86FixupKinds.h"
30 using namespace llvm::object;
32 // FIXME: this has been copied from (or to) X86AsmBackend.cpp
33 static unsigned getFixupKindLog2Size(unsigned Kind) {
35 // FIXME: Until ARM has it's own relocation stuff spun off, it comes
36 // through here and we don't want it to puke all over. Any reasonable
37 // values will only come when ARM relocation support gets added, at which
38 // point this will be X86 only again and the llvm_unreachable can be
40 default: return 0;// llvm_unreachable("invalid fixup kind!");
42 case FK_Data_1: return 0;
44 case FK_Data_2: return 1;
46 case X86::reloc_riprel_4byte:
47 case X86::reloc_riprel_4byte_movq_load:
48 case X86::reloc_signed_4byte:
49 case FK_Data_4: return 2;
50 case FK_Data_8: return 3;
54 static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
55 // Undefined symbols are always extern.
56 if (SD->Symbol->isUndefined())
59 // References to weak definitions require external relocation entries; the
60 // definition may not always be the one in the same object file.
61 if (SD->getFlags() & SF_WeakDefinition)
64 // Otherwise, we can use an internal relocation.
68 static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
70 const MCSymbolData *BaseSymbol) {
71 // The effective fixup address is
72 // addr(atom(A)) + offset(A)
73 // - addr(atom(B)) - offset(B)
74 // - addr(BaseSymbol) + <fixup offset from base symbol>
75 // and the offsets are not relocatable, so the fixup is fully resolved when
76 // addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
78 // Note that "false" is almost always conservatively correct (it means we emit
79 // a relocation which is unnecessary), except when it would force us to emit a
80 // relocation which the target cannot encode.
82 const MCSymbolData *A_Base = 0, *B_Base = 0;
83 if (const MCSymbolRefExpr *A = Target.getSymA()) {
84 // Modified symbol references cannot be resolved.
85 if (A->getKind() != MCSymbolRefExpr::VK_None)
88 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
93 if (const MCSymbolRefExpr *B = Target.getSymB()) {
94 // Modified symbol references cannot be resolved.
95 if (B->getKind() != MCSymbolRefExpr::VK_None)
98 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
103 // If there is no base, A and B have to be the same atom for this fixup to be
106 return A_Base == B_Base;
108 // Otherwise, B must be missing and A must be the base.
109 return !B_Base && BaseSymbol == A_Base;
112 static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
113 const MCValue Target,
114 const MCSection *BaseSection) {
115 // The effective fixup address is
116 // addr(atom(A)) + offset(A)
117 // - addr(atom(B)) - offset(B)
118 // - addr(<base symbol>) + <fixup offset from base symbol>
119 // and the offsets are not relocatable, so the fixup is fully resolved when
120 // addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
122 // The simple (Darwin, except on x86_64) way of dealing with this was to
123 // assume that any reference to a temporary symbol *must* be a temporary
124 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
125 // relocation to a temporary symbol (in the same section) is fully
126 // resolved. This also works in conjunction with absolutized .set, which
127 // requires the compiler to use .set to absolutize the differences between
128 // symbols which the compiler knows to be assembly time constants, so we don't
129 // need to worry about considering symbol differences fully resolved.
131 // Non-relative fixups are only resolved if constant.
133 return Target.isAbsolute();
135 // Otherwise, relative fixups are only resolved if not a difference and the
136 // target is a temporary in the same section.
137 if (Target.isAbsolute() || Target.getSymB())
140 const MCSymbol *A = &Target.getSymA()->getSymbol();
141 if (!A->isTemporary() || !A->isInSection() ||
142 &A->getSection() != BaseSection)
150 class MachObjectWriter : public MCObjectWriter {
151 /// MachSymbolData - Helper struct for containing some precomputed information
153 struct MachSymbolData {
154 MCSymbolData *SymbolData;
155 uint64_t StringIndex;
156 uint8_t SectionIndex;
158 // Support lexicographic sorting.
159 bool operator<(const MachSymbolData &RHS) const {
160 return SymbolData->getSymbol().getName() <
161 RHS.SymbolData->getSymbol().getName();
165 /// @name Utility Methods
168 bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
169 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
172 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
177 /// @name Relocation Data
180 llvm::DenseMap<const MCSectionData*,
181 std::vector<macho::RelocationEntry> > Relocations;
182 llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
185 /// @name Symbol Table Data
188 SmallString<256> StringTable;
189 std::vector<MachSymbolData> LocalSymbolData;
190 std::vector<MachSymbolData> ExternalSymbolData;
191 std::vector<MachSymbolData> UndefinedSymbolData;
195 SectionAddrMap SectionAddress;
196 uint64_t getSectionAddress(const MCSectionData* SD) const {
197 return SectionAddress.lookup(SD);
199 uint64_t getSymbolAddress(const MCSymbolData* SD,
200 const MCAsmLayout &Layout) const {
201 return getSectionAddress(SD->getFragment()->getParent()) +
202 Layout.getSymbolOffset(SD);
204 uint64_t getFragmentAddress(const MCFragment *Fragment,
205 const MCAsmLayout &Layout) const {
206 return getSectionAddress(Fragment->getParent()) +
207 Layout.getFragmentOffset(Fragment);
210 uint64_t getPaddingSize(const MCSectionData *SD,
211 const MCAsmLayout &Layout) const {
212 uint64_t EndAddr = getSectionAddress(SD) + Layout.getSectionAddressSize(SD);
213 unsigned Next = SD->getLayoutOrder() + 1;
214 if (Next >= Layout.getSectionOrder().size())
217 const MCSectionData &NextSD = *Layout.getSectionOrder()[Next];
218 if (NextSD.getSection().isVirtualSection())
220 return OffsetToAlignment(EndAddr, NextSD.getAlignment());
223 unsigned Is64Bit : 1;
229 MachObjectWriter(raw_ostream &_OS,
230 bool _Is64Bit, uint32_t _CPUType, uint32_t _CPUSubtype,
231 bool _IsLittleEndian)
232 : MCObjectWriter(_OS, _IsLittleEndian),
233 Is64Bit(_Is64Bit), CPUType(_CPUType), CPUSubtype(_CPUSubtype) {
236 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
237 bool SubsectionsViaSymbols) {
240 if (SubsectionsViaSymbols)
241 Flags |= macho::HF_SubsectionsViaSymbols;
243 // struct mach_header (28 bytes) or
244 // struct mach_header_64 (32 bytes)
246 uint64_t Start = OS.tell();
249 Write32(Is64Bit ? macho::HM_Object64 : macho::HM_Object32);
254 Write32(macho::HFT_Object);
255 Write32(NumLoadCommands);
256 Write32(LoadCommandsSize);
259 Write32(0); // reserved
261 assert(OS.tell() - Start == Is64Bit ?
262 macho::Header64Size : macho::Header32Size);
265 /// WriteSegmentLoadCommand - Write a segment load command.
267 /// \arg NumSections - The number of sections in this segment.
268 /// \arg SectionDataSize - The total size of the sections.
269 void WriteSegmentLoadCommand(unsigned NumSections,
271 uint64_t SectionDataStartOffset,
272 uint64_t SectionDataSize) {
273 // struct segment_command (56 bytes) or
274 // struct segment_command_64 (72 bytes)
276 uint64_t Start = OS.tell();
279 unsigned SegmentLoadCommandSize = Is64Bit ? macho::SegmentLoadCommand64Size:
280 macho::SegmentLoadCommand32Size;
281 Write32(Is64Bit ? macho::LCT_Segment64 : macho::LCT_Segment);
282 Write32(SegmentLoadCommandSize +
283 NumSections * (Is64Bit ? macho::Section64Size :
284 macho::Section32Size));
288 Write64(0); // vmaddr
289 Write64(VMSize); // vmsize
290 Write64(SectionDataStartOffset); // file offset
291 Write64(SectionDataSize); // file size
293 Write32(0); // vmaddr
294 Write32(VMSize); // vmsize
295 Write32(SectionDataStartOffset); // file offset
296 Write32(SectionDataSize); // file size
298 Write32(0x7); // maxprot
299 Write32(0x7); // initprot
300 Write32(NumSections);
303 assert(OS.tell() - Start == SegmentLoadCommandSize);
306 void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
307 const MCSectionData &SD, uint64_t FileOffset,
308 uint64_t RelocationsStart, unsigned NumRelocations) {
309 uint64_t SectionSize = Layout.getSectionAddressSize(&SD);
311 // The offset is unused for virtual sections.
312 if (SD.getSection().isVirtualSection()) {
313 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
317 // struct section (68 bytes) or
318 // struct section_64 (80 bytes)
320 uint64_t Start = OS.tell();
323 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
324 WriteBytes(Section.getSectionName(), 16);
325 WriteBytes(Section.getSegmentName(), 16);
327 Write64(getSectionAddress(&SD)); // address
328 Write64(SectionSize); // size
330 Write32(getSectionAddress(&SD)); // address
331 Write32(SectionSize); // size
335 unsigned Flags = Section.getTypeAndAttributes();
336 if (SD.hasInstructions())
337 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
339 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
340 Write32(Log2_32(SD.getAlignment()));
341 Write32(NumRelocations ? RelocationsStart : 0);
342 Write32(NumRelocations);
344 Write32(IndirectSymBase.lookup(&SD)); // reserved1
345 Write32(Section.getStubSize()); // reserved2
347 Write32(0); // reserved3
349 assert(OS.tell() - Start == Is64Bit ? macho::Section64Size :
350 macho::Section32Size);
353 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
354 uint32_t StringTableOffset,
355 uint32_t StringTableSize) {
356 // struct symtab_command (24 bytes)
358 uint64_t Start = OS.tell();
361 Write32(macho::LCT_Symtab);
362 Write32(macho::SymtabLoadCommandSize);
363 Write32(SymbolOffset);
365 Write32(StringTableOffset);
366 Write32(StringTableSize);
368 assert(OS.tell() - Start == macho::SymtabLoadCommandSize);
371 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
372 uint32_t NumLocalSymbols,
373 uint32_t FirstExternalSymbol,
374 uint32_t NumExternalSymbols,
375 uint32_t FirstUndefinedSymbol,
376 uint32_t NumUndefinedSymbols,
377 uint32_t IndirectSymbolOffset,
378 uint32_t NumIndirectSymbols) {
379 // struct dysymtab_command (80 bytes)
381 uint64_t Start = OS.tell();
384 Write32(macho::LCT_Dysymtab);
385 Write32(macho::DysymtabLoadCommandSize);
386 Write32(FirstLocalSymbol);
387 Write32(NumLocalSymbols);
388 Write32(FirstExternalSymbol);
389 Write32(NumExternalSymbols);
390 Write32(FirstUndefinedSymbol);
391 Write32(NumUndefinedSymbols);
392 Write32(0); // tocoff
394 Write32(0); // modtaboff
395 Write32(0); // nmodtab
396 Write32(0); // extrefsymoff
397 Write32(0); // nextrefsyms
398 Write32(IndirectSymbolOffset);
399 Write32(NumIndirectSymbols);
400 Write32(0); // extreloff
401 Write32(0); // nextrel
402 Write32(0); // locreloff
403 Write32(0); // nlocrel
405 assert(OS.tell() - Start == macho::DysymtabLoadCommandSize);
408 void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
409 MCSymbolData &Data = *MSD.SymbolData;
410 const MCSymbol &Symbol = Data.getSymbol();
412 uint16_t Flags = Data.getFlags();
413 uint32_t Address = 0;
415 // Set the N_TYPE bits. See <mach-o/nlist.h>.
417 // FIXME: Are the prebound or indirect fields possible here?
418 if (Symbol.isUndefined())
419 Type = macho::STT_Undefined;
420 else if (Symbol.isAbsolute())
421 Type = macho::STT_Absolute;
423 Type = macho::STT_Section;
425 // FIXME: Set STAB bits.
427 if (Data.isPrivateExtern())
428 Type |= macho::STF_PrivateExtern;
431 if (Data.isExternal() || Symbol.isUndefined())
432 Type |= macho::STF_External;
434 // Compute the symbol address.
435 if (Symbol.isDefined()) {
436 if (Symbol.isAbsolute()) {
437 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
439 Address = getSymbolAddress(&Data, Layout);
441 } else if (Data.isCommon()) {
442 // Common symbols are encoded with the size in the address
443 // field, and their alignment in the flags.
444 Address = Data.getCommonSize();
446 // Common alignment is packed into the 'desc' bits.
447 if (unsigned Align = Data.getCommonAlignment()) {
448 unsigned Log2Size = Log2_32(Align);
449 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
451 report_fatal_error("invalid 'common' alignment '" +
453 // FIXME: Keep this mask with the SymbolFlags enumeration.
454 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
458 // struct nlist (12 bytes)
460 Write32(MSD.StringIndex);
462 Write8(MSD.SectionIndex);
464 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
473 // FIXME: We really need to improve the relocation validation. Basically, we
474 // want to implement a separate computation which evaluates the relocation
475 // entry as the linker would, and verifies that the resultant fixup value is
476 // exactly what the encoder wanted. This will catch several classes of
479 // - Relocation entry bugs, the two algorithms are unlikely to have the same
482 // - Relaxation issues, where we forget to relax something.
484 // - Input errors, where something cannot be correctly encoded. 'as' allows
485 // these through in many cases.
487 static bool isFixupKindRIPRel(unsigned Kind) {
488 return Kind == X86::reloc_riprel_4byte ||
489 Kind == X86::reloc_riprel_4byte_movq_load;
491 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
492 const MCFragment *Fragment,
493 const MCFixup &Fixup, MCValue Target,
494 uint64_t &FixedValue) {
495 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
496 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
497 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
500 uint32_t FixupOffset =
501 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
502 uint32_t FixupAddress =
503 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
506 unsigned IsExtern = 0;
509 Value = Target.getConstant();
512 // Compensate for the relocation offset, Darwin x86_64 relocations only
513 // have the addend and appear to have attempted to define it to be the
514 // actual expression addend without the PCrel bias. However, instructions
515 // with data following the relocation are not accomodated for (see comment
516 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
517 Value += 1LL << Log2Size;
520 if (Target.isAbsolute()) { // constant
521 // SymbolNum of 0 indicates the absolute section.
522 Type = macho::RIT_X86_64_Unsigned;
525 // FIXME: I believe this is broken, I don't think the linker can
526 // understand it. I think it would require a local relocation, but I'm not
527 // sure if that would work either. The official way to get an absolute
528 // PCrel relocation is to use an absolute symbol (which we don't support
532 Type = macho::RIT_X86_64_Branch;
534 } else if (Target.getSymB()) { // A - B + constant
535 const MCSymbol *A = &Target.getSymA()->getSymbol();
536 MCSymbolData &A_SD = Asm.getSymbolData(*A);
537 const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
539 const MCSymbol *B = &Target.getSymB()->getSymbol();
540 MCSymbolData &B_SD = Asm.getSymbolData(*B);
541 const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
543 // Neither symbol can be modified.
544 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
545 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
546 report_fatal_error("unsupported relocation of modified symbol");
548 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
549 // implement most of these correctly.
551 report_fatal_error("unsupported pc-relative relocation of difference");
553 // The support for the situation where one or both of the symbols would
554 // require a local relocation is handled just like if the symbols were
555 // external. This is certainly used in the case of debug sections where
556 // the section has only temporary symbols and thus the symbols don't have
557 // base symbols. This is encoded using the section ordinal and
558 // non-extern relocation entries.
560 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
561 // a single SIGNED relocation); reject it for now. Except the case where
562 // both symbols don't have a base, equal but both NULL.
563 if (A_Base == B_Base && A_Base)
564 report_fatal_error("unsupported relocation with identical base");
566 Value += getSymbolAddress(&A_SD, Layout) -
567 (A_Base == NULL ? 0 : getSymbolAddress(A_Base, Layout));
568 Value -= getSymbolAddress(&B_SD, Layout) -
569 (B_Base == NULL ? 0 : getSymbolAddress(B_Base, Layout));
572 Index = A_Base->getIndex();
576 Index = A_SD.getFragment()->getParent()->getOrdinal() + 1;
579 Type = macho::RIT_X86_64_Unsigned;
581 macho::RelocationEntry MRE;
582 MRE.Word0 = FixupOffset;
583 MRE.Word1 = ((Index << 0) |
588 Relocations[Fragment->getParent()].push_back(MRE);
591 Index = B_Base->getIndex();
595 Index = B_SD.getFragment()->getParent()->getOrdinal() + 1;
598 Type = macho::RIT_X86_64_Subtractor;
600 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
601 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
602 const MCSymbolData *Base = Asm.getAtom(&SD);
604 // Relocations inside debug sections always use local relocations when
605 // possible. This seems to be done because the debugger doesn't fully
606 // understand x86_64 relocation entries, and expects to find values that
607 // have already been fixed up.
608 if (Symbol->isInSection()) {
609 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
610 Fragment->getParent()->getSection());
611 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
615 // x86_64 almost always uses external relocations, except when there is no
616 // symbol to use as a base address (a local symbol with no preceeding
617 // non-local symbol).
619 Index = Base->getIndex();
622 // Add the local offset, if needed.
624 Value += Layout.getSymbolOffset(&SD) - Layout.getSymbolOffset(Base);
625 } else if (Symbol->isInSection()) {
626 // The index is the section ordinal (1-based).
627 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
629 Value += getSymbolAddress(&SD, Layout);
632 Value -= FixupAddress + (1 << Log2Size);
633 } else if (Symbol->isVariable()) {
634 const MCExpr *Value = Symbol->getVariableValue();
636 bool isAbs = Value->EvaluateAsAbsolute(Res, Layout, SectionAddress);
641 report_fatal_error("unsupported relocation of variable '" +
642 Symbol->getName() + "'");
645 report_fatal_error("unsupported relocation of undefined symbol '" +
646 Symbol->getName() + "'");
649 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
652 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
653 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
654 // rewrite the movq to an leaq at link time if the symbol ends up in
655 // the same linkage unit.
656 if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
657 Type = macho::RIT_X86_64_GOTLoad;
659 Type = macho::RIT_X86_64_GOT;
660 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
661 Type = macho::RIT_X86_64_TLV;
662 } else if (Modifier != MCSymbolRefExpr::VK_None) {
663 report_fatal_error("unsupported symbol modifier in relocation");
665 Type = macho::RIT_X86_64_Signed;
667 // The Darwin x86_64 relocation format has a problem where it cannot
668 // encode an address (L<foo> + <constant>) which is outside the atom
669 // containing L<foo>. Generally, this shouldn't occur but it does
670 // happen when we have a RIPrel instruction with data following the
671 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
672 // adjustment Darwin x86_64 uses, the offset is still negative and
673 // the linker has no way to recognize this.
675 // To work around this, Darwin uses several special relocation types
676 // to indicate the offsets. However, the specification or
677 // implementation of these seems to also be incomplete; they should
678 // adjust the addend as well based on the actual encoded instruction
679 // (the additional bias), but instead appear to just look at the
681 switch (-(Target.getConstant() + (1LL << Log2Size))) {
682 case 1: Type = macho::RIT_X86_64_Signed1; break;
683 case 2: Type = macho::RIT_X86_64_Signed2; break;
684 case 4: Type = macho::RIT_X86_64_Signed4; break;
688 if (Modifier != MCSymbolRefExpr::VK_None)
689 report_fatal_error("unsupported symbol modifier in branch "
692 Type = macho::RIT_X86_64_Branch;
695 if (Modifier == MCSymbolRefExpr::VK_GOT) {
696 Type = macho::RIT_X86_64_GOT;
697 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
698 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
699 // which case all we do is set the PCrel bit in the relocation entry;
700 // this is used with exception handling, for example. The source is
701 // required to include any necessary offset directly.
702 Type = macho::RIT_X86_64_GOT;
704 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
705 report_fatal_error("TLVP symbol modifier should have been rip-rel");
706 } else if (Modifier != MCSymbolRefExpr::VK_None)
707 report_fatal_error("unsupported symbol modifier in relocation");
709 Type = macho::RIT_X86_64_Unsigned;
713 // x86_64 always writes custom values into the fixups.
716 // struct relocation_info (8 bytes)
717 macho::RelocationEntry MRE;
718 MRE.Word0 = FixupOffset;
719 MRE.Word1 = ((Index << 0) |
724 Relocations[Fragment->getParent()].push_back(MRE);
727 void RecordScatteredRelocation(const MCAssembler &Asm,
728 const MCAsmLayout &Layout,
729 const MCFragment *Fragment,
730 const MCFixup &Fixup, MCValue Target,
731 uint64_t &FixedValue) {
732 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
733 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
734 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
735 unsigned Type = macho::RIT_Vanilla;
738 const MCSymbol *A = &Target.getSymA()->getSymbol();
739 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
741 if (!A_SD->getFragment())
742 report_fatal_error("symbol '" + A->getName() +
743 "' can not be undefined in a subtraction expression");
745 uint32_t Value = getSymbolAddress(A_SD, Layout);
746 uint64_t SecAddr = getSectionAddress(A_SD->getFragment()->getParent());
747 FixedValue += SecAddr;
750 if (const MCSymbolRefExpr *B = Target.getSymB()) {
751 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
753 if (!B_SD->getFragment())
754 report_fatal_error("symbol '" + B->getSymbol().getName() +
755 "' can not be undefined in a subtraction expression");
757 // Select the appropriate difference relocation type.
759 // Note that there is no longer any semantic difference between these two
760 // relocation types from the linkers point of view, this is done solely
761 // for pedantic compatibility with 'as'.
762 Type = A_SD->isExternal() ? macho::RIT_Difference :
763 macho::RIT_LocalDifference;
764 Value2 = getSymbolAddress(B_SD, Layout);
765 FixedValue -= getSectionAddress(B_SD->getFragment()->getParent());
768 // Relocations are written out in reverse order, so the PAIR comes first.
769 if (Type == macho::RIT_Difference || Type == macho::RIT_LocalDifference) {
770 macho::RelocationEntry MRE;
771 MRE.Word0 = ((0 << 0) |
772 (macho::RIT_Pair << 24) |
775 macho::RF_Scattered);
777 Relocations[Fragment->getParent()].push_back(MRE);
780 macho::RelocationEntry MRE;
781 MRE.Word0 = ((FixupOffset << 0) |
785 macho::RF_Scattered);
787 Relocations[Fragment->getParent()].push_back(MRE);
790 void RecordTLVPRelocation(const MCAssembler &Asm,
791 const MCAsmLayout &Layout,
792 const MCFragment *Fragment,
793 const MCFixup &Fixup, MCValue Target,
794 uint64_t &FixedValue) {
795 assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
797 "Should only be called with a 32-bit TLVP relocation!");
799 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
800 uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
801 unsigned IsPCRel = 0;
803 // Get the symbol data.
804 MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
805 unsigned Index = SD_A->getIndex();
807 // We're only going to have a second symbol in pic mode and it'll be a
808 // subtraction from the picbase. For 32-bit pic the addend is the difference
809 // between the picbase and the next address. For 32-bit static the addend
811 if (Target.getSymB()) {
812 // If this is a subtraction then we're pcrel.
813 uint32_t FixupAddress =
814 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
815 MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
817 FixedValue = (FixupAddress - getSymbolAddress(SD_B, Layout) +
818 Target.getConstant());
819 FixedValue += 1ULL << Log2Size;
824 // struct relocation_info (8 bytes)
825 macho::RelocationEntry MRE;
827 MRE.Word1 = ((Index << 0) |
830 (1 << 27) | // Extern
831 (macho::RIT_TLV << 28)); // Type
832 Relocations[Fragment->getParent()].push_back(MRE);
835 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
836 const MCFragment *Fragment, const MCFixup &Fixup,
837 MCValue Target, uint64_t &FixedValue) {
839 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
843 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
844 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
846 // If this is a 32-bit TLVP reloc it's handled a bit differently.
847 if (Target.getSymA() &&
848 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
849 RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
853 // If this is a difference or a defined symbol plus an offset, then we need
854 // a scattered relocation entry.
855 // Differences always require scattered relocations.
856 if (Target.getSymB())
857 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
860 // Get the symbol data, if any.
861 MCSymbolData *SD = 0;
862 if (Target.getSymA())
863 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
865 // If this is an internal relocation with an offset, it also needs a
866 // scattered relocation entry.
867 uint32_t Offset = Target.getConstant();
869 Offset += 1 << Log2Size;
870 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
871 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
875 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
877 unsigned IsExtern = 0;
880 if (Target.isAbsolute()) { // constant
881 // SymbolNum of 0 indicates the absolute section.
883 // FIXME: Currently, these are never generated (see code below). I cannot
884 // find a case where they are actually emitted.
885 Type = macho::RIT_Vanilla;
886 } else if (SD->getSymbol().isVariable()) {
887 const MCExpr *Value = SD->getSymbol().getVariableValue();
889 bool isAbs = Value->EvaluateAsAbsolute(Res, Layout, SectionAddress);
894 report_fatal_error("unsupported relocation of variable '" +
895 SD->getSymbol().getName() + "'");
898 // Check whether we need an external or internal relocation.
899 if (doesSymbolRequireExternRelocation(SD)) {
901 Index = SD->getIndex();
902 // For external relocations, make sure to offset the fixup value to
903 // compensate for the addend of the symbol address, if it was
904 // undefined. This occurs with weak definitions, for example.
905 if (!SD->Symbol->isUndefined())
906 FixedValue -= Layout.getSymbolOffset(SD);
908 // The index is the section ordinal (1-based).
909 Index = SD->getFragment()->getParent()->getOrdinal() + 1;
910 FixedValue += getSectionAddress(SD->getFragment()->getParent());
913 FixedValue -= getSectionAddress(Fragment->getParent());
915 Type = macho::RIT_Vanilla;
918 // struct relocation_info (8 bytes)
919 macho::RelocationEntry MRE;
920 MRE.Word0 = FixupOffset;
921 MRE.Word1 = ((Index << 0) |
926 Relocations[Fragment->getParent()].push_back(MRE);
929 void BindIndirectSymbols(MCAssembler &Asm) {
930 // This is the point where 'as' creates actual symbols for indirect symbols
931 // (in the following two passes). It would be easier for us to do this
932 // sooner when we see the attribute, but that makes getting the order in the
933 // symbol table much more complicated than it is worth.
935 // FIXME: Revisit this when the dust settles.
937 // Bind non lazy symbol pointers first.
938 unsigned IndirectIndex = 0;
939 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
940 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
941 const MCSectionMachO &Section =
942 cast<MCSectionMachO>(it->SectionData->getSection());
944 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
947 // Initialize the section indirect symbol base, if necessary.
948 if (!IndirectSymBase.count(it->SectionData))
949 IndirectSymBase[it->SectionData] = IndirectIndex;
951 Asm.getOrCreateSymbolData(*it->Symbol);
954 // Then lazy symbol pointers and symbol stubs.
956 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
957 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
958 const MCSectionMachO &Section =
959 cast<MCSectionMachO>(it->SectionData->getSection());
961 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
962 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
965 // Initialize the section indirect symbol base, if necessary.
966 if (!IndirectSymBase.count(it->SectionData))
967 IndirectSymBase[it->SectionData] = IndirectIndex;
969 // Set the symbol type to undefined lazy, but only on construction.
971 // FIXME: Do not hardcode.
973 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
975 Entry.setFlags(Entry.getFlags() | 0x0001);
979 /// ComputeSymbolTable - Compute the symbol table data
981 /// \param StringTable [out] - The string table data.
982 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
984 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
985 std::vector<MachSymbolData> &LocalSymbolData,
986 std::vector<MachSymbolData> &ExternalSymbolData,
987 std::vector<MachSymbolData> &UndefinedSymbolData) {
988 // Build section lookup table.
989 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
991 for (MCAssembler::iterator it = Asm.begin(),
992 ie = Asm.end(); it != ie; ++it, ++Index)
993 SectionIndexMap[&it->getSection()] = Index;
994 assert(Index <= 256 && "Too many sections!");
996 // Index 0 is always the empty string.
997 StringMap<uint64_t> StringIndexMap;
998 StringTable += '\x00';
1000 // Build the symbol arrays and the string table, but only for non-local
1003 // The particular order that we collect the symbols and create the string
1004 // table, then sort the symbols is chosen to match 'as'. Even though it
1005 // doesn't matter for correctness, this is important for letting us diff .o
1007 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1008 ie = Asm.symbol_end(); it != ie; ++it) {
1009 const MCSymbol &Symbol = it->getSymbol();
1011 // Ignore non-linker visible symbols.
1012 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1015 if (!it->isExternal() && !Symbol.isUndefined())
1018 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1020 Entry = StringTable.size();
1021 StringTable += Symbol.getName();
1022 StringTable += '\x00';
1026 MSD.SymbolData = it;
1027 MSD.StringIndex = Entry;
1029 if (Symbol.isUndefined()) {
1030 MSD.SectionIndex = 0;
1031 UndefinedSymbolData.push_back(MSD);
1032 } else if (Symbol.isAbsolute()) {
1033 MSD.SectionIndex = 0;
1034 ExternalSymbolData.push_back(MSD);
1036 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1037 assert(MSD.SectionIndex && "Invalid section index!");
1038 ExternalSymbolData.push_back(MSD);
1042 // Now add the data for local symbols.
1043 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1044 ie = Asm.symbol_end(); it != ie; ++it) {
1045 const MCSymbol &Symbol = it->getSymbol();
1047 // Ignore non-linker visible symbols.
1048 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1051 if (it->isExternal() || Symbol.isUndefined())
1054 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1056 Entry = StringTable.size();
1057 StringTable += Symbol.getName();
1058 StringTable += '\x00';
1062 MSD.SymbolData = it;
1063 MSD.StringIndex = Entry;
1065 if (Symbol.isAbsolute()) {
1066 MSD.SectionIndex = 0;
1067 LocalSymbolData.push_back(MSD);
1069 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1070 assert(MSD.SectionIndex && "Invalid section index!");
1071 LocalSymbolData.push_back(MSD);
1075 // External and undefined symbols are required to be in lexicographic order.
1076 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1077 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1079 // Set the symbol indices.
1081 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1082 LocalSymbolData[i].SymbolData->setIndex(Index++);
1083 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1084 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1085 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1086 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1088 // The string table is padded to a multiple of 4.
1089 while (StringTable.size() % 4)
1090 StringTable += '\x00';
1093 void computeSectionAddresses(const MCAssembler &Asm,
1094 const MCAsmLayout &Layout) {
1095 uint64_t StartAddress = 0;
1096 const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
1097 for (int i = 0, n = Order.size(); i != n ; ++i) {
1098 const MCSectionData *SD = Order[i];
1099 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
1100 SectionAddress[SD] = StartAddress;
1101 StartAddress += Layout.getSectionAddressSize(SD);
1102 // Explicitly pad the section to match the alignment requirements of the
1103 // following one. This is for 'gas' compatibility, it shouldn't
1104 /// strictly be necessary.
1105 StartAddress += getPaddingSize(SD, Layout);
1109 void ExecutePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout) {
1110 computeSectionAddresses(Asm, Layout);
1112 // Create symbol data for any indirect symbols.
1113 BindIndirectSymbols(Asm);
1115 // Compute symbol table information and bind symbol indices.
1116 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1117 UndefinedSymbolData);
1121 bool IsFixupFullyResolved(const MCAssembler &Asm,
1122 const MCValue Target,
1124 const MCFragment *DF) const {
1125 // If we aren't using scattered symbols, the fixup is fully resolved.
1126 if (!Asm.getBackend().hasScatteredSymbols())
1129 // Otherwise, determine whether this value is actually resolved; scattering
1130 // may cause atoms to move.
1132 // Check if we are using the "simple" resolution algorithm (e.g.,
1134 if (!Asm.getBackend().hasReliableSymbolDifference()) {
1135 const MCSection *BaseSection = 0;
1137 BaseSection = &DF->getParent()->getSection();
1139 return isScatteredFixupFullyResolvedSimple(Asm, Target, BaseSection);
1142 // Otherwise, compute the proper answer as reliably as possible.
1144 // If this is a PCrel relocation, find the base atom (identified by its
1145 // symbol) that the fixup value is relative to.
1146 const MCSymbolData *BaseSymbol = 0;
1148 BaseSymbol = DF->getAtom();
1153 return isScatteredFixupFullyResolved(Asm, Target, BaseSymbol);
1156 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
1157 unsigned NumSections = Asm.size();
1159 // The section data starts after the header, the segment load command (and
1160 // section headers) and the symbol table.
1161 unsigned NumLoadCommands = 1;
1162 uint64_t LoadCommandsSize = Is64Bit ?
1163 macho::SegmentLoadCommand64Size + NumSections * macho::Section64Size :
1164 macho::SegmentLoadCommand32Size + NumSections * macho::Section32Size;
1166 // Add the symbol table load command sizes, if used.
1167 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1168 UndefinedSymbolData.size();
1170 NumLoadCommands += 2;
1171 LoadCommandsSize += (macho::SymtabLoadCommandSize +
1172 macho::DysymtabLoadCommandSize);
1175 // Compute the total size of the section data, as well as its file size and
1177 uint64_t SectionDataStart = (Is64Bit ? macho::Header64Size :
1178 macho::Header32Size) + LoadCommandsSize;
1179 uint64_t SectionDataSize = 0;
1180 uint64_t SectionDataFileSize = 0;
1181 uint64_t VMSize = 0;
1182 for (MCAssembler::const_iterator it = Asm.begin(),
1183 ie = Asm.end(); it != ie; ++it) {
1184 const MCSectionData &SD = *it;
1185 uint64_t Address = getSectionAddress(&SD);
1186 uint64_t Size = Layout.getSectionAddressSize(&SD);
1187 uint64_t FileSize = Layout.getSectionFileSize(&SD);
1188 FileSize += getPaddingSize(&SD, Layout);
1190 VMSize = std::max(VMSize, Address + Size);
1192 if (SD.getSection().isVirtualSection())
1195 SectionDataSize = std::max(SectionDataSize, Address + Size);
1196 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
1199 // The section data is padded to 4 bytes.
1201 // FIXME: Is this machine dependent?
1202 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1203 SectionDataFileSize += SectionDataPadding;
1205 // Write the prolog, starting with the header and load command...
1206 WriteHeader(NumLoadCommands, LoadCommandsSize,
1207 Asm.getSubsectionsViaSymbols());
1208 WriteSegmentLoadCommand(NumSections, VMSize,
1209 SectionDataStart, SectionDataSize);
1211 // ... and then the section headers.
1212 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1213 for (MCAssembler::const_iterator it = Asm.begin(),
1214 ie = Asm.end(); it != ie; ++it) {
1215 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
1216 unsigned NumRelocs = Relocs.size();
1217 uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
1218 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
1219 RelocTableEnd += NumRelocs * macho::RelocationInfoSize;
1222 // Write the symbol table load command, if used.
1224 unsigned FirstLocalSymbol = 0;
1225 unsigned NumLocalSymbols = LocalSymbolData.size();
1226 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1227 unsigned NumExternalSymbols = ExternalSymbolData.size();
1228 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1229 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1230 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1231 unsigned NumSymTabSymbols =
1232 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1233 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1234 uint64_t IndirectSymbolOffset = 0;
1236 // If used, the indirect symbols are written after the section data.
1237 if (NumIndirectSymbols)
1238 IndirectSymbolOffset = RelocTableEnd;
1240 // The symbol table is written after the indirect symbol data.
1241 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1243 // The string table is written after symbol table.
1244 uint64_t StringTableOffset =
1245 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? macho::Nlist64Size :
1246 macho::Nlist32Size);
1247 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1248 StringTableOffset, StringTable.size());
1250 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1251 FirstExternalSymbol, NumExternalSymbols,
1252 FirstUndefinedSymbol, NumUndefinedSymbols,
1253 IndirectSymbolOffset, NumIndirectSymbols);
1256 // Write the actual section data.
1257 for (MCAssembler::const_iterator it = Asm.begin(),
1258 ie = Asm.end(); it != ie; ++it) {
1259 Asm.WriteSectionData(it, Layout, this);
1261 uint64_t Pad = getPaddingSize(it, Layout);
1262 for (unsigned int i = 0; i < Pad; ++i)
1266 // Write the extra padding.
1267 WriteZeros(SectionDataPadding);
1269 // Write the relocation entries.
1270 for (MCAssembler::const_iterator it = Asm.begin(),
1271 ie = Asm.end(); it != ie; ++it) {
1272 // Write the section relocation entries, in reverse order to match 'as'
1273 // (approximately, the exact algorithm is more complicated than this).
1274 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
1275 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1276 Write32(Relocs[e - i - 1].Word0);
1277 Write32(Relocs[e - i - 1].Word1);
1281 // Write the symbol table data, if used.
1283 // Write the indirect symbol entries.
1284 for (MCAssembler::const_indirect_symbol_iterator
1285 it = Asm.indirect_symbol_begin(),
1286 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1287 // Indirect symbols in the non lazy symbol pointer section have some
1288 // special handling.
1289 const MCSectionMachO &Section =
1290 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1291 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1292 // If this symbol is defined and internal, mark it as such.
1293 if (it->Symbol->isDefined() &&
1294 !Asm.getSymbolData(*it->Symbol).isExternal()) {
1295 uint32_t Flags = macho::ISF_Local;
1296 if (it->Symbol->isAbsolute())
1297 Flags |= macho::ISF_Absolute;
1303 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1306 // FIXME: Check that offsets match computed ones.
1308 // Write the symbol table entries.
1309 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1310 WriteNlist(LocalSymbolData[i], Layout);
1311 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1312 WriteNlist(ExternalSymbolData[i], Layout);
1313 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1314 WriteNlist(UndefinedSymbolData[i], Layout);
1316 // Write the string table.
1317 OS << StringTable.str();
1324 MCObjectWriter *llvm::createMachObjectWriter(raw_ostream &OS, bool is64Bit,
1326 uint32_t CPUSubtype,
1327 bool IsLittleEndian) {
1328 return new MachObjectWriter(OS, is64Bit, CPUType, CPUSubtype, IsLittleEndian);