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
151 /// X86_64 uses its own relocation types.
152 enum RelocationInfoTypeX86_64 {
153 RIT_X86_64_Unsigned = 0,
154 RIT_X86_64_Signed = 1,
155 RIT_X86_64_Branch = 2,
156 RIT_X86_64_GOTLoad = 3,
158 RIT_X86_64_Subtractor = 5,
159 RIT_X86_64_Signed1 = 6,
160 RIT_X86_64_Signed2 = 7,
161 RIT_X86_64_Signed4 = 8
164 /// MachSymbolData - Helper struct for containing some precomputed information
166 struct MachSymbolData {
167 MCSymbolData *SymbolData;
168 uint64_t StringIndex;
169 uint8_t SectionIndex;
171 // Support lexicographic sorting.
172 bool operator<(const MachSymbolData &RHS) const {
173 const std::string &Name = SymbolData->getSymbol().getName();
174 return Name < RHS.SymbolData->getSymbol().getName();
178 /// @name Relocation Data
181 struct MachRelocationEntry {
186 llvm::DenseMap<const MCSectionData*,
187 std::vector<MachRelocationEntry> > Relocations;
190 /// @name Symbol Table Data
193 SmallString<256> StringTable;
194 std::vector<MachSymbolData> LocalSymbolData;
195 std::vector<MachSymbolData> ExternalSymbolData;
196 std::vector<MachSymbolData> UndefinedSymbolData;
200 MachObjectWriter *Writer;
204 unsigned Is64Bit : 1;
207 MachObjectWriterImpl(MachObjectWriter *_Writer, bool _Is64Bit)
208 : Writer(_Writer), OS(Writer->getStream()), Is64Bit(_Is64Bit) {
211 void Write8(uint8_t Value) { Writer->Write8(Value); }
212 void Write16(uint16_t Value) { Writer->Write16(Value); }
213 void Write32(uint32_t Value) { Writer->Write32(Value); }
214 void Write64(uint64_t Value) { Writer->Write64(Value); }
215 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
216 void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
217 Writer->WriteBytes(Str, ZeroFillSize);
220 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
221 bool SubsectionsViaSymbols) {
224 if (SubsectionsViaSymbols)
225 Flags |= HF_SubsectionsViaSymbols;
227 // struct mach_header (28 bytes) or
228 // struct mach_header_64 (32 bytes)
230 uint64_t Start = OS.tell();
233 Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
235 // FIXME: Support cputype.
236 Write32(Is64Bit ? MachO::CPUTypeX86_64 : MachO::CPUTypeI386);
237 // FIXME: Support cpusubtype.
238 Write32(MachO::CPUSubType_I386_ALL);
240 Write32(NumLoadCommands); // Object files have a single load command, the
242 Write32(LoadCommandsSize);
245 Write32(0); // reserved
247 assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
250 /// WriteSegmentLoadCommand - Write a segment load command.
252 /// \arg NumSections - The number of sections in this segment.
253 /// \arg SectionDataSize - The total size of the sections.
254 void WriteSegmentLoadCommand(unsigned NumSections,
256 uint64_t SectionDataStartOffset,
257 uint64_t SectionDataSize) {
258 // struct segment_command (56 bytes) or
259 // struct segment_command_64 (72 bytes)
261 uint64_t Start = OS.tell();
264 unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
265 SegmentLoadCommand32Size;
266 Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
267 Write32(SegmentLoadCommandSize +
268 NumSections * (Is64Bit ? Section64Size : Section32Size));
272 Write64(0); // vmaddr
273 Write64(VMSize); // vmsize
274 Write64(SectionDataStartOffset); // file offset
275 Write64(SectionDataSize); // file size
277 Write32(0); // vmaddr
278 Write32(VMSize); // vmsize
279 Write32(SectionDataStartOffset); // file offset
280 Write32(SectionDataSize); // file size
282 Write32(0x7); // maxprot
283 Write32(0x7); // initprot
284 Write32(NumSections);
287 assert(OS.tell() - Start == SegmentLoadCommandSize);
290 void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
291 const MCSectionData &SD, uint64_t FileOffset,
292 uint64_t RelocationsStart, unsigned NumRelocations) {
293 uint64_t SectionSize = Layout.getSectionSize(&SD);
295 // The offset is unused for virtual sections.
296 if (Asm.getBackend().isVirtualSection(SD.getSection())) {
297 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
301 // struct section (68 bytes) or
302 // struct section_64 (80 bytes)
304 uint64_t Start = OS.tell();
307 // FIXME: cast<> support!
308 const MCSectionMachO &Section =
309 static_cast<const MCSectionMachO&>(SD.getSection());
310 WriteBytes(Section.getSectionName(), 16);
311 WriteBytes(Section.getSegmentName(), 16);
313 Write64(Layout.getSectionAddress(&SD)); // address
314 Write64(SectionSize); // size
316 Write32(Layout.getSectionAddress(&SD)); // address
317 Write32(SectionSize); // size
321 unsigned Flags = Section.getTypeAndAttributes();
322 if (SD.hasInstructions())
323 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
325 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
326 Write32(Log2_32(SD.getAlignment()));
327 Write32(NumRelocations ? RelocationsStart : 0);
328 Write32(NumRelocations);
330 Write32(0); // reserved1
331 Write32(Section.getStubSize()); // reserved2
333 Write32(0); // reserved3
335 assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
338 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
339 uint32_t StringTableOffset,
340 uint32_t StringTableSize) {
341 // struct symtab_command (24 bytes)
343 uint64_t Start = OS.tell();
347 Write32(SymtabLoadCommandSize);
348 Write32(SymbolOffset);
350 Write32(StringTableOffset);
351 Write32(StringTableSize);
353 assert(OS.tell() - Start == SymtabLoadCommandSize);
356 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
357 uint32_t NumLocalSymbols,
358 uint32_t FirstExternalSymbol,
359 uint32_t NumExternalSymbols,
360 uint32_t FirstUndefinedSymbol,
361 uint32_t NumUndefinedSymbols,
362 uint32_t IndirectSymbolOffset,
363 uint32_t NumIndirectSymbols) {
364 // struct dysymtab_command (80 bytes)
366 uint64_t Start = OS.tell();
369 Write32(LCT_Dysymtab);
370 Write32(DysymtabLoadCommandSize);
371 Write32(FirstLocalSymbol);
372 Write32(NumLocalSymbols);
373 Write32(FirstExternalSymbol);
374 Write32(NumExternalSymbols);
375 Write32(FirstUndefinedSymbol);
376 Write32(NumUndefinedSymbols);
377 Write32(0); // tocoff
379 Write32(0); // modtaboff
380 Write32(0); // nmodtab
381 Write32(0); // extrefsymoff
382 Write32(0); // nextrefsyms
383 Write32(IndirectSymbolOffset);
384 Write32(NumIndirectSymbols);
385 Write32(0); // extreloff
386 Write32(0); // nextrel
387 Write32(0); // locreloff
388 Write32(0); // nlocrel
390 assert(OS.tell() - Start == DysymtabLoadCommandSize);
393 void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
394 MCSymbolData &Data = *MSD.SymbolData;
395 const MCSymbol &Symbol = Data.getSymbol();
397 uint16_t Flags = Data.getFlags();
398 uint32_t Address = 0;
400 // Set the N_TYPE bits. See <mach-o/nlist.h>.
402 // FIXME: Are the prebound or indirect fields possible here?
403 if (Symbol.isUndefined())
404 Type = STT_Undefined;
405 else if (Symbol.isAbsolute())
410 // FIXME: Set STAB bits.
412 if (Data.isPrivateExtern())
413 Type |= STF_PrivateExtern;
416 if (Data.isExternal() || Symbol.isUndefined())
417 Type |= STF_External;
419 // Compute the symbol address.
420 if (Symbol.isDefined()) {
421 if (Symbol.isAbsolute()) {
422 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
424 Address = Layout.getSymbolAddress(&Data);
426 } else if (Data.isCommon()) {
427 // Common symbols are encoded with the size in the address
428 // field, and their alignment in the flags.
429 Address = Data.getCommonSize();
431 // Common alignment is packed into the 'desc' bits.
432 if (unsigned Align = Data.getCommonAlignment()) {
433 unsigned Log2Size = Log2_32(Align);
434 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
436 report_fatal_error("invalid 'common' alignment '" +
438 // FIXME: Keep this mask with the SymbolFlags enumeration.
439 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
443 // struct nlist (12 bytes)
445 Write32(MSD.StringIndex);
447 Write8(MSD.SectionIndex);
449 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
458 // FIXME: We really need to improve the relocation validation. Basically, we
459 // want to implement a separate computation which evaluates the relocation
460 // entry as the linker would, and verifies that the resultant fixup value is
461 // exactly what the encoder wanted. This will catch several classes of
464 // - Relocation entry bugs, the two algorithms are unlikely to have the same
467 // - Relaxation issues, where we forget to relax something.
469 // - Input errors, where something cannot be correctly encoded. 'as' allows
470 // these through in many cases.
472 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
473 const MCFragment *Fragment,
474 const MCAsmFixup &Fixup, MCValue Target,
475 uint64_t &FixedValue) {
476 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
477 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.Kind);
478 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
481 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.Offset;
482 uint32_t FixupAddress = Layout.getFragmentAddress(Fragment) + Fixup.Offset;
485 unsigned IsExtern = 0;
488 Value = Target.getConstant();
491 // Compensate for the relocation offset, Darwin x86_64 relocations only
492 // have the addend and appear to have attempted to define it to be the
493 // actual expression addend without the PCrel bias. However, instructions
494 // with data following the relocation are not accomodated for (see comment
495 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
496 Value += 1LL << Log2Size;
499 if (Target.isAbsolute()) { // constant
500 // SymbolNum of 0 indicates the absolute section.
501 Type = RIT_X86_64_Unsigned;
504 // FIXME: I believe this is broken, I don't think the linker can
505 // understand it. I think it would require a local relocation, but I'm not
506 // sure if that would work either. The official way to get an absolute
507 // PCrel relocation is to use an absolute symbol (which we don't support
511 Type = RIT_X86_64_Branch;
513 } else if (Target.getSymB()) { // A - B + constant
514 const MCSymbol *A = &Target.getSymA()->getSymbol();
515 MCSymbolData &A_SD = Asm.getSymbolData(*A);
516 const MCSymbolData *A_Base = Asm.getAtom(Layout, &A_SD);
518 const MCSymbol *B = &Target.getSymB()->getSymbol();
519 MCSymbolData &B_SD = Asm.getSymbolData(*B);
520 const MCSymbolData *B_Base = Asm.getAtom(Layout, &B_SD);
522 // Neither symbol can be modified.
523 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
524 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
525 report_fatal_error("unsupported relocation of modified symbol");
527 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
528 // implement most of these correctly.
530 report_fatal_error("unsupported pc-relative relocation of difference");
532 // We don't currently support any situation where one or both of the
533 // symbols would require a local relocation. This is almost certainly
534 // unused and may not be possible to encode correctly.
535 if (!A_Base || !B_Base)
536 report_fatal_error("unsupported local relocations in difference");
538 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
539 // a single SIGNED relocation); reject it for now.
540 if (A_Base == B_Base)
541 report_fatal_error("unsupported relocation with identical base");
543 Value += Layout.getSymbolAddress(&A_SD) - Layout.getSymbolAddress(A_Base);
544 Value -= Layout.getSymbolAddress(&B_SD) - Layout.getSymbolAddress(B_Base);
546 Index = A_Base->getIndex();
548 Type = RIT_X86_64_Unsigned;
550 MachRelocationEntry MRE;
551 MRE.Word0 = FixupOffset;
552 MRE.Word1 = ((Index << 0) |
557 Relocations[Fragment->getParent()].push_back(MRE);
559 Index = B_Base->getIndex();
561 Type = RIT_X86_64_Subtractor;
563 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
564 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
565 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
567 // Relocations inside debug sections always use local relocations when
568 // possible. This seems to be done because the debugger doesn't fully
569 // understand x86_64 relocation entries, and expects to find values that
570 // have already been fixed up.
571 if (Symbol->isInSection()) {
572 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
573 Fragment->getParent()->getSection());
574 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
578 // x86_64 almost always uses external relocations, except when there is no
579 // symbol to use as a base address (a local symbol with no preceeding
580 // non-local symbol).
582 Index = Base->getIndex();
585 // Add the local offset, if needed.
587 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
588 } else if (Symbol->isInSection()) {
589 // The index is the section ordinal (1-based).
590 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
592 Value += Layout.getSymbolAddress(&SD);
595 Value -= FixupAddress + (1 << Log2Size);
597 report_fatal_error("unsupported relocation of undefined symbol '" +
598 Symbol->getName() + "'");
601 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
604 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
605 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
606 // rewrite the movq to an leaq at link time if the symbol ends up in
607 // the same linkage unit.
608 if (unsigned(Fixup.Kind) == X86::reloc_riprel_4byte_movq_load)
609 Type = RIT_X86_64_GOTLoad;
611 Type = RIT_X86_64_GOT;
612 } else if (Modifier != MCSymbolRefExpr::VK_None)
613 report_fatal_error("unsupported symbol modifier in relocation");
615 Type = RIT_X86_64_Signed;
617 if (Modifier != MCSymbolRefExpr::VK_None)
618 report_fatal_error("unsupported symbol modifier in branch "
621 Type = RIT_X86_64_Branch;
624 // The Darwin x86_64 relocation format has a problem where it cannot
625 // encode an address (L<foo> + <constant>) which is outside the atom
626 // containing L<foo>. Generally, this shouldn't occur but it does happen
627 // when we have a RIPrel instruction with data following the relocation
628 // entry (e.g., movb $012, L0(%rip)). Even with the PCrel adjustment
629 // Darwin x86_64 uses, the offset is still negative and the linker has
630 // no way to recognize this.
632 // To work around this, Darwin uses several special relocation types to
633 // indicate the offsets. However, the specification or implementation of
634 // these seems to also be incomplete; they should adjust the addend as
635 // well based on the actual encoded instruction (the additional bias),
636 // but instead appear to just look at the final offset.
638 switch (-(Target.getConstant() + (1LL << Log2Size))) {
639 case 1: Type = RIT_X86_64_Signed1; break;
640 case 2: Type = RIT_X86_64_Signed2; break;
641 case 4: Type = RIT_X86_64_Signed4; break;
645 if (Modifier == MCSymbolRefExpr::VK_GOT) {
646 Type = RIT_X86_64_GOT;
647 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
648 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
649 // which case all we do is set the PCrel bit in the relocation entry;
650 // this is used with exception handling, for example. The source is
651 // required to include any necessary offset directly.
652 Type = RIT_X86_64_GOT;
654 } else if (Modifier != MCSymbolRefExpr::VK_None)
655 report_fatal_error("unsupported symbol modifier in relocation");
657 Type = RIT_X86_64_Unsigned;
661 // x86_64 always writes custom values into the fixups.
664 // struct relocation_info (8 bytes)
665 MachRelocationEntry MRE;
666 MRE.Word0 = FixupOffset;
667 MRE.Word1 = ((Index << 0) |
672 Relocations[Fragment->getParent()].push_back(MRE);
675 void RecordScatteredRelocation(const MCAssembler &Asm,
676 const MCAsmLayout &Layout,
677 const MCFragment *Fragment,
678 const MCAsmFixup &Fixup, MCValue Target,
679 uint64_t &FixedValue) {
680 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.Offset;
681 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
682 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
683 unsigned Type = RIT_Vanilla;
686 const MCSymbol *A = &Target.getSymA()->getSymbol();
687 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
689 if (!A_SD->getFragment())
690 report_fatal_error("symbol '" + A->getName() +
691 "' can not be undefined in a subtraction expression");
693 uint32_t Value = Layout.getSymbolAddress(A_SD);
696 if (const MCSymbolRefExpr *B = Target.getSymB()) {
697 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
699 if (!B_SD->getFragment())
700 report_fatal_error("symbol '" + B->getSymbol().getName() +
701 "' can not be undefined in a subtraction expression");
703 // Select the appropriate difference relocation type.
705 // Note that there is no longer any semantic difference between these two
706 // relocation types from the linkers point of view, this is done solely
707 // for pedantic compatibility with 'as'.
708 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
709 Value2 = Layout.getSymbolAddress(B_SD);
712 // Relocations are written out in reverse order, so the PAIR comes first.
713 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
714 MachRelocationEntry MRE;
715 MRE.Word0 = ((0 << 0) |
721 Relocations[Fragment->getParent()].push_back(MRE);
724 MachRelocationEntry MRE;
725 MRE.Word0 = ((FixupOffset << 0) |
731 Relocations[Fragment->getParent()].push_back(MRE);
734 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
735 const MCFragment *Fragment, const MCAsmFixup &Fixup,
736 MCValue Target, uint64_t &FixedValue) {
738 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
742 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
743 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
745 // If this is a difference or a defined symbol plus an offset, then we need
746 // a scattered relocation entry.
747 // Differences always require scattered relocations.
748 if (Target.getSymB())
749 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
752 // Get the symbol data, if any.
753 MCSymbolData *SD = 0;
754 if (Target.getSymA())
755 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
757 // If this is an internal relocation with an offset, it also needs a
758 // scattered relocation entry.
759 uint32_t Offset = Target.getConstant();
761 Offset += 1 << Log2Size;
762 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
763 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
767 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.Offset;
770 unsigned IsExtern = 0;
773 if (Target.isAbsolute()) { // constant
774 // SymbolNum of 0 indicates the absolute section.
776 // FIXME: Currently, these are never generated (see code below). I cannot
777 // find a case where they are actually emitted.
781 // Check whether we need an external or internal relocation.
782 if (doesSymbolRequireExternRelocation(SD)) {
784 Index = SD->getIndex();
785 // For external relocations, make sure to offset the fixup value to
786 // compensate for the addend of the symbol address, if it was
787 // undefined. This occurs with weak definitions, for example.
788 if (!SD->Symbol->isUndefined())
789 FixedValue -= Layout.getSymbolAddress(SD);
792 // The index is the section ordinal (1-based).
793 Index = SD->getFragment()->getParent()->getOrdinal() + 1;
794 Value = Layout.getSymbolAddress(SD);
800 // struct relocation_info (8 bytes)
801 MachRelocationEntry MRE;
802 MRE.Word0 = FixupOffset;
803 MRE.Word1 = ((Index << 0) |
808 Relocations[Fragment->getParent()].push_back(MRE);
811 void BindIndirectSymbols(MCAssembler &Asm) {
812 // This is the point where 'as' creates actual symbols for indirect symbols
813 // (in the following two passes). It would be easier for us to do this
814 // sooner when we see the attribute, but that makes getting the order in the
815 // symbol table much more complicated than it is worth.
817 // FIXME: Revisit this when the dust settles.
819 // Bind non lazy symbol pointers first.
820 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
821 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
822 // FIXME: cast<> support!
823 const MCSectionMachO &Section =
824 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
826 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
829 Asm.getOrCreateSymbolData(*it->Symbol);
832 // Then lazy symbol pointers and symbol stubs.
833 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
834 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
835 // FIXME: cast<> support!
836 const MCSectionMachO &Section =
837 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
839 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
840 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
843 // Set the symbol type to undefined lazy, but only on construction.
845 // FIXME: Do not hardcode.
847 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
849 Entry.setFlags(Entry.getFlags() | 0x0001);
853 /// ComputeSymbolTable - Compute the symbol table data
855 /// \param StringTable [out] - The string table data.
856 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
858 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
859 std::vector<MachSymbolData> &LocalSymbolData,
860 std::vector<MachSymbolData> &ExternalSymbolData,
861 std::vector<MachSymbolData> &UndefinedSymbolData) {
862 // Build section lookup table.
863 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
865 for (MCAssembler::iterator it = Asm.begin(),
866 ie = Asm.end(); it != ie; ++it, ++Index)
867 SectionIndexMap[&it->getSection()] = Index;
868 assert(Index <= 256 && "Too many sections!");
870 // Index 0 is always the empty string.
871 StringMap<uint64_t> StringIndexMap;
872 StringTable += '\x00';
874 // Build the symbol arrays and the string table, but only for non-local
877 // The particular order that we collect the symbols and create the string
878 // table, then sort the symbols is chosen to match 'as'. Even though it
879 // doesn't matter for correctness, this is important for letting us diff .o
881 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
882 ie = Asm.symbol_end(); it != ie; ++it) {
883 const MCSymbol &Symbol = it->getSymbol();
885 // Ignore non-linker visible symbols.
886 if (!Asm.isSymbolLinkerVisible(it))
889 if (!it->isExternal() && !Symbol.isUndefined())
892 uint64_t &Entry = StringIndexMap[Symbol.getName()];
894 Entry = StringTable.size();
895 StringTable += Symbol.getName();
896 StringTable += '\x00';
901 MSD.StringIndex = Entry;
903 if (Symbol.isUndefined()) {
904 MSD.SectionIndex = 0;
905 UndefinedSymbolData.push_back(MSD);
906 } else if (Symbol.isAbsolute()) {
907 MSD.SectionIndex = 0;
908 ExternalSymbolData.push_back(MSD);
910 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
911 assert(MSD.SectionIndex && "Invalid section index!");
912 ExternalSymbolData.push_back(MSD);
916 // Now add the data for local symbols.
917 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
918 ie = Asm.symbol_end(); it != ie; ++it) {
919 const MCSymbol &Symbol = it->getSymbol();
921 // Ignore non-linker visible symbols.
922 if (!Asm.isSymbolLinkerVisible(it))
925 if (it->isExternal() || Symbol.isUndefined())
928 uint64_t &Entry = StringIndexMap[Symbol.getName()];
930 Entry = StringTable.size();
931 StringTable += Symbol.getName();
932 StringTable += '\x00';
937 MSD.StringIndex = Entry;
939 if (Symbol.isAbsolute()) {
940 MSD.SectionIndex = 0;
941 LocalSymbolData.push_back(MSD);
943 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
944 assert(MSD.SectionIndex && "Invalid section index!");
945 LocalSymbolData.push_back(MSD);
949 // External and undefined symbols are required to be in lexicographic order.
950 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
951 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
953 // Set the symbol indices.
955 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
956 LocalSymbolData[i].SymbolData->setIndex(Index++);
957 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
958 ExternalSymbolData[i].SymbolData->setIndex(Index++);
959 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
960 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
962 // The string table is padded to a multiple of 4.
963 while (StringTable.size() % 4)
964 StringTable += '\x00';
967 void ExecutePostLayoutBinding(MCAssembler &Asm) {
968 // Create symbol data for any indirect symbols.
969 BindIndirectSymbols(Asm);
971 // Compute symbol table information and bind symbol indices.
972 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
973 UndefinedSymbolData);
976 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout) {
977 unsigned NumSections = Asm.size();
979 // The section data starts after the header, the segment load command (and
980 // section headers) and the symbol table.
981 unsigned NumLoadCommands = 1;
982 uint64_t LoadCommandsSize = Is64Bit ?
983 SegmentLoadCommand64Size + NumSections * Section64Size :
984 SegmentLoadCommand32Size + NumSections * Section32Size;
986 // Add the symbol table load command sizes, if used.
987 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
988 UndefinedSymbolData.size();
990 NumLoadCommands += 2;
991 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
994 // Compute the total size of the section data, as well as its file size and
996 uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
998 uint64_t SectionDataSize = 0;
999 uint64_t SectionDataFileSize = 0;
1000 uint64_t VMSize = 0;
1001 for (MCAssembler::const_iterator it = Asm.begin(),
1002 ie = Asm.end(); it != ie; ++it) {
1003 const MCSectionData &SD = *it;
1004 uint64_t Address = Layout.getSectionAddress(&SD);
1005 uint64_t Size = Layout.getSectionSize(&SD);
1006 uint64_t FileSize = Layout.getSectionFileSize(&SD);
1008 VMSize = std::max(VMSize, Address + Size);
1010 if (Asm.getBackend().isVirtualSection(SD.getSection()))
1013 SectionDataSize = std::max(SectionDataSize, Address + Size);
1014 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
1017 // The section data is padded to 4 bytes.
1019 // FIXME: Is this machine dependent?
1020 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1021 SectionDataFileSize += SectionDataPadding;
1023 // Write the prolog, starting with the header and load command...
1024 WriteHeader(NumLoadCommands, LoadCommandsSize,
1025 Asm.getSubsectionsViaSymbols());
1026 WriteSegmentLoadCommand(NumSections, VMSize,
1027 SectionDataStart, SectionDataSize);
1029 // ... and then the section headers.
1030 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1031 for (MCAssembler::const_iterator it = Asm.begin(),
1032 ie = Asm.end(); it != ie; ++it) {
1033 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1034 unsigned NumRelocs = Relocs.size();
1035 uint64_t SectionStart = SectionDataStart + Layout.getSectionAddress(it);
1036 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
1037 RelocTableEnd += NumRelocs * RelocationInfoSize;
1040 // Write the symbol table load command, if used.
1042 unsigned FirstLocalSymbol = 0;
1043 unsigned NumLocalSymbols = LocalSymbolData.size();
1044 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1045 unsigned NumExternalSymbols = ExternalSymbolData.size();
1046 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1047 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1048 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1049 unsigned NumSymTabSymbols =
1050 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1051 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1052 uint64_t IndirectSymbolOffset = 0;
1054 // If used, the indirect symbols are written after the section data.
1055 if (NumIndirectSymbols)
1056 IndirectSymbolOffset = RelocTableEnd;
1058 // The symbol table is written after the indirect symbol data.
1059 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1061 // The string table is written after symbol table.
1062 uint64_t StringTableOffset =
1063 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
1065 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1066 StringTableOffset, StringTable.size());
1068 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1069 FirstExternalSymbol, NumExternalSymbols,
1070 FirstUndefinedSymbol, NumUndefinedSymbols,
1071 IndirectSymbolOffset, NumIndirectSymbols);
1074 // Write the actual section data.
1075 for (MCAssembler::const_iterator it = Asm.begin(),
1076 ie = Asm.end(); it != ie; ++it)
1077 Asm.WriteSectionData(it, Layout, Writer);
1079 // Write the extra padding.
1080 WriteZeros(SectionDataPadding);
1082 // Write the relocation entries.
1083 for (MCAssembler::const_iterator it = Asm.begin(),
1084 ie = Asm.end(); it != ie; ++it) {
1085 // Write the section relocation entries, in reverse order to match 'as'
1086 // (approximately, the exact algorithm is more complicated than this).
1087 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1088 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1089 Write32(Relocs[e - i - 1].Word0);
1090 Write32(Relocs[e - i - 1].Word1);
1094 // Write the symbol table data, if used.
1096 // Write the indirect symbol entries.
1097 for (MCAssembler::const_indirect_symbol_iterator
1098 it = Asm.indirect_symbol_begin(),
1099 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1100 // Indirect symbols in the non lazy symbol pointer section have some
1101 // special handling.
1102 const MCSectionMachO &Section =
1103 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1104 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1105 // If this symbol is defined and internal, mark it as such.
1106 if (it->Symbol->isDefined() &&
1107 !Asm.getSymbolData(*it->Symbol).isExternal()) {
1108 uint32_t Flags = ISF_Local;
1109 if (it->Symbol->isAbsolute())
1110 Flags |= ISF_Absolute;
1116 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1119 // FIXME: Check that offsets match computed ones.
1121 // Write the symbol table entries.
1122 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1123 WriteNlist(LocalSymbolData[i], Layout);
1124 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1125 WriteNlist(ExternalSymbolData[i], Layout);
1126 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1127 WriteNlist(UndefinedSymbolData[i], Layout);
1129 // Write the string table.
1130 OS << StringTable.str();
1137 MachObjectWriter::MachObjectWriter(raw_ostream &OS,
1139 bool IsLittleEndian)
1140 : MCObjectWriter(OS, IsLittleEndian)
1142 Impl = new MachObjectWriterImpl(this, Is64Bit);
1145 MachObjectWriter::~MachObjectWriter() {
1146 delete (MachObjectWriterImpl*) Impl;
1149 void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1150 ((MachObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1153 void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
1154 const MCAsmLayout &Layout,
1155 const MCFragment *Fragment,
1156 const MCAsmFixup &Fixup, MCValue Target,
1157 uint64_t &FixedValue) {
1158 ((MachObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1159 Target, FixedValue);
1162 void MachObjectWriter::WriteObject(const MCAssembler &Asm,
1163 const MCAsmLayout &Layout) {
1164 ((MachObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);