1 //===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCMachObjectWriter.h"
11 #include "llvm/ADT/OwningPtr.h"
12 #include "llvm/ADT/StringMap.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAssembler.h"
15 #include "llvm/MC/MCAsmLayout.h"
16 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCObjectWriter.h"
18 #include "llvm/MC/MCSectionMachO.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/MC/MCMachOSymbolFlags.h"
21 #include "llvm/MC/MCValue.h"
22 #include "llvm/Object/MachOFormat.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Target/TargetAsmBackend.h"
27 #include "../Target/X86/X86FixupKinds.h"
31 using namespace llvm::object;
33 // FIXME: this has been copied from (or to) X86AsmBackend.cpp
34 static unsigned getFixupKindLog2Size(unsigned Kind) {
36 // FIXME: Until ARM has it's own relocation stuff spun off, it comes
37 // through here and we don't want it to puke all over. Any reasonable
38 // values will only come when ARM relocation support gets added, at which
39 // point this will be X86 only again and the llvm_unreachable can be
41 default: return 0;// llvm_unreachable("invalid fixup kind!");
43 case FK_Data_1: return 0;
45 case FK_Data_2: return 1;
47 case X86::reloc_riprel_4byte:
48 case X86::reloc_riprel_4byte_movq_load:
49 case X86::reloc_signed_4byte:
50 case FK_Data_4: return 2;
51 case FK_Data_8: return 3;
55 static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
56 // Undefined symbols are always extern.
57 if (SD->Symbol->isUndefined())
60 // References to weak definitions require external relocation entries; the
61 // definition may not always be the one in the same object file.
62 if (SD->getFlags() & SF_WeakDefinition)
65 // Otherwise, we can use an internal relocation.
69 static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
71 const MCSymbolData *BaseSymbol) {
72 // The effective fixup address is
73 // addr(atom(A)) + offset(A)
74 // - addr(atom(B)) - offset(B)
75 // - addr(BaseSymbol) + <fixup offset from base symbol>
76 // and the offsets are not relocatable, so the fixup is fully resolved when
77 // addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
79 // Note that "false" is almost always conservatively correct (it means we emit
80 // a relocation which is unnecessary), except when it would force us to emit a
81 // relocation which the target cannot encode.
83 const MCSymbolData *A_Base = 0, *B_Base = 0;
84 if (const MCSymbolRefExpr *A = Target.getSymA()) {
85 // Modified symbol references cannot be resolved.
86 if (A->getKind() != MCSymbolRefExpr::VK_None)
89 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
94 if (const MCSymbolRefExpr *B = Target.getSymB()) {
95 // Modified symbol references cannot be resolved.
96 if (B->getKind() != MCSymbolRefExpr::VK_None)
99 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
104 // If there is no base, A and B have to be the same atom for this fixup to be
107 return A_Base == B_Base;
109 // Otherwise, B must be missing and A must be the base.
110 return !B_Base && BaseSymbol == A_Base;
113 static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
114 const MCValue Target,
115 const MCSection *BaseSection) {
116 // The effective fixup address is
117 // addr(atom(A)) + offset(A)
118 // - addr(atom(B)) - offset(B)
119 // - addr(<base symbol>) + <fixup offset from base symbol>
120 // and the offsets are not relocatable, so the fixup is fully resolved when
121 // addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
123 // The simple (Darwin, except on x86_64) way of dealing with this was to
124 // assume that any reference to a temporary symbol *must* be a temporary
125 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
126 // relocation to a temporary symbol (in the same section) is fully
127 // resolved. This also works in conjunction with absolutized .set, which
128 // requires the compiler to use .set to absolutize the differences between
129 // symbols which the compiler knows to be assembly time constants, so we don't
130 // need to worry about considering symbol differences fully resolved.
132 // Non-relative fixups are only resolved if constant.
134 return Target.isAbsolute();
136 // Otherwise, relative fixups are only resolved if not a difference and the
137 // target is a temporary in the same section.
138 if (Target.isAbsolute() || Target.getSymB())
141 const MCSymbol *A = &Target.getSymA()->getSymbol();
142 if (!A->isTemporary() || !A->isInSection() ||
143 &A->getSection() != BaseSection)
151 class MachObjectWriter : public MCObjectWriter {
152 /// MachSymbolData - Helper struct for containing some precomputed information
154 struct MachSymbolData {
155 MCSymbolData *SymbolData;
156 uint64_t StringIndex;
157 uint8_t SectionIndex;
159 // Support lexicographic sorting.
160 bool operator<(const MachSymbolData &RHS) const {
161 return SymbolData->getSymbol().getName() <
162 RHS.SymbolData->getSymbol().getName();
166 /// The target specific Mach-O writer instance.
167 llvm::OwningPtr<MCMachObjectTargetWriter> TargetObjectWriter;
169 /// @name Relocation Data
172 llvm::DenseMap<const MCSectionData*,
173 std::vector<macho::RelocationEntry> > Relocations;
174 llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
177 /// @name Symbol Table Data
180 SmallString<256> StringTable;
181 std::vector<MachSymbolData> LocalSymbolData;
182 std::vector<MachSymbolData> ExternalSymbolData;
183 std::vector<MachSymbolData> UndefinedSymbolData;
188 /// @name Utility Methods
191 bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
192 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
195 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
200 SectionAddrMap SectionAddress;
201 uint64_t getSectionAddress(const MCSectionData* SD) const {
202 return SectionAddress.lookup(SD);
204 uint64_t getSymbolAddress(const MCSymbolData* SD,
205 const MCAsmLayout &Layout) const {
206 return getSectionAddress(SD->getFragment()->getParent()) +
207 Layout.getSymbolOffset(SD);
209 uint64_t getFragmentAddress(const MCFragment *Fragment,
210 const MCAsmLayout &Layout) const {
211 return getSectionAddress(Fragment->getParent()) +
212 Layout.getFragmentOffset(Fragment);
215 uint64_t getPaddingSize(const MCSectionData *SD,
216 const MCAsmLayout &Layout) const {
217 uint64_t EndAddr = getSectionAddress(SD) + Layout.getSectionAddressSize(SD);
218 unsigned Next = SD->getLayoutOrder() + 1;
219 if (Next >= Layout.getSectionOrder().size())
222 const MCSectionData &NextSD = *Layout.getSectionOrder()[Next];
223 if (NextSD.getSection().isVirtualSection())
225 return OffsetToAlignment(EndAddr, NextSD.getAlignment());
229 MachObjectWriter(MCMachObjectTargetWriter *MOTW, raw_ostream &_OS,
230 bool _IsLittleEndian)
231 : MCObjectWriter(_OS, _IsLittleEndian), TargetObjectWriter(MOTW) {
234 /// @name Target Writer Proxy Accessors
237 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
239 uint32_t CPUType = TargetObjectWriter->getCPUType() & mach::CTFM_ArchMask;
240 return CPUType == mach::CTM_ARM;
245 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
246 bool SubsectionsViaSymbols) {
249 if (SubsectionsViaSymbols)
250 Flags |= macho::HF_SubsectionsViaSymbols;
252 // struct mach_header (28 bytes) or
253 // struct mach_header_64 (32 bytes)
255 uint64_t Start = OS.tell();
258 Write32(is64Bit() ? macho::HM_Object64 : macho::HM_Object32);
260 Write32(TargetObjectWriter->getCPUType());
261 Write32(TargetObjectWriter->getCPUSubtype());
263 Write32(macho::HFT_Object);
264 Write32(NumLoadCommands);
265 Write32(LoadCommandsSize);
268 Write32(0); // reserved
270 assert(OS.tell() - Start == is64Bit() ?
271 macho::Header64Size : macho::Header32Size);
274 /// WriteSegmentLoadCommand - Write a segment load command.
276 /// \arg NumSections - The number of sections in this segment.
277 /// \arg SectionDataSize - The total size of the sections.
278 void WriteSegmentLoadCommand(unsigned NumSections,
280 uint64_t SectionDataStartOffset,
281 uint64_t SectionDataSize) {
282 // struct segment_command (56 bytes) or
283 // struct segment_command_64 (72 bytes)
285 uint64_t Start = OS.tell();
288 unsigned SegmentLoadCommandSize =
289 is64Bit() ? macho::SegmentLoadCommand64Size:
290 macho::SegmentLoadCommand32Size;
291 Write32(is64Bit() ? macho::LCT_Segment64 : macho::LCT_Segment);
292 Write32(SegmentLoadCommandSize +
293 NumSections * (is64Bit() ? macho::Section64Size :
294 macho::Section32Size));
298 Write64(0); // vmaddr
299 Write64(VMSize); // vmsize
300 Write64(SectionDataStartOffset); // file offset
301 Write64(SectionDataSize); // file size
303 Write32(0); // vmaddr
304 Write32(VMSize); // vmsize
305 Write32(SectionDataStartOffset); // file offset
306 Write32(SectionDataSize); // file size
308 Write32(0x7); // maxprot
309 Write32(0x7); // initprot
310 Write32(NumSections);
313 assert(OS.tell() - Start == SegmentLoadCommandSize);
316 void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
317 const MCSectionData &SD, uint64_t FileOffset,
318 uint64_t RelocationsStart, unsigned NumRelocations) {
319 uint64_t SectionSize = Layout.getSectionAddressSize(&SD);
321 // The offset is unused for virtual sections.
322 if (SD.getSection().isVirtualSection()) {
323 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
327 // struct section (68 bytes) or
328 // struct section_64 (80 bytes)
330 uint64_t Start = OS.tell();
333 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
334 WriteBytes(Section.getSectionName(), 16);
335 WriteBytes(Section.getSegmentName(), 16);
337 Write64(getSectionAddress(&SD)); // address
338 Write64(SectionSize); // size
340 Write32(getSectionAddress(&SD)); // address
341 Write32(SectionSize); // size
345 unsigned Flags = Section.getTypeAndAttributes();
346 if (SD.hasInstructions())
347 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
349 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
350 Write32(Log2_32(SD.getAlignment()));
351 Write32(NumRelocations ? RelocationsStart : 0);
352 Write32(NumRelocations);
354 Write32(IndirectSymBase.lookup(&SD)); // reserved1
355 Write32(Section.getStubSize()); // reserved2
357 Write32(0); // reserved3
359 assert(OS.tell() - Start == is64Bit() ? macho::Section64Size :
360 macho::Section32Size);
363 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
364 uint32_t StringTableOffset,
365 uint32_t StringTableSize) {
366 // struct symtab_command (24 bytes)
368 uint64_t Start = OS.tell();
371 Write32(macho::LCT_Symtab);
372 Write32(macho::SymtabLoadCommandSize);
373 Write32(SymbolOffset);
375 Write32(StringTableOffset);
376 Write32(StringTableSize);
378 assert(OS.tell() - Start == macho::SymtabLoadCommandSize);
381 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
382 uint32_t NumLocalSymbols,
383 uint32_t FirstExternalSymbol,
384 uint32_t NumExternalSymbols,
385 uint32_t FirstUndefinedSymbol,
386 uint32_t NumUndefinedSymbols,
387 uint32_t IndirectSymbolOffset,
388 uint32_t NumIndirectSymbols) {
389 // struct dysymtab_command (80 bytes)
391 uint64_t Start = OS.tell();
394 Write32(macho::LCT_Dysymtab);
395 Write32(macho::DysymtabLoadCommandSize);
396 Write32(FirstLocalSymbol);
397 Write32(NumLocalSymbols);
398 Write32(FirstExternalSymbol);
399 Write32(NumExternalSymbols);
400 Write32(FirstUndefinedSymbol);
401 Write32(NumUndefinedSymbols);
402 Write32(0); // tocoff
404 Write32(0); // modtaboff
405 Write32(0); // nmodtab
406 Write32(0); // extrefsymoff
407 Write32(0); // nextrefsyms
408 Write32(IndirectSymbolOffset);
409 Write32(NumIndirectSymbols);
410 Write32(0); // extreloff
411 Write32(0); // nextrel
412 Write32(0); // locreloff
413 Write32(0); // nlocrel
415 assert(OS.tell() - Start == macho::DysymtabLoadCommandSize);
418 void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
419 MCSymbolData &Data = *MSD.SymbolData;
420 const MCSymbol &Symbol = Data.getSymbol();
422 uint16_t Flags = Data.getFlags();
423 uint32_t Address = 0;
425 // Set the N_TYPE bits. See <mach-o/nlist.h>.
427 // FIXME: Are the prebound or indirect fields possible here?
428 if (Symbol.isUndefined())
429 Type = macho::STT_Undefined;
430 else if (Symbol.isAbsolute())
431 Type = macho::STT_Absolute;
433 Type = macho::STT_Section;
435 // FIXME: Set STAB bits.
437 if (Data.isPrivateExtern())
438 Type |= macho::STF_PrivateExtern;
441 if (Data.isExternal() || Symbol.isUndefined())
442 Type |= macho::STF_External;
444 // Compute the symbol address.
445 if (Symbol.isDefined()) {
446 if (Symbol.isAbsolute()) {
447 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
449 Address = getSymbolAddress(&Data, Layout);
451 } else if (Data.isCommon()) {
452 // Common symbols are encoded with the size in the address
453 // field, and their alignment in the flags.
454 Address = Data.getCommonSize();
456 // Common alignment is packed into the 'desc' bits.
457 if (unsigned Align = Data.getCommonAlignment()) {
458 unsigned Log2Size = Log2_32(Align);
459 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
461 report_fatal_error("invalid 'common' alignment '" +
463 // FIXME: Keep this mask with the SymbolFlags enumeration.
464 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
468 // struct nlist (12 bytes)
470 Write32(MSD.StringIndex);
472 Write8(MSD.SectionIndex);
474 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
483 // FIXME: We really need to improve the relocation validation. Basically, we
484 // want to implement a separate computation which evaluates the relocation
485 // entry as the linker would, and verifies that the resultant fixup value is
486 // exactly what the encoder wanted. This will catch several classes of
489 // - Relocation entry bugs, the two algorithms are unlikely to have the same
492 // - Relaxation issues, where we forget to relax something.
494 // - Input errors, where something cannot be correctly encoded. 'as' allows
495 // these through in many cases.
497 static bool isFixupKindRIPRel(unsigned Kind) {
498 return Kind == X86::reloc_riprel_4byte ||
499 Kind == X86::reloc_riprel_4byte_movq_load;
501 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
502 const MCFragment *Fragment,
503 const MCFixup &Fixup, MCValue Target,
504 uint64_t &FixedValue) {
505 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
506 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
507 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
510 uint32_t FixupOffset =
511 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
512 uint32_t FixupAddress =
513 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
516 unsigned IsExtern = 0;
519 Value = Target.getConstant();
522 // Compensate for the relocation offset, Darwin x86_64 relocations only
523 // have the addend and appear to have attempted to define it to be the
524 // actual expression addend without the PCrel bias. However, instructions
525 // with data following the relocation are not accomodated for (see comment
526 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
527 Value += 1LL << Log2Size;
530 if (Target.isAbsolute()) { // constant
531 // SymbolNum of 0 indicates the absolute section.
532 Type = macho::RIT_X86_64_Unsigned;
535 // FIXME: I believe this is broken, I don't think the linker can
536 // understand it. I think it would require a local relocation, but I'm not
537 // sure if that would work either. The official way to get an absolute
538 // PCrel relocation is to use an absolute symbol (which we don't support
542 Type = macho::RIT_X86_64_Branch;
544 } else if (Target.getSymB()) { // A - B + constant
545 const MCSymbol *A = &Target.getSymA()->getSymbol();
546 MCSymbolData &A_SD = Asm.getSymbolData(*A);
547 const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
549 const MCSymbol *B = &Target.getSymB()->getSymbol();
550 MCSymbolData &B_SD = Asm.getSymbolData(*B);
551 const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
553 // Neither symbol can be modified.
554 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
555 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
556 report_fatal_error("unsupported relocation of modified symbol");
558 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
559 // implement most of these correctly.
561 report_fatal_error("unsupported pc-relative relocation of difference");
563 // The support for the situation where one or both of the symbols would
564 // require a local relocation is handled just like if the symbols were
565 // external. This is certainly used in the case of debug sections where
566 // the section has only temporary symbols and thus the symbols don't have
567 // base symbols. This is encoded using the section ordinal and
568 // non-extern relocation entries.
570 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
571 // a single SIGNED relocation); reject it for now. Except the case where
572 // both symbols don't have a base, equal but both NULL.
573 if (A_Base == B_Base && A_Base)
574 report_fatal_error("unsupported relocation with identical base");
576 Value += getSymbolAddress(&A_SD, Layout) -
577 (A_Base == NULL ? 0 : getSymbolAddress(A_Base, Layout));
578 Value -= getSymbolAddress(&B_SD, Layout) -
579 (B_Base == NULL ? 0 : getSymbolAddress(B_Base, Layout));
582 Index = A_Base->getIndex();
586 Index = A_SD.getFragment()->getParent()->getOrdinal() + 1;
589 Type = macho::RIT_X86_64_Unsigned;
591 macho::RelocationEntry MRE;
592 MRE.Word0 = FixupOffset;
593 MRE.Word1 = ((Index << 0) |
598 Relocations[Fragment->getParent()].push_back(MRE);
601 Index = B_Base->getIndex();
605 Index = B_SD.getFragment()->getParent()->getOrdinal() + 1;
608 Type = macho::RIT_X86_64_Subtractor;
610 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
611 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
612 const MCSymbolData *Base = Asm.getAtom(&SD);
614 // Relocations inside debug sections always use local relocations when
615 // possible. This seems to be done because the debugger doesn't fully
616 // understand x86_64 relocation entries, and expects to find values that
617 // have already been fixed up.
618 if (Symbol->isInSection()) {
619 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
620 Fragment->getParent()->getSection());
621 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
625 // x86_64 almost always uses external relocations, except when there is no
626 // symbol to use as a base address (a local symbol with no preceeding
627 // non-local symbol).
629 Index = Base->getIndex();
632 // Add the local offset, if needed.
634 Value += Layout.getSymbolOffset(&SD) - Layout.getSymbolOffset(Base);
635 } else if (Symbol->isInSection()) {
636 // The index is the section ordinal (1-based).
637 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
639 Value += getSymbolAddress(&SD, Layout);
642 Value -= FixupAddress + (1 << Log2Size);
643 } else if (Symbol->isVariable()) {
644 const MCExpr *Value = Symbol->getVariableValue();
646 bool isAbs = Value->EvaluateAsAbsolute(Res, Layout, SectionAddress);
651 report_fatal_error("unsupported relocation of variable '" +
652 Symbol->getName() + "'");
655 report_fatal_error("unsupported relocation of undefined symbol '" +
656 Symbol->getName() + "'");
659 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
662 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
663 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
664 // rewrite the movq to an leaq at link time if the symbol ends up in
665 // the same linkage unit.
666 if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
667 Type = macho::RIT_X86_64_GOTLoad;
669 Type = macho::RIT_X86_64_GOT;
670 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
671 Type = macho::RIT_X86_64_TLV;
672 } else if (Modifier != MCSymbolRefExpr::VK_None) {
673 report_fatal_error("unsupported symbol modifier in relocation");
675 Type = macho::RIT_X86_64_Signed;
677 // The Darwin x86_64 relocation format has a problem where it cannot
678 // encode an address (L<foo> + <constant>) which is outside the atom
679 // containing L<foo>. Generally, this shouldn't occur but it does
680 // happen when we have a RIPrel instruction with data following the
681 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
682 // adjustment Darwin x86_64 uses, the offset is still negative and
683 // the linker has no way to recognize this.
685 // To work around this, Darwin uses several special relocation types
686 // to indicate the offsets. However, the specification or
687 // implementation of these seems to also be incomplete; they should
688 // adjust the addend as well based on the actual encoded instruction
689 // (the additional bias), but instead appear to just look at the
691 switch (-(Target.getConstant() + (1LL << Log2Size))) {
692 case 1: Type = macho::RIT_X86_64_Signed1; break;
693 case 2: Type = macho::RIT_X86_64_Signed2; break;
694 case 4: Type = macho::RIT_X86_64_Signed4; break;
698 if (Modifier != MCSymbolRefExpr::VK_None)
699 report_fatal_error("unsupported symbol modifier in branch "
702 Type = macho::RIT_X86_64_Branch;
705 if (Modifier == MCSymbolRefExpr::VK_GOT) {
706 Type = macho::RIT_X86_64_GOT;
707 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
708 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
709 // which case all we do is set the PCrel bit in the relocation entry;
710 // this is used with exception handling, for example. The source is
711 // required to include any necessary offset directly.
712 Type = macho::RIT_X86_64_GOT;
714 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
715 report_fatal_error("TLVP symbol modifier should have been rip-rel");
716 } else if (Modifier != MCSymbolRefExpr::VK_None)
717 report_fatal_error("unsupported symbol modifier in relocation");
719 Type = macho::RIT_X86_64_Unsigned;
723 // x86_64 always writes custom values into the fixups.
726 // struct relocation_info (8 bytes)
727 macho::RelocationEntry MRE;
728 MRE.Word0 = FixupOffset;
729 MRE.Word1 = ((Index << 0) |
734 Relocations[Fragment->getParent()].push_back(MRE);
737 void RecordScatteredRelocation(const MCAssembler &Asm,
738 const MCAsmLayout &Layout,
739 const MCFragment *Fragment,
740 const MCFixup &Fixup, MCValue Target,
741 uint64_t &FixedValue) {
742 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
743 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
744 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
745 unsigned Type = macho::RIT_Vanilla;
748 const MCSymbol *A = &Target.getSymA()->getSymbol();
749 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
751 if (!A_SD->getFragment())
752 report_fatal_error("symbol '" + A->getName() +
753 "' can not be undefined in a subtraction expression");
755 uint32_t Value = getSymbolAddress(A_SD, Layout);
756 uint64_t SecAddr = getSectionAddress(A_SD->getFragment()->getParent());
757 FixedValue += SecAddr;
760 if (const MCSymbolRefExpr *B = Target.getSymB()) {
761 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
763 if (!B_SD->getFragment())
764 report_fatal_error("symbol '" + B->getSymbol().getName() +
765 "' can not be undefined in a subtraction expression");
767 // Select the appropriate difference relocation type.
769 // Note that there is no longer any semantic difference between these two
770 // relocation types from the linkers point of view, this is done solely
771 // for pedantic compatibility with 'as'.
772 Type = A_SD->isExternal() ? (unsigned)macho::RIT_Difference :
773 (unsigned)macho::RIT_Generic_LocalDifference;
774 Value2 = getSymbolAddress(B_SD, Layout);
775 FixedValue -= getSectionAddress(B_SD->getFragment()->getParent());
778 // Relocations are written out in reverse order, so the PAIR comes first.
779 if (Type == macho::RIT_Difference ||
780 Type == macho::RIT_Generic_LocalDifference) {
781 macho::RelocationEntry MRE;
782 MRE.Word0 = ((0 << 0) |
783 (macho::RIT_Pair << 24) |
786 macho::RF_Scattered);
788 Relocations[Fragment->getParent()].push_back(MRE);
791 macho::RelocationEntry MRE;
792 MRE.Word0 = ((FixupOffset << 0) |
796 macho::RF_Scattered);
798 Relocations[Fragment->getParent()].push_back(MRE);
801 void RecordTLVPRelocation(const MCAssembler &Asm,
802 const MCAsmLayout &Layout,
803 const MCFragment *Fragment,
804 const MCFixup &Fixup, MCValue Target,
805 uint64_t &FixedValue) {
806 assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
808 "Should only be called with a 32-bit TLVP relocation!");
810 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
811 uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
812 unsigned IsPCRel = 0;
814 // Get the symbol data.
815 MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
816 unsigned Index = SD_A->getIndex();
818 // We're only going to have a second symbol in pic mode and it'll be a
819 // subtraction from the picbase. For 32-bit pic the addend is the difference
820 // between the picbase and the next address. For 32-bit static the addend
822 if (Target.getSymB()) {
823 // If this is a subtraction then we're pcrel.
824 uint32_t FixupAddress =
825 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
826 MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
828 FixedValue = (FixupAddress - getSymbolAddress(SD_B, Layout) +
829 Target.getConstant());
830 FixedValue += 1ULL << Log2Size;
835 // struct relocation_info (8 bytes)
836 macho::RelocationEntry MRE;
838 MRE.Word1 = ((Index << 0) |
841 (1 << 27) | // Extern
842 (macho::RIT_Generic_TLV << 28)); // Type
843 Relocations[Fragment->getParent()].push_back(MRE);
846 void RecordARMRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
847 const MCFragment *Fragment, const MCFixup &Fixup,
848 MCValue Target, uint64_t &FixedValue) {
849 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
850 // FIXME: Eliminate this!
851 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
853 // If this is a difference or a defined symbol plus an offset, then we need
854 // a scattered relocation entry. Differences always require scattered
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 // FIXME: For other platforms, we need to use scattered relocations for
866 // internal relocations with offsets. If this is an internal relocation
867 // with an offset, it also needs a scattered relocation entry.
869 // Is this right for ARM?
870 uint32_t Offset = Target.getConstant();
872 Offset += 1 << Log2Size;
873 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
874 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
878 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
880 unsigned IsExtern = 0;
883 if (Target.isAbsolute()) { // constant
885 report_fatal_error("FIXME: relocations to absolute targets "
886 "not yet implemented");
887 } else if (SD->getSymbol().isVariable()) {
889 if (SD->getSymbol().getVariableValue()->EvaluateAsAbsolute(
890 Res, Layout, SectionAddress)) {
895 report_fatal_error("unsupported relocation of variable '" +
896 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 RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
930 const MCFragment *Fragment, const MCFixup &Fixup,
931 MCValue Target, uint64_t &FixedValue) {
932 // FIXME: These needs to be factored into the target Mach-O writer.
934 RecordARMRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
938 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
942 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
943 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
945 // If this is a 32-bit TLVP reloc it's handled a bit differently.
946 if (Target.getSymA() &&
947 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
948 RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
952 // If this is a difference or a defined symbol plus an offset, then we need
953 // a scattered relocation entry.
954 // Differences always require scattered relocations.
955 if (Target.getSymB())
956 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
959 // Get the symbol data, if any.
960 MCSymbolData *SD = 0;
961 if (Target.getSymA())
962 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
964 // If this is an internal relocation with an offset, it also needs a
965 // scattered relocation entry.
966 uint32_t Offset = Target.getConstant();
968 Offset += 1 << Log2Size;
969 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
970 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
974 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
976 unsigned IsExtern = 0;
979 if (Target.isAbsolute()) { // constant
980 // SymbolNum of 0 indicates the absolute section.
982 // FIXME: Currently, these are never generated (see code below). I cannot
983 // find a case where they are actually emitted.
984 Type = macho::RIT_Vanilla;
985 } else if (SD->getSymbol().isVariable()) {
987 if (SD->getSymbol().getVariableValue()->EvaluateAsAbsolute(
988 Res, Layout, SectionAddress)) {
993 report_fatal_error("unsupported relocation of variable '" +
994 SD->getSymbol().getName() + "'");
996 // Check whether we need an external or internal relocation.
997 if (doesSymbolRequireExternRelocation(SD)) {
999 Index = SD->getIndex();
1000 // For external relocations, make sure to offset the fixup value to
1001 // compensate for the addend of the symbol address, if it was
1002 // undefined. This occurs with weak definitions, for example.
1003 if (!SD->Symbol->isUndefined())
1004 FixedValue -= Layout.getSymbolOffset(SD);
1006 // The index is the section ordinal (1-based).
1007 Index = SD->getFragment()->getParent()->getOrdinal() + 1;
1008 FixedValue += getSectionAddress(SD->getFragment()->getParent());
1011 FixedValue -= getSectionAddress(Fragment->getParent());
1013 Type = macho::RIT_Vanilla;
1016 // struct relocation_info (8 bytes)
1017 macho::RelocationEntry MRE;
1018 MRE.Word0 = FixupOffset;
1019 MRE.Word1 = ((Index << 0) |
1024 Relocations[Fragment->getParent()].push_back(MRE);
1027 void BindIndirectSymbols(MCAssembler &Asm) {
1028 // This is the point where 'as' creates actual symbols for indirect symbols
1029 // (in the following two passes). It would be easier for us to do this
1030 // sooner when we see the attribute, but that makes getting the order in the
1031 // symbol table much more complicated than it is worth.
1033 // FIXME: Revisit this when the dust settles.
1035 // Bind non lazy symbol pointers first.
1036 unsigned IndirectIndex = 0;
1037 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
1038 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
1039 const MCSectionMachO &Section =
1040 cast<MCSectionMachO>(it->SectionData->getSection());
1042 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
1045 // Initialize the section indirect symbol base, if necessary.
1046 if (!IndirectSymBase.count(it->SectionData))
1047 IndirectSymBase[it->SectionData] = IndirectIndex;
1049 Asm.getOrCreateSymbolData(*it->Symbol);
1052 // Then lazy symbol pointers and symbol stubs.
1054 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
1055 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
1056 const MCSectionMachO &Section =
1057 cast<MCSectionMachO>(it->SectionData->getSection());
1059 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
1060 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
1063 // Initialize the section indirect symbol base, if necessary.
1064 if (!IndirectSymBase.count(it->SectionData))
1065 IndirectSymBase[it->SectionData] = IndirectIndex;
1067 // Set the symbol type to undefined lazy, but only on construction.
1069 // FIXME: Do not hardcode.
1071 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
1073 Entry.setFlags(Entry.getFlags() | 0x0001);
1077 /// ComputeSymbolTable - Compute the symbol table data
1079 /// \param StringTable [out] - The string table data.
1080 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
1082 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
1083 std::vector<MachSymbolData> &LocalSymbolData,
1084 std::vector<MachSymbolData> &ExternalSymbolData,
1085 std::vector<MachSymbolData> &UndefinedSymbolData) {
1086 // Build section lookup table.
1087 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
1089 for (MCAssembler::iterator it = Asm.begin(),
1090 ie = Asm.end(); it != ie; ++it, ++Index)
1091 SectionIndexMap[&it->getSection()] = Index;
1092 assert(Index <= 256 && "Too many sections!");
1094 // Index 0 is always the empty string.
1095 StringMap<uint64_t> StringIndexMap;
1096 StringTable += '\x00';
1098 // Build the symbol arrays and the string table, but only for non-local
1101 // The particular order that we collect the symbols and create the string
1102 // table, then sort the symbols is chosen to match 'as'. Even though it
1103 // doesn't matter for correctness, this is important for letting us diff .o
1105 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1106 ie = Asm.symbol_end(); it != ie; ++it) {
1107 const MCSymbol &Symbol = it->getSymbol();
1109 // Ignore non-linker visible symbols.
1110 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1113 if (!it->isExternal() && !Symbol.isUndefined())
1116 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1118 Entry = StringTable.size();
1119 StringTable += Symbol.getName();
1120 StringTable += '\x00';
1124 MSD.SymbolData = it;
1125 MSD.StringIndex = Entry;
1127 if (Symbol.isUndefined()) {
1128 MSD.SectionIndex = 0;
1129 UndefinedSymbolData.push_back(MSD);
1130 } else if (Symbol.isAbsolute()) {
1131 MSD.SectionIndex = 0;
1132 ExternalSymbolData.push_back(MSD);
1134 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1135 assert(MSD.SectionIndex && "Invalid section index!");
1136 ExternalSymbolData.push_back(MSD);
1140 // Now add the data for local symbols.
1141 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1142 ie = Asm.symbol_end(); it != ie; ++it) {
1143 const MCSymbol &Symbol = it->getSymbol();
1145 // Ignore non-linker visible symbols.
1146 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1149 if (it->isExternal() || Symbol.isUndefined())
1152 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1154 Entry = StringTable.size();
1155 StringTable += Symbol.getName();
1156 StringTable += '\x00';
1160 MSD.SymbolData = it;
1161 MSD.StringIndex = Entry;
1163 if (Symbol.isAbsolute()) {
1164 MSD.SectionIndex = 0;
1165 LocalSymbolData.push_back(MSD);
1167 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1168 assert(MSD.SectionIndex && "Invalid section index!");
1169 LocalSymbolData.push_back(MSD);
1173 // External and undefined symbols are required to be in lexicographic order.
1174 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1175 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1177 // Set the symbol indices.
1179 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1180 LocalSymbolData[i].SymbolData->setIndex(Index++);
1181 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1182 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1183 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1184 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1186 // The string table is padded to a multiple of 4.
1187 while (StringTable.size() % 4)
1188 StringTable += '\x00';
1191 void computeSectionAddresses(const MCAssembler &Asm,
1192 const MCAsmLayout &Layout) {
1193 uint64_t StartAddress = 0;
1194 const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
1195 for (int i = 0, n = Order.size(); i != n ; ++i) {
1196 const MCSectionData *SD = Order[i];
1197 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
1198 SectionAddress[SD] = StartAddress;
1199 StartAddress += Layout.getSectionAddressSize(SD);
1200 // Explicitly pad the section to match the alignment requirements of the
1201 // following one. This is for 'gas' compatibility, it shouldn't
1202 /// strictly be necessary.
1203 StartAddress += getPaddingSize(SD, Layout);
1207 void ExecutePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout) {
1208 computeSectionAddresses(Asm, Layout);
1210 // Create symbol data for any indirect symbols.
1211 BindIndirectSymbols(Asm);
1213 // Compute symbol table information and bind symbol indices.
1214 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1215 UndefinedSymbolData);
1218 bool IsSymbolRefDifferenceFullyResolved(const MCAssembler &Asm,
1219 const MCSymbolRefExpr *A,
1220 const MCSymbolRefExpr *B,
1225 if (!TargetObjectWriter->useAggressiveSymbolFolding())
1228 // The effective address is
1229 // addr(atom(A)) + offset(A)
1230 // - addr(atom(B)) - offset(B)
1231 // and the offsets are not relocatable, so the fixup is fully resolved when
1232 // addr(atom(A)) - addr(atom(B)) == 0.
1233 const MCSymbolData *A_Base = 0, *B_Base = 0;
1235 // Modified symbol references cannot be resolved.
1236 if (A->getKind() != MCSymbolRefExpr::VK_None ||
1237 B->getKind() != MCSymbolRefExpr::VK_None)
1240 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
1244 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
1248 // If the atoms are the same, they are guaranteed to have the same address.
1249 if (A_Base == B_Base)
1252 // Otherwise, we can't prove this is fully resolved.
1256 bool IsFixupFullyResolved(const MCAssembler &Asm,
1257 const MCValue Target,
1259 const MCFragment *DF) const {
1260 // Otherwise, determine whether this value is actually resolved; scattering
1261 // may cause atoms to move.
1263 // Check if we are using the "simple" resolution algorithm (e.g.,
1265 if (!Asm.getBackend().hasReliableSymbolDifference()) {
1266 const MCSection *BaseSection = 0;
1268 BaseSection = &DF->getParent()->getSection();
1270 return isScatteredFixupFullyResolvedSimple(Asm, Target, BaseSection);
1273 // Otherwise, compute the proper answer as reliably as possible.
1275 // If this is a PCrel relocation, find the base atom (identified by its
1276 // symbol) that the fixup value is relative to.
1277 const MCSymbolData *BaseSymbol = 0;
1279 BaseSymbol = DF->getAtom();
1284 return isScatteredFixupFullyResolved(Asm, Target, BaseSymbol);
1287 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
1288 unsigned NumSections = Asm.size();
1290 // The section data starts after the header, the segment load command (and
1291 // section headers) and the symbol table.
1292 unsigned NumLoadCommands = 1;
1293 uint64_t LoadCommandsSize = is64Bit() ?
1294 macho::SegmentLoadCommand64Size + NumSections * macho::Section64Size :
1295 macho::SegmentLoadCommand32Size + NumSections * macho::Section32Size;
1297 // Add the symbol table load command sizes, if used.
1298 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1299 UndefinedSymbolData.size();
1301 NumLoadCommands += 2;
1302 LoadCommandsSize += (macho::SymtabLoadCommandSize +
1303 macho::DysymtabLoadCommandSize);
1306 // Compute the total size of the section data, as well as its file size and
1308 uint64_t SectionDataStart = (is64Bit() ? macho::Header64Size :
1309 macho::Header32Size) + LoadCommandsSize;
1310 uint64_t SectionDataSize = 0;
1311 uint64_t SectionDataFileSize = 0;
1312 uint64_t VMSize = 0;
1313 for (MCAssembler::const_iterator it = Asm.begin(),
1314 ie = Asm.end(); it != ie; ++it) {
1315 const MCSectionData &SD = *it;
1316 uint64_t Address = getSectionAddress(&SD);
1317 uint64_t Size = Layout.getSectionAddressSize(&SD);
1318 uint64_t FileSize = Layout.getSectionFileSize(&SD);
1319 FileSize += getPaddingSize(&SD, Layout);
1321 VMSize = std::max(VMSize, Address + Size);
1323 if (SD.getSection().isVirtualSection())
1326 SectionDataSize = std::max(SectionDataSize, Address + Size);
1327 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
1330 // The section data is padded to 4 bytes.
1332 // FIXME: Is this machine dependent?
1333 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1334 SectionDataFileSize += SectionDataPadding;
1336 // Write the prolog, starting with the header and load command...
1337 WriteHeader(NumLoadCommands, LoadCommandsSize,
1338 Asm.getSubsectionsViaSymbols());
1339 WriteSegmentLoadCommand(NumSections, VMSize,
1340 SectionDataStart, SectionDataSize);
1342 // ... and then the section headers.
1343 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1344 for (MCAssembler::const_iterator it = Asm.begin(),
1345 ie = Asm.end(); it != ie; ++it) {
1346 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
1347 unsigned NumRelocs = Relocs.size();
1348 uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
1349 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
1350 RelocTableEnd += NumRelocs * macho::RelocationInfoSize;
1353 // Write the symbol table load command, if used.
1355 unsigned FirstLocalSymbol = 0;
1356 unsigned NumLocalSymbols = LocalSymbolData.size();
1357 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1358 unsigned NumExternalSymbols = ExternalSymbolData.size();
1359 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1360 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1361 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1362 unsigned NumSymTabSymbols =
1363 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1364 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1365 uint64_t IndirectSymbolOffset = 0;
1367 // If used, the indirect symbols are written after the section data.
1368 if (NumIndirectSymbols)
1369 IndirectSymbolOffset = RelocTableEnd;
1371 // The symbol table is written after the indirect symbol data.
1372 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1374 // The string table is written after symbol table.
1375 uint64_t StringTableOffset =
1376 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ? macho::Nlist64Size :
1377 macho::Nlist32Size);
1378 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1379 StringTableOffset, StringTable.size());
1381 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1382 FirstExternalSymbol, NumExternalSymbols,
1383 FirstUndefinedSymbol, NumUndefinedSymbols,
1384 IndirectSymbolOffset, NumIndirectSymbols);
1387 // Write the actual section data.
1388 for (MCAssembler::const_iterator it = Asm.begin(),
1389 ie = Asm.end(); it != ie; ++it) {
1390 Asm.WriteSectionData(it, Layout);
1392 uint64_t Pad = getPaddingSize(it, Layout);
1393 for (unsigned int i = 0; i < Pad; ++i)
1397 // Write the extra padding.
1398 WriteZeros(SectionDataPadding);
1400 // Write the relocation entries.
1401 for (MCAssembler::const_iterator it = Asm.begin(),
1402 ie = Asm.end(); it != ie; ++it) {
1403 // Write the section relocation entries, in reverse order to match 'as'
1404 // (approximately, the exact algorithm is more complicated than this).
1405 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
1406 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1407 Write32(Relocs[e - i - 1].Word0);
1408 Write32(Relocs[e - i - 1].Word1);
1412 // Write the symbol table data, if used.
1414 // Write the indirect symbol entries.
1415 for (MCAssembler::const_indirect_symbol_iterator
1416 it = Asm.indirect_symbol_begin(),
1417 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1418 // Indirect symbols in the non lazy symbol pointer section have some
1419 // special handling.
1420 const MCSectionMachO &Section =
1421 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1422 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1423 // If this symbol is defined and internal, mark it as such.
1424 if (it->Symbol->isDefined() &&
1425 !Asm.getSymbolData(*it->Symbol).isExternal()) {
1426 uint32_t Flags = macho::ISF_Local;
1427 if (it->Symbol->isAbsolute())
1428 Flags |= macho::ISF_Absolute;
1434 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1437 // FIXME: Check that offsets match computed ones.
1439 // Write the symbol table entries.
1440 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1441 WriteNlist(LocalSymbolData[i], Layout);
1442 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1443 WriteNlist(ExternalSymbolData[i], Layout);
1444 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1445 WriteNlist(UndefinedSymbolData[i], Layout);
1447 // Write the string table.
1448 OS << StringTable.str();
1455 MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
1457 bool IsLittleEndian) {
1458 return new MachObjectWriter(MOTW, OS, IsLittleEndian);