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/MCExpr.h"
15 #include "llvm/MC/MCObjectWriter.h"
16 #include "llvm/MC/MCSectionMachO.h"
17 #include "llvm/MC/MCSymbol.h"
18 #include "llvm/MC/MCValue.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/MachO.h"
21 #include "llvm/Target/TargetAsmBackend.h"
24 #include "../Target/X86/X86FixupKinds.h"
29 static unsigned getFixupKindLog2Size(unsigned Kind) {
31 default: llvm_unreachable("invalid fixup kind!");
32 case X86::reloc_pcrel_1byte:
33 case FK_Data_1: return 0;
34 case FK_Data_2: return 1;
35 case X86::reloc_pcrel_4byte:
36 case X86::reloc_riprel_4byte:
37 case X86::reloc_riprel_4byte_movq_load:
38 case FK_Data_4: return 2;
39 case FK_Data_8: return 3;
43 static bool isFixupKindPCRel(unsigned Kind) {
47 case X86::reloc_pcrel_1byte:
48 case X86::reloc_pcrel_4byte:
49 case X86::reloc_riprel_4byte:
50 case X86::reloc_riprel_4byte_movq_load:
55 static bool isFixupKindRIPRel(unsigned Kind) {
56 return Kind == X86::reloc_riprel_4byte ||
57 Kind == X86::reloc_riprel_4byte_movq_load;
62 class MachObjectWriterImpl {
63 // See <mach-o/loader.h>.
65 Header_Magic32 = 0xFEEDFACE,
66 Header_Magic64 = 0xFEEDFACF
72 SegmentLoadCommand32Size = 56,
73 SegmentLoadCommand64Size = 72,
76 SymtabLoadCommandSize = 24,
77 DysymtabLoadCommandSize = 80,
80 RelocationInfoSize = 8
88 HF_SubsectionsViaSymbols = 0x2000
91 enum LoadCommandType {
98 // See <mach-o/nlist.h>.
100 STT_Undefined = 0x00,
105 enum SymbolTypeFlags {
106 // If any of these bits are set, then the entry is a stab entry number (see
107 // <mach-o/stab.h>. Otherwise the other masks apply.
108 STF_StabsEntryMask = 0xe0,
112 STF_PrivateExtern = 0x10
115 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
117 enum IndirectSymbolFlags {
118 ISF_Local = 0x80000000,
119 ISF_Absolute = 0x40000000
122 /// RelocationFlags - Special flags for addresses.
123 enum RelocationFlags {
124 RF_Scattered = 0x80000000
127 enum RelocationInfoType {
131 RIT_PreboundLazyPointer = 3,
132 RIT_LocalDifference = 4
135 /// X86_64 uses its own relocation types.
136 enum RelocationInfoTypeX86_64 {
137 RIT_X86_64_Unsigned = 0,
138 RIT_X86_64_Signed = 1,
139 RIT_X86_64_Branch = 2,
140 RIT_X86_64_GOTLoad = 3,
142 RIT_X86_64_Subtractor = 5,
143 RIT_X86_64_Signed1 = 6,
144 RIT_X86_64_Signed2 = 7,
145 RIT_X86_64_Signed4 = 8
148 /// MachSymbolData - Helper struct for containing some precomputed information
150 struct MachSymbolData {
151 MCSymbolData *SymbolData;
152 uint64_t StringIndex;
153 uint8_t SectionIndex;
155 // Support lexicographic sorting.
156 bool operator<(const MachSymbolData &RHS) const {
157 const std::string &Name = SymbolData->getSymbol().getName();
158 return Name < RHS.SymbolData->getSymbol().getName();
162 /// @name Relocation Data
165 struct MachRelocationEntry {
170 llvm::DenseMap<const MCSectionData*,
171 std::vector<MachRelocationEntry> > Relocations;
174 /// @name Symbol Table Data
177 SmallString<256> StringTable;
178 std::vector<MachSymbolData> LocalSymbolData;
179 std::vector<MachSymbolData> ExternalSymbolData;
180 std::vector<MachSymbolData> UndefinedSymbolData;
184 MachObjectWriter *Writer;
188 unsigned Is64Bit : 1;
191 MachObjectWriterImpl(MachObjectWriter *_Writer, bool _Is64Bit)
192 : Writer(_Writer), OS(Writer->getStream()), Is64Bit(_Is64Bit) {
195 void Write8(uint8_t Value) { Writer->Write8(Value); }
196 void Write16(uint16_t Value) { Writer->Write16(Value); }
197 void Write32(uint32_t Value) { Writer->Write32(Value); }
198 void Write64(uint64_t Value) { Writer->Write64(Value); }
199 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
200 void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
201 Writer->WriteBytes(Str, ZeroFillSize);
204 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
205 bool SubsectionsViaSymbols) {
208 if (SubsectionsViaSymbols)
209 Flags |= HF_SubsectionsViaSymbols;
211 // struct mach_header (28 bytes) or
212 // struct mach_header_64 (32 bytes)
214 uint64_t Start = OS.tell();
217 Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
219 // FIXME: Support cputype.
220 Write32(Is64Bit ? MachO::CPUTypeX86_64 : MachO::CPUTypeI386);
221 // FIXME: Support cpusubtype.
222 Write32(MachO::CPUSubType_I386_ALL);
224 Write32(NumLoadCommands); // Object files have a single load command, the
226 Write32(LoadCommandsSize);
229 Write32(0); // reserved
231 assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
234 /// WriteSegmentLoadCommand - Write a segment load command.
236 /// \arg NumSections - The number of sections in this segment.
237 /// \arg SectionDataSize - The total size of the sections.
238 void WriteSegmentLoadCommand(unsigned NumSections,
240 uint64_t SectionDataStartOffset,
241 uint64_t SectionDataSize) {
242 // struct segment_command (56 bytes) or
243 // struct segment_command_64 (72 bytes)
245 uint64_t Start = OS.tell();
248 unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
249 SegmentLoadCommand32Size;
250 Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
251 Write32(SegmentLoadCommandSize +
252 NumSections * (Is64Bit ? Section64Size : Section32Size));
256 Write64(0); // vmaddr
257 Write64(VMSize); // vmsize
258 Write64(SectionDataStartOffset); // file offset
259 Write64(SectionDataSize); // file size
261 Write32(0); // vmaddr
262 Write32(VMSize); // vmsize
263 Write32(SectionDataStartOffset); // file offset
264 Write32(SectionDataSize); // file size
266 Write32(0x7); // maxprot
267 Write32(0x7); // initprot
268 Write32(NumSections);
271 assert(OS.tell() - Start == SegmentLoadCommandSize);
274 void WriteSection(const MCAssembler &Asm, const MCSectionData &SD,
275 uint64_t FileOffset, uint64_t RelocationsStart,
276 unsigned NumRelocations) {
277 // The offset is unused for virtual sections.
278 if (Asm.getBackend().isVirtualSection(SD.getSection())) {
279 assert(SD.getFileSize() == 0 && "Invalid file size!");
283 // struct section (68 bytes) or
284 // struct section_64 (80 bytes)
286 uint64_t Start = OS.tell();
289 // FIXME: cast<> support!
290 const MCSectionMachO &Section =
291 static_cast<const MCSectionMachO&>(SD.getSection());
292 WriteBytes(Section.getSectionName(), 16);
293 WriteBytes(Section.getSegmentName(), 16);
295 Write64(SD.getAddress()); // address
296 Write64(SD.getSize()); // size
298 Write32(SD.getAddress()); // address
299 Write32(SD.getSize()); // size
303 unsigned Flags = Section.getTypeAndAttributes();
304 if (SD.hasInstructions())
305 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
307 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
308 Write32(Log2_32(SD.getAlignment()));
309 Write32(NumRelocations ? RelocationsStart : 0);
310 Write32(NumRelocations);
312 Write32(0); // reserved1
313 Write32(Section.getStubSize()); // reserved2
315 Write32(0); // reserved3
317 assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
320 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
321 uint32_t StringTableOffset,
322 uint32_t StringTableSize) {
323 // struct symtab_command (24 bytes)
325 uint64_t Start = OS.tell();
329 Write32(SymtabLoadCommandSize);
330 Write32(SymbolOffset);
332 Write32(StringTableOffset);
333 Write32(StringTableSize);
335 assert(OS.tell() - Start == SymtabLoadCommandSize);
338 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
339 uint32_t NumLocalSymbols,
340 uint32_t FirstExternalSymbol,
341 uint32_t NumExternalSymbols,
342 uint32_t FirstUndefinedSymbol,
343 uint32_t NumUndefinedSymbols,
344 uint32_t IndirectSymbolOffset,
345 uint32_t NumIndirectSymbols) {
346 // struct dysymtab_command (80 bytes)
348 uint64_t Start = OS.tell();
351 Write32(LCT_Dysymtab);
352 Write32(DysymtabLoadCommandSize);
353 Write32(FirstLocalSymbol);
354 Write32(NumLocalSymbols);
355 Write32(FirstExternalSymbol);
356 Write32(NumExternalSymbols);
357 Write32(FirstUndefinedSymbol);
358 Write32(NumUndefinedSymbols);
359 Write32(0); // tocoff
361 Write32(0); // modtaboff
362 Write32(0); // nmodtab
363 Write32(0); // extrefsymoff
364 Write32(0); // nextrefsyms
365 Write32(IndirectSymbolOffset);
366 Write32(NumIndirectSymbols);
367 Write32(0); // extreloff
368 Write32(0); // nextrel
369 Write32(0); // locreloff
370 Write32(0); // nlocrel
372 assert(OS.tell() - Start == DysymtabLoadCommandSize);
375 void WriteNlist(MachSymbolData &MSD) {
376 MCSymbolData &Data = *MSD.SymbolData;
377 const MCSymbol &Symbol = Data.getSymbol();
379 uint16_t Flags = Data.getFlags();
380 uint32_t Address = 0;
382 // Set the N_TYPE bits. See <mach-o/nlist.h>.
384 // FIXME: Are the prebound or indirect fields possible here?
385 if (Symbol.isUndefined())
386 Type = STT_Undefined;
387 else if (Symbol.isAbsolute())
392 // FIXME: Set STAB bits.
394 if (Data.isPrivateExtern())
395 Type |= STF_PrivateExtern;
398 if (Data.isExternal() || Symbol.isUndefined())
399 Type |= STF_External;
401 // Compute the symbol address.
402 if (Symbol.isDefined()) {
403 if (Symbol.isAbsolute()) {
404 llvm_unreachable("FIXME: Not yet implemented!");
406 Address = Data.getAddress();
408 } else if (Data.isCommon()) {
409 // Common symbols are encoded with the size in the address
410 // field, and their alignment in the flags.
411 Address = Data.getCommonSize();
413 // Common alignment is packed into the 'desc' bits.
414 if (unsigned Align = Data.getCommonAlignment()) {
415 unsigned Log2Size = Log2_32(Align);
416 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
418 llvm_report_error("invalid 'common' alignment '" +
420 // FIXME: Keep this mask with the SymbolFlags enumeration.
421 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
425 // struct nlist (12 bytes)
427 Write32(MSD.StringIndex);
429 Write8(MSD.SectionIndex);
431 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
440 void RecordX86_64Relocation(const MCAssembler &Asm,
441 const MCFragment *Fragment,
442 const MCAsmFixup &Fixup, MCValue Target,
443 uint64_t &FixedValue) {
444 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
445 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.Kind);
446 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
449 uint32_t Address = Fragment->getOffset() + Fixup.Offset;
452 unsigned IsExtern = 0;
455 Value = Target.getConstant();
458 // Compensate for the relocation offset, Darwin x86_64 relocations only
459 // have the addend and appear to have attempted to define it to be the
460 // actual expression addend without the PCrel bias. However, instructions
461 // with data following the relocation are not accomodated for (see comment
462 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
463 Value += 1 << Log2Size;
466 if (Target.isAbsolute()) { // constant
467 // SymbolNum of 0 indicates the absolute section.
468 Type = RIT_X86_64_Unsigned;
471 // FIXME: I believe this is broken, I don't think the linker can
472 // understand it. I think it would require a local relocation, but I'm not
473 // sure if that would work either. The official way to get an absolute
474 // PCrel relocation is to use an absolute symbol (which we don't support
478 Type = RIT_X86_64_Branch;
480 } else if (Target.getSymB()) { // A - B + constant
481 const MCSymbol *A = &Target.getSymA()->getSymbol();
482 MCSymbolData &A_SD = Asm.getSymbolData(*A);
483 const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
485 const MCSymbol *B = &Target.getSymB()->getSymbol();
486 MCSymbolData &B_SD = Asm.getSymbolData(*B);
487 const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
489 // Neither symbol can be modified.
490 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
491 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
492 llvm_report_error("unsupported relocation of modified symbol");
494 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
495 // implement most of these correctly.
497 llvm_report_error("unsupported pc-relative relocation of difference");
499 // We don't currently support any situation where one or both of the
500 // symbols would require a local relocation. This is almost certainly
501 // unused and may not be possible to encode correctly.
502 if (!A_Base || !B_Base)
503 llvm_report_error("unsupported local relocations in difference");
505 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
506 // a single SIGNED relocation); reject it for now.
507 if (A_Base == B_Base)
508 llvm_report_error("unsupported relocation with identical base");
510 Value += A_SD.getAddress() - A_Base->getAddress();
511 Value -= B_SD.getAddress() - B_Base->getAddress();
513 Index = A_Base->getIndex();
515 Type = RIT_X86_64_Unsigned;
517 MachRelocationEntry MRE;
519 MRE.Word1 = ((Index << 0) |
524 Relocations[Fragment->getParent()].push_back(MRE);
526 Index = B_Base->getIndex();
528 Type = RIT_X86_64_Subtractor;
530 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
531 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
532 const MCSymbolData *Base = Asm.getAtom(&SD);
534 // x86_64 almost always uses external relocations, except when there is no
535 // symbol to use as a base address (a local symbol with no preceeding
536 // non-local symbol).
538 Index = Base->getIndex();
541 // Add the local offset, if needed.
543 Value += SD.getAddress() - Base->getAddress();
545 // The index is the section ordinal.
549 MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
550 for (; it != ie; ++it, ++Index)
551 if (&*it == SD.getFragment()->getParent())
553 assert(it != ie && "Unable to find section index!");
555 Value += SD.getAddress();
558 Value -= Address + (1 << Log2Size);
561 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
564 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
565 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
566 // rewrite the movq to an leaq at link time if the symbol ends up in
567 // the same linkage unit.
568 if (unsigned(Fixup.Kind) == X86::reloc_riprel_4byte_movq_load)
569 Type = RIT_X86_64_GOTLoad;
571 Type = RIT_X86_64_GOT;
572 } else if (Modifier != MCSymbolRefExpr::VK_None)
573 llvm_report_error("unsupported symbol modifier in relocation");
575 Type = RIT_X86_64_Signed;
577 if (Modifier != MCSymbolRefExpr::VK_None)
578 llvm_report_error("unsupported symbol modifier in branch "
581 Type = RIT_X86_64_Branch;
584 // The Darwin x86_64 relocation format has a problem where it cannot
585 // encode an address (L<foo> + <constant>) which is outside the atom
586 // containing L<foo>. Generally, this shouldn't occur but it does happen
587 // when we have a RIPrel instruction with data following the relocation
588 // entry (e.g., movb $012, L0(%rip)). Even with the PCrel adjustment
589 // Darwin x86_64 uses, the offset is still negative and the linker has
590 // no way to recognize this.
592 // To work around this, Darwin uses several special relocation types to
593 // indicate the offsets. However, the specification or implementation of
594 // these seems to also be incomplete; they should adjust the addend as
595 // well based on the actual encoded instruction (the additional bias),
596 // but instead appear to just look at the final offset.
598 switch (-(Target.getConstant() + (1 << Log2Size))) {
599 case 1: Type = RIT_X86_64_Signed1; break;
600 case 2: Type = RIT_X86_64_Signed2; break;
601 case 4: Type = RIT_X86_64_Signed4; break;
605 if (Modifier == MCSymbolRefExpr::VK_GOT)
606 Type = RIT_X86_64_GOT;
607 else if (Modifier != MCSymbolRefExpr::VK_None)
608 llvm_report_error("unsupported symbol modifier in relocation");
610 Type = RIT_X86_64_Unsigned;
614 // x86_64 always writes custom values into the fixups.
617 // struct relocation_info (8 bytes)
618 MachRelocationEntry MRE;
620 MRE.Word1 = ((Index << 0) |
625 Relocations[Fragment->getParent()].push_back(MRE);
628 void RecordScatteredRelocation(const MCAssembler &Asm,
629 const MCFragment *Fragment,
630 const MCAsmFixup &Fixup, MCValue Target,
631 uint64_t &FixedValue) {
632 uint32_t Address = Fragment->getOffset() + Fixup.Offset;
633 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
634 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
635 unsigned Type = RIT_Vanilla;
638 const MCSymbol *A = &Target.getSymA()->getSymbol();
639 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
641 if (!A_SD->getFragment())
642 llvm_report_error("symbol '" + A->getName() +
643 "' can not be undefined in a subtraction expression");
645 uint32_t Value = A_SD->getAddress();
648 if (const MCSymbolRefExpr *B = Target.getSymB()) {
649 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
651 if (!B_SD->getFragment())
652 llvm_report_error("symbol '" + B->getSymbol().getName() +
653 "' can not be undefined in a subtraction expression");
655 // Select the appropriate difference relocation type.
657 // Note that there is no longer any semantic difference between these two
658 // relocation types from the linkers point of view, this is done solely
659 // for pedantic compatibility with 'as'.
660 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
661 Value2 = B_SD->getAddress();
664 // Relocations are written out in reverse order, so the PAIR comes first.
665 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
666 MachRelocationEntry MRE;
667 MRE.Word0 = ((0 << 0) |
673 Relocations[Fragment->getParent()].push_back(MRE);
676 MachRelocationEntry MRE;
677 MRE.Word0 = ((Address << 0) |
683 Relocations[Fragment->getParent()].push_back(MRE);
686 void RecordRelocation(const MCAssembler &Asm, const MCFragment *Fragment,
687 const MCAsmFixup &Fixup, MCValue Target,
688 uint64_t &FixedValue) {
690 RecordX86_64Relocation(Asm, Fragment, Fixup, Target, FixedValue);
694 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
695 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
697 // If this is a difference or a defined symbol plus an offset, then we need
698 // a scattered relocation entry.
699 uint32_t Offset = Target.getConstant();
701 Offset += 1 << Log2Size;
702 if (Target.getSymB() ||
703 (Target.getSymA() && !Target.getSymA()->getSymbol().isUndefined() &&
705 RecordScatteredRelocation(Asm, Fragment, Fixup, Target, FixedValue);
710 uint32_t Address = Fragment->getOffset() + Fixup.Offset;
713 unsigned IsExtern = 0;
716 if (Target.isAbsolute()) { // constant
717 // SymbolNum of 0 indicates the absolute section.
719 // FIXME: Currently, these are never generated (see code below). I cannot
720 // find a case where they are actually emitted.
724 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
725 MCSymbolData *SD = &Asm.getSymbolData(*Symbol);
727 if (Symbol->isUndefined()) {
729 Index = SD->getIndex();
732 // The index is the section ordinal.
736 MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
737 for (; it != ie; ++it, ++Index)
738 if (&*it == SD->getFragment()->getParent())
740 assert(it != ie && "Unable to find section index!");
741 Value = SD->getAddress();
747 // struct relocation_info (8 bytes)
748 MachRelocationEntry MRE;
750 MRE.Word1 = ((Index << 0) |
755 Relocations[Fragment->getParent()].push_back(MRE);
758 void BindIndirectSymbols(MCAssembler &Asm) {
759 // This is the point where 'as' creates actual symbols for indirect symbols
760 // (in the following two passes). It would be easier for us to do this
761 // sooner when we see the attribute, but that makes getting the order in the
762 // symbol table much more complicated than it is worth.
764 // FIXME: Revisit this when the dust settles.
766 // Bind non lazy symbol pointers first.
767 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
768 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
769 // FIXME: cast<> support!
770 const MCSectionMachO &Section =
771 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
773 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
776 Asm.getOrCreateSymbolData(*it->Symbol);
779 // Then lazy symbol pointers and symbol stubs.
780 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
781 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
782 // FIXME: cast<> support!
783 const MCSectionMachO &Section =
784 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
786 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
787 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
790 // Set the symbol type to undefined lazy, but only on construction.
792 // FIXME: Do not hardcode.
794 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
796 Entry.setFlags(Entry.getFlags() | 0x0001);
800 /// ComputeSymbolTable - Compute the symbol table data
802 /// \param StringTable [out] - The string table data.
803 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
805 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
806 std::vector<MachSymbolData> &LocalSymbolData,
807 std::vector<MachSymbolData> &ExternalSymbolData,
808 std::vector<MachSymbolData> &UndefinedSymbolData) {
809 // Build section lookup table.
810 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
812 for (MCAssembler::iterator it = Asm.begin(),
813 ie = Asm.end(); it != ie; ++it, ++Index)
814 SectionIndexMap[&it->getSection()] = Index;
815 assert(Index <= 256 && "Too many sections!");
817 // Index 0 is always the empty string.
818 StringMap<uint64_t> StringIndexMap;
819 StringTable += '\x00';
821 // Build the symbol arrays and the string table, but only for non-local
824 // The particular order that we collect the symbols and create the string
825 // table, then sort the symbols is chosen to match 'as'. Even though it
826 // doesn't matter for correctness, this is important for letting us diff .o
828 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
829 ie = Asm.symbol_end(); it != ie; ++it) {
830 const MCSymbol &Symbol = it->getSymbol();
832 // Ignore non-linker visible symbols.
833 if (!Asm.isSymbolLinkerVisible(it))
836 if (!it->isExternal() && !Symbol.isUndefined())
839 uint64_t &Entry = StringIndexMap[Symbol.getName()];
841 Entry = StringTable.size();
842 StringTable += Symbol.getName();
843 StringTable += '\x00';
848 MSD.StringIndex = Entry;
850 if (Symbol.isUndefined()) {
851 MSD.SectionIndex = 0;
852 UndefinedSymbolData.push_back(MSD);
853 } else if (Symbol.isAbsolute()) {
854 MSD.SectionIndex = 0;
855 ExternalSymbolData.push_back(MSD);
857 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
858 assert(MSD.SectionIndex && "Invalid section index!");
859 ExternalSymbolData.push_back(MSD);
863 // Now add the data for local symbols.
864 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
865 ie = Asm.symbol_end(); it != ie; ++it) {
866 const MCSymbol &Symbol = it->getSymbol();
868 // Ignore non-linker visible symbols.
869 if (!Asm.isSymbolLinkerVisible(it))
872 if (it->isExternal() || Symbol.isUndefined())
875 uint64_t &Entry = StringIndexMap[Symbol.getName()];
877 Entry = StringTable.size();
878 StringTable += Symbol.getName();
879 StringTable += '\x00';
884 MSD.StringIndex = Entry;
886 if (Symbol.isAbsolute()) {
887 MSD.SectionIndex = 0;
888 LocalSymbolData.push_back(MSD);
890 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
891 assert(MSD.SectionIndex && "Invalid section index!");
892 LocalSymbolData.push_back(MSD);
896 // External and undefined symbols are required to be in lexicographic order.
897 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
898 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
900 // Set the symbol indices.
902 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
903 LocalSymbolData[i].SymbolData->setIndex(Index++);
904 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
905 ExternalSymbolData[i].SymbolData->setIndex(Index++);
906 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
907 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
909 // The string table is padded to a multiple of 4.
910 while (StringTable.size() % 4)
911 StringTable += '\x00';
914 void ExecutePostLayoutBinding(MCAssembler &Asm) {
915 // Create symbol data for any indirect symbols.
916 BindIndirectSymbols(Asm);
918 // Compute symbol table information and bind symbol indices.
919 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
920 UndefinedSymbolData);
923 void WriteObject(const MCAssembler &Asm) {
924 unsigned NumSections = Asm.size();
926 // The section data starts after the header, the segment load command (and
927 // section headers) and the symbol table.
928 unsigned NumLoadCommands = 1;
929 uint64_t LoadCommandsSize = Is64Bit ?
930 SegmentLoadCommand64Size + NumSections * Section64Size :
931 SegmentLoadCommand32Size + NumSections * Section32Size;
933 // Add the symbol table load command sizes, if used.
934 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
935 UndefinedSymbolData.size();
937 NumLoadCommands += 2;
938 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
941 // Compute the total size of the section data, as well as its file size and
943 uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
945 uint64_t SectionDataSize = 0;
946 uint64_t SectionDataFileSize = 0;
948 for (MCAssembler::const_iterator it = Asm.begin(),
949 ie = Asm.end(); it != ie; ++it) {
950 const MCSectionData &SD = *it;
952 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
954 if (Asm.getBackend().isVirtualSection(SD.getSection()))
957 SectionDataSize = std::max(SectionDataSize,
958 SD.getAddress() + SD.getSize());
959 SectionDataFileSize = std::max(SectionDataFileSize,
960 SD.getAddress() + SD.getFileSize());
963 // The section data is padded to 4 bytes.
965 // FIXME: Is this machine dependent?
966 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
967 SectionDataFileSize += SectionDataPadding;
969 // Write the prolog, starting with the header and load command...
970 WriteHeader(NumLoadCommands, LoadCommandsSize,
971 Asm.getSubsectionsViaSymbols());
972 WriteSegmentLoadCommand(NumSections, VMSize,
973 SectionDataStart, SectionDataSize);
975 // ... and then the section headers.
976 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
977 for (MCAssembler::const_iterator it = Asm.begin(),
978 ie = Asm.end(); it != ie; ++it) {
979 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
980 unsigned NumRelocs = Relocs.size();
981 uint64_t SectionStart = SectionDataStart + it->getAddress();
982 WriteSection(Asm, *it, SectionStart, RelocTableEnd, NumRelocs);
983 RelocTableEnd += NumRelocs * RelocationInfoSize;
986 // Write the symbol table load command, if used.
988 unsigned FirstLocalSymbol = 0;
989 unsigned NumLocalSymbols = LocalSymbolData.size();
990 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
991 unsigned NumExternalSymbols = ExternalSymbolData.size();
992 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
993 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
994 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
995 unsigned NumSymTabSymbols =
996 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
997 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
998 uint64_t IndirectSymbolOffset = 0;
1000 // If used, the indirect symbols are written after the section data.
1001 if (NumIndirectSymbols)
1002 IndirectSymbolOffset = RelocTableEnd;
1004 // The symbol table is written after the indirect symbol data.
1005 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1007 // The string table is written after symbol table.
1008 uint64_t StringTableOffset =
1009 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
1011 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1012 StringTableOffset, StringTable.size());
1014 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1015 FirstExternalSymbol, NumExternalSymbols,
1016 FirstUndefinedSymbol, NumUndefinedSymbols,
1017 IndirectSymbolOffset, NumIndirectSymbols);
1020 // Write the actual section data.
1021 for (MCAssembler::const_iterator it = Asm.begin(),
1022 ie = Asm.end(); it != ie; ++it)
1023 Asm.WriteSectionData(it, Writer);
1025 // Write the extra padding.
1026 WriteZeros(SectionDataPadding);
1028 // Write the relocation entries.
1029 for (MCAssembler::const_iterator it = Asm.begin(),
1030 ie = Asm.end(); it != ie; ++it) {
1031 // Write the section relocation entries, in reverse order to match 'as'
1032 // (approximately, the exact algorithm is more complicated than this).
1033 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1034 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1035 Write32(Relocs[e - i - 1].Word0);
1036 Write32(Relocs[e - i - 1].Word1);
1040 // Write the symbol table data, if used.
1042 // Write the indirect symbol entries.
1043 for (MCAssembler::const_indirect_symbol_iterator
1044 it = Asm.indirect_symbol_begin(),
1045 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1046 // Indirect symbols in the non lazy symbol pointer section have some
1047 // special handling.
1048 const MCSectionMachO &Section =
1049 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1050 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1051 // If this symbol is defined and internal, mark it as such.
1052 if (it->Symbol->isDefined() &&
1053 !Asm.getSymbolData(*it->Symbol).isExternal()) {
1054 uint32_t Flags = ISF_Local;
1055 if (it->Symbol->isAbsolute())
1056 Flags |= ISF_Absolute;
1062 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1065 // FIXME: Check that offsets match computed ones.
1067 // Write the symbol table entries.
1068 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1069 WriteNlist(LocalSymbolData[i]);
1070 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1071 WriteNlist(ExternalSymbolData[i]);
1072 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1073 WriteNlist(UndefinedSymbolData[i]);
1075 // Write the string table.
1076 OS << StringTable.str();
1083 MachObjectWriter::MachObjectWriter(raw_ostream &OS,
1085 bool IsLittleEndian)
1086 : MCObjectWriter(OS, IsLittleEndian)
1088 Impl = new MachObjectWriterImpl(this, Is64Bit);
1091 MachObjectWriter::~MachObjectWriter() {
1092 delete (MachObjectWriterImpl*) Impl;
1095 void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1096 ((MachObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1099 void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
1100 const MCFragment *Fragment,
1101 const MCAsmFixup &Fixup, MCValue Target,
1102 uint64_t &FixedValue) {
1103 ((MachObjectWriterImpl*) Impl)->RecordRelocation(Asm, Fragment, Fixup,
1104 Target, FixedValue);
1107 void MachObjectWriter::WriteObject(const MCAssembler &Asm) {
1108 ((MachObjectWriterImpl*) Impl)->WriteObject(Asm);