1 //===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MachObjectWriter.h"
11 #include "llvm/ADT/StringMap.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAssembler.h"
14 #include "llvm/MC/MCAsmLayout.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCObjectWriter.h"
17 #include "llvm/MC/MCSectionMachO.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/MC/MCMachOSymbolFlags.h"
20 #include "llvm/MC/MCValue.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MachO.h"
23 #include "llvm/Target/TargetAsmBackend.h"
26 #include "../Target/X86/X86FixupKinds.h"
31 static unsigned getFixupKindLog2Size(unsigned Kind) {
33 default: llvm_unreachable("invalid fixup kind!");
34 case X86::reloc_pcrel_1byte:
35 case FK_Data_1: return 0;
36 case FK_Data_2: return 1;
37 case X86::reloc_pcrel_4byte:
38 case X86::reloc_riprel_4byte:
39 case X86::reloc_riprel_4byte_movq_load:
40 case FK_Data_4: return 2;
41 case FK_Data_8: return 3;
45 static bool isFixupKindPCRel(unsigned Kind) {
49 case X86::reloc_pcrel_1byte:
50 case X86::reloc_pcrel_4byte:
51 case X86::reloc_riprel_4byte:
52 case X86::reloc_riprel_4byte_movq_load:
57 static bool isFixupKindRIPRel(unsigned Kind) {
58 return Kind == X86::reloc_riprel_4byte ||
59 Kind == X86::reloc_riprel_4byte_movq_load;
62 static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
63 // Undefined symbols are always extern.
64 if (SD->Symbol->isUndefined())
67 // References to weak definitions require external relocation entries; the
68 // definition may not always be the one in the same object file.
69 if (SD->getFlags() & SF_WeakDefinition)
72 // Otherwise, we can use an internal relocation.
78 class MachObjectWriterImpl {
79 // See <mach-o/loader.h>.
81 Header_Magic32 = 0xFEEDFACE,
82 Header_Magic64 = 0xFEEDFACF
88 SegmentLoadCommand32Size = 56,
89 SegmentLoadCommand64Size = 72,
92 SymtabLoadCommandSize = 24,
93 DysymtabLoadCommandSize = 80,
96 RelocationInfoSize = 8
104 HF_SubsectionsViaSymbols = 0x2000
107 enum LoadCommandType {
114 // See <mach-o/nlist.h>.
115 enum SymbolTypeType {
116 STT_Undefined = 0x00,
121 enum SymbolTypeFlags {
122 // If any of these bits are set, then the entry is a stab entry number (see
123 // <mach-o/stab.h>. Otherwise the other masks apply.
124 STF_StabsEntryMask = 0xe0,
128 STF_PrivateExtern = 0x10
131 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
133 enum IndirectSymbolFlags {
134 ISF_Local = 0x80000000,
135 ISF_Absolute = 0x40000000
138 /// RelocationFlags - Special flags for addresses.
139 enum RelocationFlags {
140 RF_Scattered = 0x80000000
143 enum RelocationInfoType {
147 RIT_PreboundLazyPointer = 3,
148 RIT_LocalDifference = 4,
152 /// X86_64 uses its own relocation types.
153 enum RelocationInfoTypeX86_64 {
154 RIT_X86_64_Unsigned = 0,
155 RIT_X86_64_Signed = 1,
156 RIT_X86_64_Branch = 2,
157 RIT_X86_64_GOTLoad = 3,
159 RIT_X86_64_Subtractor = 5,
160 RIT_X86_64_Signed1 = 6,
161 RIT_X86_64_Signed2 = 7,
162 RIT_X86_64_Signed4 = 8,
166 /// MachSymbolData - Helper struct for containing some precomputed information
168 struct MachSymbolData {
169 MCSymbolData *SymbolData;
170 uint64_t StringIndex;
171 uint8_t SectionIndex;
173 // Support lexicographic sorting.
174 bool operator<(const MachSymbolData &RHS) const {
175 return SymbolData->getSymbol().getName() <
176 RHS.SymbolData->getSymbol().getName();
180 /// @name Relocation Data
183 struct MachRelocationEntry {
188 llvm::DenseMap<const MCSectionData*,
189 std::vector<MachRelocationEntry> > Relocations;
190 llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
193 /// @name Symbol Table Data
196 SmallString<256> StringTable;
197 std::vector<MachSymbolData> LocalSymbolData;
198 std::vector<MachSymbolData> ExternalSymbolData;
199 std::vector<MachSymbolData> UndefinedSymbolData;
203 MachObjectWriter *Writer;
207 unsigned Is64Bit : 1;
210 MachObjectWriterImpl(MachObjectWriter *_Writer, bool _Is64Bit)
211 : Writer(_Writer), OS(Writer->getStream()), Is64Bit(_Is64Bit) {
214 void Write8(uint8_t Value) { Writer->Write8(Value); }
215 void Write16(uint16_t Value) { Writer->Write16(Value); }
216 void Write32(uint32_t Value) { Writer->Write32(Value); }
217 void Write64(uint64_t Value) { Writer->Write64(Value); }
218 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
219 void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
220 Writer->WriteBytes(Str, ZeroFillSize);
223 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
224 bool SubsectionsViaSymbols) {
227 if (SubsectionsViaSymbols)
228 Flags |= HF_SubsectionsViaSymbols;
230 // struct mach_header (28 bytes) or
231 // struct mach_header_64 (32 bytes)
233 uint64_t Start = OS.tell();
236 Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
238 // FIXME: Support cputype.
239 Write32(Is64Bit ? MachO::CPUTypeX86_64 : MachO::CPUTypeI386);
240 // FIXME: Support cpusubtype.
241 Write32(MachO::CPUSubType_I386_ALL);
243 Write32(NumLoadCommands); // Object files have a single load command, the
245 Write32(LoadCommandsSize);
248 Write32(0); // reserved
250 assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
253 /// WriteSegmentLoadCommand - Write a segment load command.
255 /// \arg NumSections - The number of sections in this segment.
256 /// \arg SectionDataSize - The total size of the sections.
257 void WriteSegmentLoadCommand(unsigned NumSections,
259 uint64_t SectionDataStartOffset,
260 uint64_t SectionDataSize) {
261 // struct segment_command (56 bytes) or
262 // struct segment_command_64 (72 bytes)
264 uint64_t Start = OS.tell();
267 unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
268 SegmentLoadCommand32Size;
269 Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
270 Write32(SegmentLoadCommandSize +
271 NumSections * (Is64Bit ? Section64Size : Section32Size));
275 Write64(0); // vmaddr
276 Write64(VMSize); // vmsize
277 Write64(SectionDataStartOffset); // file offset
278 Write64(SectionDataSize); // file size
280 Write32(0); // vmaddr
281 Write32(VMSize); // vmsize
282 Write32(SectionDataStartOffset); // file offset
283 Write32(SectionDataSize); // file size
285 Write32(0x7); // maxprot
286 Write32(0x7); // initprot
287 Write32(NumSections);
290 assert(OS.tell() - Start == SegmentLoadCommandSize);
293 void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
294 const MCSectionData &SD, uint64_t FileOffset,
295 uint64_t RelocationsStart, unsigned NumRelocations) {
296 uint64_t SectionSize = Layout.getSectionSize(&SD);
298 // The offset is unused for virtual sections.
299 if (Asm.getBackend().isVirtualSection(SD.getSection())) {
300 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
304 // struct section (68 bytes) or
305 // struct section_64 (80 bytes)
307 uint64_t Start = OS.tell();
310 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
311 WriteBytes(Section.getSectionName(), 16);
312 WriteBytes(Section.getSegmentName(), 16);
314 Write64(Layout.getSectionAddress(&SD)); // address
315 Write64(SectionSize); // size
317 Write32(Layout.getSectionAddress(&SD)); // address
318 Write32(SectionSize); // size
322 unsigned Flags = Section.getTypeAndAttributes();
323 if (SD.hasInstructions())
324 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
326 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
327 Write32(Log2_32(SD.getAlignment()));
328 Write32(NumRelocations ? RelocationsStart : 0);
329 Write32(NumRelocations);
331 Write32(IndirectSymBase.lookup(&SD)); // reserved1
332 Write32(Section.getStubSize()); // reserved2
334 Write32(0); // reserved3
336 assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
339 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
340 uint32_t StringTableOffset,
341 uint32_t StringTableSize) {
342 // struct symtab_command (24 bytes)
344 uint64_t Start = OS.tell();
348 Write32(SymtabLoadCommandSize);
349 Write32(SymbolOffset);
351 Write32(StringTableOffset);
352 Write32(StringTableSize);
354 assert(OS.tell() - Start == SymtabLoadCommandSize);
357 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
358 uint32_t NumLocalSymbols,
359 uint32_t FirstExternalSymbol,
360 uint32_t NumExternalSymbols,
361 uint32_t FirstUndefinedSymbol,
362 uint32_t NumUndefinedSymbols,
363 uint32_t IndirectSymbolOffset,
364 uint32_t NumIndirectSymbols) {
365 // struct dysymtab_command (80 bytes)
367 uint64_t Start = OS.tell();
370 Write32(LCT_Dysymtab);
371 Write32(DysymtabLoadCommandSize);
372 Write32(FirstLocalSymbol);
373 Write32(NumLocalSymbols);
374 Write32(FirstExternalSymbol);
375 Write32(NumExternalSymbols);
376 Write32(FirstUndefinedSymbol);
377 Write32(NumUndefinedSymbols);
378 Write32(0); // tocoff
380 Write32(0); // modtaboff
381 Write32(0); // nmodtab
382 Write32(0); // extrefsymoff
383 Write32(0); // nextrefsyms
384 Write32(IndirectSymbolOffset);
385 Write32(NumIndirectSymbols);
386 Write32(0); // extreloff
387 Write32(0); // nextrel
388 Write32(0); // locreloff
389 Write32(0); // nlocrel
391 assert(OS.tell() - Start == DysymtabLoadCommandSize);
394 void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
395 MCSymbolData &Data = *MSD.SymbolData;
396 const MCSymbol &Symbol = Data.getSymbol();
398 uint16_t Flags = Data.getFlags();
399 uint32_t Address = 0;
401 // Set the N_TYPE bits. See <mach-o/nlist.h>.
403 // FIXME: Are the prebound or indirect fields possible here?
404 if (Symbol.isUndefined())
405 Type = STT_Undefined;
406 else if (Symbol.isAbsolute())
411 // FIXME: Set STAB bits.
413 if (Data.isPrivateExtern())
414 Type |= STF_PrivateExtern;
417 if (Data.isExternal() || Symbol.isUndefined())
418 Type |= STF_External;
420 // Compute the symbol address.
421 if (Symbol.isDefined()) {
422 if (Symbol.isAbsolute()) {
423 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
425 Address = Layout.getSymbolAddress(&Data);
427 } else if (Data.isCommon()) {
428 // Common symbols are encoded with the size in the address
429 // field, and their alignment in the flags.
430 Address = Data.getCommonSize();
432 // Common alignment is packed into the 'desc' bits.
433 if (unsigned Align = Data.getCommonAlignment()) {
434 unsigned Log2Size = Log2_32(Align);
435 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
437 report_fatal_error("invalid 'common' alignment '" +
439 // FIXME: Keep this mask with the SymbolFlags enumeration.
440 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
444 // struct nlist (12 bytes)
446 Write32(MSD.StringIndex);
448 Write8(MSD.SectionIndex);
450 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
459 // FIXME: We really need to improve the relocation validation. Basically, we
460 // want to implement a separate computation which evaluates the relocation
461 // entry as the linker would, and verifies that the resultant fixup value is
462 // exactly what the encoder wanted. This will catch several classes of
465 // - Relocation entry bugs, the two algorithms are unlikely to have the same
468 // - Relaxation issues, where we forget to relax something.
470 // - Input errors, where something cannot be correctly encoded. 'as' allows
471 // these through in many cases.
473 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
474 const MCFragment *Fragment,
475 const MCAsmFixup &Fixup, MCValue Target,
476 uint64_t &FixedValue) {
477 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
478 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.Kind);
479 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
482 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.Offset;
483 uint32_t FixupAddress = Layout.getFragmentAddress(Fragment) + Fixup.Offset;
486 unsigned IsExtern = 0;
489 Value = Target.getConstant();
492 // Compensate for the relocation offset, Darwin x86_64 relocations only
493 // have the addend and appear to have attempted to define it to be the
494 // actual expression addend without the PCrel bias. However, instructions
495 // with data following the relocation are not accomodated for (see comment
496 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
497 Value += 1LL << Log2Size;
500 if (Target.isAbsolute()) { // constant
501 // SymbolNum of 0 indicates the absolute section.
502 Type = RIT_X86_64_Unsigned;
505 // FIXME: I believe this is broken, I don't think the linker can
506 // understand it. I think it would require a local relocation, but I'm not
507 // sure if that would work either. The official way to get an absolute
508 // PCrel relocation is to use an absolute symbol (which we don't support
512 Type = RIT_X86_64_Branch;
514 } else if (Target.getSymB()) { // A - B + constant
515 const MCSymbol *A = &Target.getSymA()->getSymbol();
516 MCSymbolData &A_SD = Asm.getSymbolData(*A);
517 const MCSymbolData *A_Base = Asm.getAtom(Layout, &A_SD);
519 const MCSymbol *B = &Target.getSymB()->getSymbol();
520 MCSymbolData &B_SD = Asm.getSymbolData(*B);
521 const MCSymbolData *B_Base = Asm.getAtom(Layout, &B_SD);
523 // Neither symbol can be modified.
524 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
525 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
526 report_fatal_error("unsupported relocation of modified symbol");
528 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
529 // implement most of these correctly.
531 report_fatal_error("unsupported pc-relative relocation of difference");
533 // We don't currently support any situation where one or both of the
534 // symbols would require a local relocation. This is almost certainly
535 // unused and may not be possible to encode correctly.
536 if (!A_Base || !B_Base)
537 report_fatal_error("unsupported local relocations in difference");
539 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
540 // a single SIGNED relocation); reject it for now.
541 if (A_Base == B_Base)
542 report_fatal_error("unsupported relocation with identical base");
544 Value += Layout.getSymbolAddress(&A_SD) - Layout.getSymbolAddress(A_Base);
545 Value -= Layout.getSymbolAddress(&B_SD) - Layout.getSymbolAddress(B_Base);
547 Index = A_Base->getIndex();
549 Type = RIT_X86_64_Unsigned;
551 MachRelocationEntry MRE;
552 MRE.Word0 = FixupOffset;
553 MRE.Word1 = ((Index << 0) |
558 Relocations[Fragment->getParent()].push_back(MRE);
560 Index = B_Base->getIndex();
562 Type = RIT_X86_64_Subtractor;
564 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
565 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
566 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
568 // Relocations inside debug sections always use local relocations when
569 // possible. This seems to be done because the debugger doesn't fully
570 // understand x86_64 relocation entries, and expects to find values that
571 // have already been fixed up.
572 if (Symbol->isInSection()) {
573 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
574 Fragment->getParent()->getSection());
575 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
579 // x86_64 almost always uses external relocations, except when there is no
580 // symbol to use as a base address (a local symbol with no preceeding
581 // non-local symbol).
583 Index = Base->getIndex();
586 // Add the local offset, if needed.
588 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
589 } else if (Symbol->isInSection()) {
590 // The index is the section ordinal (1-based).
591 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
593 Value += Layout.getSymbolAddress(&SD);
596 Value -= FixupAddress + (1 << Log2Size);
598 report_fatal_error("unsupported relocation of undefined symbol '" +
599 Symbol->getName() + "'");
602 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
605 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
606 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
607 // rewrite the movq to an leaq at link time if the symbol ends up in
608 // the same linkage unit.
609 if (unsigned(Fixup.Kind) == X86::reloc_riprel_4byte_movq_load)
610 Type = RIT_X86_64_GOTLoad;
612 Type = RIT_X86_64_GOT;
613 } else if (Modifier != MCSymbolRefExpr::VK_None) {
614 report_fatal_error("unsupported symbol modifier in relocation");
615 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
616 Type = RIT_X86_64_TLV;
618 Type = RIT_X86_64_Signed;
620 // The Darwin x86_64 relocation format has a problem where it cannot
621 // encode an address (L<foo> + <constant>) which is outside the atom
622 // containing L<foo>. Generally, this shouldn't occur but it does
623 // happen when we have a RIPrel instruction with data following the
624 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
625 // adjustment Darwin x86_64 uses, the offset is still negative and
626 // the linker has no way to recognize this.
628 // To work around this, Darwin uses several special relocation types
629 // to indicate the offsets. However, the specification or
630 // implementation of these seems to also be incomplete; they should
631 // adjust the addend as well based on the actual encoded instruction
632 // (the additional bias), but instead appear to just look at the
634 switch (-(Target.getConstant() + (1LL << Log2Size))) {
635 case 1: Type = RIT_X86_64_Signed1; break;
636 case 2: Type = RIT_X86_64_Signed2; break;
637 case 4: Type = RIT_X86_64_Signed4; break;
641 if (Modifier != MCSymbolRefExpr::VK_None)
642 report_fatal_error("unsupported symbol modifier in branch "
645 Type = RIT_X86_64_Branch;
648 if (Modifier == MCSymbolRefExpr::VK_GOT) {
649 Type = RIT_X86_64_GOT;
650 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
651 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
652 // which case all we do is set the PCrel bit in the relocation entry;
653 // this is used with exception handling, for example. The source is
654 // required to include any necessary offset directly.
655 Type = RIT_X86_64_GOT;
657 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
658 report_fatal_error("TLVP symbol modifier should have been rip-rel");
659 } else if (Modifier != MCSymbolRefExpr::VK_None)
660 report_fatal_error("unsupported symbol modifier in relocation");
662 Type = RIT_X86_64_Unsigned;
666 // x86_64 always writes custom values into the fixups.
669 // struct relocation_info (8 bytes)
670 MachRelocationEntry MRE;
671 MRE.Word0 = FixupOffset;
672 MRE.Word1 = ((Index << 0) |
677 Relocations[Fragment->getParent()].push_back(MRE);
680 void RecordScatteredRelocation(const MCAssembler &Asm,
681 const MCAsmLayout &Layout,
682 const MCFragment *Fragment,
683 const MCAsmFixup &Fixup, MCValue Target,
684 uint64_t &FixedValue) {
685 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.Offset;
686 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
687 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
688 unsigned Type = RIT_Vanilla;
691 const MCSymbol *A = &Target.getSymA()->getSymbol();
692 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
694 if (!A_SD->getFragment())
695 report_fatal_error("symbol '" + A->getName() +
696 "' can not be undefined in a subtraction expression");
698 uint32_t Value = Layout.getSymbolAddress(A_SD);
701 if (const MCSymbolRefExpr *B = Target.getSymB()) {
702 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
704 if (!B_SD->getFragment())
705 report_fatal_error("symbol '" + B->getSymbol().getName() +
706 "' can not be undefined in a subtraction expression");
708 // Select the appropriate difference relocation type.
710 // Note that there is no longer any semantic difference between these two
711 // relocation types from the linkers point of view, this is done solely
712 // for pedantic compatibility with 'as'.
713 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
714 Value2 = Layout.getSymbolAddress(B_SD);
717 // Relocations are written out in reverse order, so the PAIR comes first.
718 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
719 MachRelocationEntry MRE;
720 MRE.Word0 = ((0 << 0) |
726 Relocations[Fragment->getParent()].push_back(MRE);
729 MachRelocationEntry MRE;
730 MRE.Word0 = ((FixupOffset << 0) |
736 Relocations[Fragment->getParent()].push_back(MRE);
739 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
740 const MCFragment *Fragment, const MCAsmFixup &Fixup,
741 MCValue Target, uint64_t &FixedValue) {
743 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
747 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
748 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
750 // If this is a difference or a defined symbol plus an offset, then we need
751 // a scattered relocation entry.
752 // Differences always require scattered relocations.
753 if (Target.getSymB())
754 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
757 // Get the symbol data, if any.
758 MCSymbolData *SD = 0;
759 if (Target.getSymA())
760 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
762 // If this is an internal relocation with an offset, it also needs a
763 // scattered relocation entry.
764 uint32_t Offset = Target.getConstant();
766 Offset += 1 << Log2Size;
767 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
768 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
772 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.Offset;
775 unsigned IsExtern = 0;
778 if (Target.isAbsolute()) { // constant
779 // SymbolNum of 0 indicates the absolute section.
781 // FIXME: Currently, these are never generated (see code below). I cannot
782 // find a case where they are actually emitted.
786 // Check whether we need an external or internal relocation.
787 if (doesSymbolRequireExternRelocation(SD)) {
789 Index = SD->getIndex();
790 // For external relocations, make sure to offset the fixup value to
791 // compensate for the addend of the symbol address, if it was
792 // undefined. This occurs with weak definitions, for example.
793 if (!SD->Symbol->isUndefined())
794 FixedValue -= Layout.getSymbolAddress(SD);
797 // The index is the section ordinal (1-based).
798 Index = SD->getFragment()->getParent()->getOrdinal() + 1;
799 Value = Layout.getSymbolAddress(SD);
805 // struct relocation_info (8 bytes)
806 MachRelocationEntry MRE;
807 MRE.Word0 = FixupOffset;
808 MRE.Word1 = ((Index << 0) |
813 Relocations[Fragment->getParent()].push_back(MRE);
816 void BindIndirectSymbols(MCAssembler &Asm) {
817 // This is the point where 'as' creates actual symbols for indirect symbols
818 // (in the following two passes). It would be easier for us to do this
819 // sooner when we see the attribute, but that makes getting the order in the
820 // symbol table much more complicated than it is worth.
822 // FIXME: Revisit this when the dust settles.
824 // Bind non lazy symbol pointers first.
825 unsigned IndirectIndex = 0;
826 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
827 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
828 const MCSectionMachO &Section =
829 cast<MCSectionMachO>(it->SectionData->getSection());
831 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
834 // Initialize the section indirect symbol base, if necessary.
835 if (!IndirectSymBase.count(it->SectionData))
836 IndirectSymBase[it->SectionData] = IndirectIndex;
838 Asm.getOrCreateSymbolData(*it->Symbol);
841 // Then lazy symbol pointers and symbol stubs.
843 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
844 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
845 const MCSectionMachO &Section =
846 cast<MCSectionMachO>(it->SectionData->getSection());
848 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
849 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
852 // Initialize the section indirect symbol base, if necessary.
853 if (!IndirectSymBase.count(it->SectionData))
854 IndirectSymBase[it->SectionData] = IndirectIndex;
856 // Set the symbol type to undefined lazy, but only on construction.
858 // FIXME: Do not hardcode.
860 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
862 Entry.setFlags(Entry.getFlags() | 0x0001);
866 /// ComputeSymbolTable - Compute the symbol table data
868 /// \param StringTable [out] - The string table data.
869 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
871 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
872 std::vector<MachSymbolData> &LocalSymbolData,
873 std::vector<MachSymbolData> &ExternalSymbolData,
874 std::vector<MachSymbolData> &UndefinedSymbolData) {
875 // Build section lookup table.
876 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
878 for (MCAssembler::iterator it = Asm.begin(),
879 ie = Asm.end(); it != ie; ++it, ++Index)
880 SectionIndexMap[&it->getSection()] = Index;
881 assert(Index <= 256 && "Too many sections!");
883 // Index 0 is always the empty string.
884 StringMap<uint64_t> StringIndexMap;
885 StringTable += '\x00';
887 // Build the symbol arrays and the string table, but only for non-local
890 // The particular order that we collect the symbols and create the string
891 // table, then sort the symbols is chosen to match 'as'. Even though it
892 // doesn't matter for correctness, this is important for letting us diff .o
894 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
895 ie = Asm.symbol_end(); it != ie; ++it) {
896 const MCSymbol &Symbol = it->getSymbol();
898 // Ignore non-linker visible symbols.
899 if (!Asm.isSymbolLinkerVisible(it))
902 if (!it->isExternal() && !Symbol.isUndefined())
905 uint64_t &Entry = StringIndexMap[Symbol.getName()];
907 Entry = StringTable.size();
908 StringTable += Symbol.getName();
909 StringTable += '\x00';
914 MSD.StringIndex = Entry;
916 if (Symbol.isUndefined()) {
917 MSD.SectionIndex = 0;
918 UndefinedSymbolData.push_back(MSD);
919 } else if (Symbol.isAbsolute()) {
920 MSD.SectionIndex = 0;
921 ExternalSymbolData.push_back(MSD);
923 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
924 assert(MSD.SectionIndex && "Invalid section index!");
925 ExternalSymbolData.push_back(MSD);
929 // Now add the data for local symbols.
930 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
931 ie = Asm.symbol_end(); it != ie; ++it) {
932 const MCSymbol &Symbol = it->getSymbol();
934 // Ignore non-linker visible symbols.
935 if (!Asm.isSymbolLinkerVisible(it))
938 if (it->isExternal() || Symbol.isUndefined())
941 uint64_t &Entry = StringIndexMap[Symbol.getName()];
943 Entry = StringTable.size();
944 StringTable += Symbol.getName();
945 StringTable += '\x00';
950 MSD.StringIndex = Entry;
952 if (Symbol.isAbsolute()) {
953 MSD.SectionIndex = 0;
954 LocalSymbolData.push_back(MSD);
956 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
957 assert(MSD.SectionIndex && "Invalid section index!");
958 LocalSymbolData.push_back(MSD);
962 // External and undefined symbols are required to be in lexicographic order.
963 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
964 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
966 // Set the symbol indices.
968 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
969 LocalSymbolData[i].SymbolData->setIndex(Index++);
970 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
971 ExternalSymbolData[i].SymbolData->setIndex(Index++);
972 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
973 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
975 // The string table is padded to a multiple of 4.
976 while (StringTable.size() % 4)
977 StringTable += '\x00';
980 void ExecutePostLayoutBinding(MCAssembler &Asm) {
981 // Create symbol data for any indirect symbols.
982 BindIndirectSymbols(Asm);
984 // Compute symbol table information and bind symbol indices.
985 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
986 UndefinedSymbolData);
989 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout) {
990 unsigned NumSections = Asm.size();
992 // The section data starts after the header, the segment load command (and
993 // section headers) and the symbol table.
994 unsigned NumLoadCommands = 1;
995 uint64_t LoadCommandsSize = Is64Bit ?
996 SegmentLoadCommand64Size + NumSections * Section64Size :
997 SegmentLoadCommand32Size + NumSections * Section32Size;
999 // Add the symbol table load command sizes, if used.
1000 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1001 UndefinedSymbolData.size();
1003 NumLoadCommands += 2;
1004 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
1007 // Compute the total size of the section data, as well as its file size and
1009 uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
1011 uint64_t SectionDataSize = 0;
1012 uint64_t SectionDataFileSize = 0;
1013 uint64_t VMSize = 0;
1014 for (MCAssembler::const_iterator it = Asm.begin(),
1015 ie = Asm.end(); it != ie; ++it) {
1016 const MCSectionData &SD = *it;
1017 uint64_t Address = Layout.getSectionAddress(&SD);
1018 uint64_t Size = Layout.getSectionSize(&SD);
1019 uint64_t FileSize = Layout.getSectionFileSize(&SD);
1021 VMSize = std::max(VMSize, Address + Size);
1023 if (Asm.getBackend().isVirtualSection(SD.getSection()))
1026 SectionDataSize = std::max(SectionDataSize, Address + Size);
1027 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
1030 // The section data is padded to 4 bytes.
1032 // FIXME: Is this machine dependent?
1033 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1034 SectionDataFileSize += SectionDataPadding;
1036 // Write the prolog, starting with the header and load command...
1037 WriteHeader(NumLoadCommands, LoadCommandsSize,
1038 Asm.getSubsectionsViaSymbols());
1039 WriteSegmentLoadCommand(NumSections, VMSize,
1040 SectionDataStart, SectionDataSize);
1042 // ... and then the section headers.
1043 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1044 for (MCAssembler::const_iterator it = Asm.begin(),
1045 ie = Asm.end(); it != ie; ++it) {
1046 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1047 unsigned NumRelocs = Relocs.size();
1048 uint64_t SectionStart = SectionDataStart + Layout.getSectionAddress(it);
1049 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
1050 RelocTableEnd += NumRelocs * RelocationInfoSize;
1053 // Write the symbol table load command, if used.
1055 unsigned FirstLocalSymbol = 0;
1056 unsigned NumLocalSymbols = LocalSymbolData.size();
1057 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1058 unsigned NumExternalSymbols = ExternalSymbolData.size();
1059 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1060 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1061 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1062 unsigned NumSymTabSymbols =
1063 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1064 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1065 uint64_t IndirectSymbolOffset = 0;
1067 // If used, the indirect symbols are written after the section data.
1068 if (NumIndirectSymbols)
1069 IndirectSymbolOffset = RelocTableEnd;
1071 // The symbol table is written after the indirect symbol data.
1072 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1074 // The string table is written after symbol table.
1075 uint64_t StringTableOffset =
1076 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
1078 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1079 StringTableOffset, StringTable.size());
1081 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1082 FirstExternalSymbol, NumExternalSymbols,
1083 FirstUndefinedSymbol, NumUndefinedSymbols,
1084 IndirectSymbolOffset, NumIndirectSymbols);
1087 // Write the actual section data.
1088 for (MCAssembler::const_iterator it = Asm.begin(),
1089 ie = Asm.end(); it != ie; ++it)
1090 Asm.WriteSectionData(it, Layout, Writer);
1092 // Write the extra padding.
1093 WriteZeros(SectionDataPadding);
1095 // Write the relocation entries.
1096 for (MCAssembler::const_iterator it = Asm.begin(),
1097 ie = Asm.end(); it != ie; ++it) {
1098 // Write the section relocation entries, in reverse order to match 'as'
1099 // (approximately, the exact algorithm is more complicated than this).
1100 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1101 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1102 Write32(Relocs[e - i - 1].Word0);
1103 Write32(Relocs[e - i - 1].Word1);
1107 // Write the symbol table data, if used.
1109 // Write the indirect symbol entries.
1110 for (MCAssembler::const_indirect_symbol_iterator
1111 it = Asm.indirect_symbol_begin(),
1112 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1113 // Indirect symbols in the non lazy symbol pointer section have some
1114 // special handling.
1115 const MCSectionMachO &Section =
1116 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1117 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1118 // If this symbol is defined and internal, mark it as such.
1119 if (it->Symbol->isDefined() &&
1120 !Asm.getSymbolData(*it->Symbol).isExternal()) {
1121 uint32_t Flags = ISF_Local;
1122 if (it->Symbol->isAbsolute())
1123 Flags |= ISF_Absolute;
1129 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1132 // FIXME: Check that offsets match computed ones.
1134 // Write the symbol table entries.
1135 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1136 WriteNlist(LocalSymbolData[i], Layout);
1137 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1138 WriteNlist(ExternalSymbolData[i], Layout);
1139 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1140 WriteNlist(UndefinedSymbolData[i], Layout);
1142 // Write the string table.
1143 OS << StringTable.str();
1150 MachObjectWriter::MachObjectWriter(raw_ostream &OS,
1152 bool IsLittleEndian)
1153 : MCObjectWriter(OS, IsLittleEndian)
1155 Impl = new MachObjectWriterImpl(this, Is64Bit);
1158 MachObjectWriter::~MachObjectWriter() {
1159 delete (MachObjectWriterImpl*) Impl;
1162 void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1163 ((MachObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1166 void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
1167 const MCAsmLayout &Layout,
1168 const MCFragment *Fragment,
1169 const MCAsmFixup &Fixup, MCValue Target,
1170 uint64_t &FixedValue) {
1171 ((MachObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1172 Target, FixedValue);
1175 void MachObjectWriter::WriteObject(const MCAssembler &Asm,
1176 const MCAsmLayout &Layout) {
1177 ((MachObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);