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 virtual ~MachObjectWriterImpl() {}
197 void Write8(uint8_t Value) { Writer->Write8(Value); }
198 void Write16(uint16_t Value) { Writer->Write16(Value); }
199 void Write32(uint32_t Value) { Writer->Write32(Value); }
200 void Write64(uint64_t Value) { Writer->Write64(Value); }
201 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
202 void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
203 Writer->WriteBytes(Str, ZeroFillSize);
206 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
207 bool SubsectionsViaSymbols) {
210 if (SubsectionsViaSymbols)
211 Flags |= HF_SubsectionsViaSymbols;
213 // struct mach_header (28 bytes) or
214 // struct mach_header_64 (32 bytes)
216 uint64_t Start = OS.tell();
219 Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
221 // FIXME: Support cputype.
222 Write32(Is64Bit ? MachO::CPUTypeX86_64 : MachO::CPUTypeI386);
223 // FIXME: Support cpusubtype.
224 Write32(MachO::CPUSubType_I386_ALL);
226 Write32(NumLoadCommands); // Object files have a single load command, the
228 Write32(LoadCommandsSize);
231 Write32(0); // reserved
233 assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
236 /// WriteSegmentLoadCommand - Write a segment load command.
238 /// \arg NumSections - The number of sections in this segment.
239 /// \arg SectionDataSize - The total size of the sections.
240 void WriteSegmentLoadCommand(unsigned NumSections,
242 uint64_t SectionDataStartOffset,
243 uint64_t SectionDataSize) {
244 // struct segment_command (56 bytes) or
245 // struct segment_command_64 (72 bytes)
247 uint64_t Start = OS.tell();
250 unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
251 SegmentLoadCommand32Size;
252 Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
253 Write32(SegmentLoadCommandSize +
254 NumSections * (Is64Bit ? Section64Size : Section32Size));
258 Write64(0); // vmaddr
259 Write64(VMSize); // vmsize
260 Write64(SectionDataStartOffset); // file offset
261 Write64(SectionDataSize); // file size
263 Write32(0); // vmaddr
264 Write32(VMSize); // vmsize
265 Write32(SectionDataStartOffset); // file offset
266 Write32(SectionDataSize); // file size
268 Write32(0x7); // maxprot
269 Write32(0x7); // initprot
270 Write32(NumSections);
273 assert(OS.tell() - Start == SegmentLoadCommandSize);
276 void WriteSection(const MCAssembler &Asm, const MCSectionData &SD,
277 uint64_t FileOffset, uint64_t RelocationsStart,
278 unsigned NumRelocations) {
279 // The offset is unused for virtual sections.
280 if (Asm.getBackend().isVirtualSection(SD.getSection())) {
281 assert(SD.getFileSize() == 0 && "Invalid file size!");
285 // struct section (68 bytes) or
286 // struct section_64 (80 bytes)
288 uint64_t Start = OS.tell();
291 // FIXME: cast<> support!
292 const MCSectionMachO &Section =
293 static_cast<const MCSectionMachO&>(SD.getSection());
294 WriteBytes(Section.getSectionName(), 16);
295 WriteBytes(Section.getSegmentName(), 16);
297 Write64(SD.getAddress()); // address
298 Write64(SD.getSize()); // size
300 Write32(SD.getAddress()); // address
301 Write32(SD.getSize()); // size
305 unsigned Flags = Section.getTypeAndAttributes();
306 if (SD.hasInstructions())
307 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
309 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
310 Write32(Log2_32(SD.getAlignment()));
311 Write32(NumRelocations ? RelocationsStart : 0);
312 Write32(NumRelocations);
314 Write32(0); // reserved1
315 Write32(Section.getStubSize()); // reserved2
317 Write32(0); // reserved3
319 assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
322 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
323 uint32_t StringTableOffset,
324 uint32_t StringTableSize) {
325 // struct symtab_command (24 bytes)
327 uint64_t Start = OS.tell();
331 Write32(SymtabLoadCommandSize);
332 Write32(SymbolOffset);
334 Write32(StringTableOffset);
335 Write32(StringTableSize);
337 assert(OS.tell() - Start == SymtabLoadCommandSize);
340 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
341 uint32_t NumLocalSymbols,
342 uint32_t FirstExternalSymbol,
343 uint32_t NumExternalSymbols,
344 uint32_t FirstUndefinedSymbol,
345 uint32_t NumUndefinedSymbols,
346 uint32_t IndirectSymbolOffset,
347 uint32_t NumIndirectSymbols) {
348 // struct dysymtab_command (80 bytes)
350 uint64_t Start = OS.tell();
353 Write32(LCT_Dysymtab);
354 Write32(DysymtabLoadCommandSize);
355 Write32(FirstLocalSymbol);
356 Write32(NumLocalSymbols);
357 Write32(FirstExternalSymbol);
358 Write32(NumExternalSymbols);
359 Write32(FirstUndefinedSymbol);
360 Write32(NumUndefinedSymbols);
361 Write32(0); // tocoff
363 Write32(0); // modtaboff
364 Write32(0); // nmodtab
365 Write32(0); // extrefsymoff
366 Write32(0); // nextrefsyms
367 Write32(IndirectSymbolOffset);
368 Write32(NumIndirectSymbols);
369 Write32(0); // extreloff
370 Write32(0); // nextrel
371 Write32(0); // locreloff
372 Write32(0); // nlocrel
374 assert(OS.tell() - Start == DysymtabLoadCommandSize);
377 void WriteNlist(MachSymbolData &MSD) {
378 MCSymbolData &Data = *MSD.SymbolData;
379 const MCSymbol &Symbol = Data.getSymbol();
381 uint16_t Flags = Data.getFlags();
382 uint32_t Address = 0;
384 // Set the N_TYPE bits. See <mach-o/nlist.h>.
386 // FIXME: Are the prebound or indirect fields possible here?
387 if (Symbol.isUndefined())
388 Type = STT_Undefined;
389 else if (Symbol.isAbsolute())
394 // FIXME: Set STAB bits.
396 if (Data.isPrivateExtern())
397 Type |= STF_PrivateExtern;
400 if (Data.isExternal() || Symbol.isUndefined())
401 Type |= STF_External;
403 // Compute the symbol address.
404 if (Symbol.isDefined()) {
405 if (Symbol.isAbsolute()) {
406 llvm_unreachable("FIXME: Not yet implemented!");
408 Address = Data.getAddress();
410 } else if (Data.isCommon()) {
411 // Common symbols are encoded with the size in the address
412 // field, and their alignment in the flags.
413 Address = Data.getCommonSize();
415 // Common alignment is packed into the 'desc' bits.
416 if (unsigned Align = Data.getCommonAlignment()) {
417 unsigned Log2Size = Log2_32(Align);
418 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
420 llvm_report_error("invalid 'common' alignment '" +
422 // FIXME: Keep this mask with the SymbolFlags enumeration.
423 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
427 // struct nlist (12 bytes)
429 Write32(MSD.StringIndex);
431 Write8(MSD.SectionIndex);
433 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
442 void RecordX86_64Relocation(const MCAssembler &Asm,
443 const MCDataFragment &Fragment,
444 const MCAsmFixup &Fixup, MCValue Target,
445 uint64_t &FixedValue) {
446 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
447 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.Kind);
448 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
451 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
454 unsigned IsExtern = 0;
457 Value = Target.getConstant();
460 // Compensate for the relocation offset, Darwin x86_64 relocations only
461 // have the addend and appear to have attempted to define it to be the
462 // actual expression addend without the PCrel bias. However, instructions
463 // with data following the relocation are not accomodated for (see comment
464 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
465 Value += 1 << Log2Size;
468 if (Target.isAbsolute()) { // constant
469 // SymbolNum of 0 indicates the absolute section.
470 Type = RIT_X86_64_Unsigned;
473 // FIXME: I believe this is broken, I don't think the linker can
474 // understand it. I think it would require a local relocation, but I'm not
475 // sure if that would work either. The official way to get an absolute
476 // PCrel relocation is to use an absolute symbol (which we don't support
480 Type = RIT_X86_64_Branch;
482 } else if (Target.getSymB()) { // A - B + constant
483 const MCSymbol *A = &Target.getSymA()->getSymbol();
484 MCSymbolData &A_SD = Asm.getSymbolData(*A);
485 const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
487 const MCSymbol *B = &Target.getSymB()->getSymbol();
488 MCSymbolData &B_SD = Asm.getSymbolData(*B);
489 const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
491 // Neither symbol can be modified.
492 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
493 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
494 llvm_report_error("unsupported relocation of modified symbol");
496 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
497 // implement most of these correctly.
499 llvm_report_error("unsupported pc-relative relocation of difference");
501 // We don't currently support any situation where one or both of the
502 // symbols would require a local relocation. This is almost certainly
503 // unused and may not be possible to encode correctly.
504 if (!A_Base || !B_Base)
505 llvm_report_error("unsupported local relocations in difference");
507 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
508 // a single SIGNED relocation); reject it for now.
509 if (A_Base == B_Base)
510 llvm_report_error("unsupported relocation with identical base");
512 Value += A_SD.getAddress() - A_Base->getAddress();
513 Value -= B_SD.getAddress() - B_Base->getAddress();
515 Index = A_Base->getIndex();
517 Type = RIT_X86_64_Unsigned;
519 MachRelocationEntry MRE;
521 MRE.Word1 = ((Index << 0) |
526 Relocations[Fragment.getParent()].push_back(MRE);
528 Index = B_Base->getIndex();
530 Type = RIT_X86_64_Subtractor;
532 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
533 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
534 const MCSymbolData *Base = Asm.getAtom(&SD);
536 // x86_64 almost always uses external relocations, except when there is no
537 // symbol to use as a base address (a local symbol with no preceeding
538 // non-local symbol).
540 Index = Base->getIndex();
543 // Add the local offset, if needed.
545 Value += SD.getAddress() - Base->getAddress();
547 // The index is the section ordinal.
551 MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
552 for (; it != ie; ++it, ++Index)
553 if (&*it == SD.getFragment()->getParent())
555 assert(it != ie && "Unable to find section index!");
557 Value += SD.getAddress();
560 Value -= Address + (1 << Log2Size);
563 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
566 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
567 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
568 // rewrite the movq to an leaq at link time if the symbol ends up in
569 // the same linkage unit.
570 if (unsigned(Fixup.Kind) == X86::reloc_riprel_4byte_movq_load)
571 Type = RIT_X86_64_GOTLoad;
573 Type = RIT_X86_64_GOT;
574 } else if (Modifier != MCSymbolRefExpr::VK_None)
575 llvm_report_error("unsupported symbol modifier in relocation");
577 Type = RIT_X86_64_Signed;
579 if (Modifier != MCSymbolRefExpr::VK_None)
580 llvm_report_error("unsupported symbol modifier in branch "
583 Type = RIT_X86_64_Branch;
586 // The Darwin x86_64 relocation format has a problem where it cannot
587 // encode an address (L<foo> + <constant>) which is outside the atom
588 // containing L<foo>. Generally, this shouldn't occur but it does happen
589 // when we have a RIPrel instruction with data following the relocation
590 // entry (e.g., movb $012, L0(%rip)). Even with the PCrel adjustment
591 // Darwin x86_64 uses, the offset is still negative and the linker has
592 // no way to recognize this.
594 // To work around this, Darwin uses several special relocation types to
595 // indicate the offsets. However, the specification or implementation of
596 // these seems to also be incomplete; they should adjust the addend as
597 // well based on the actual encoded instruction (the additional bias),
598 // but instead appear to just look at the final offset.
600 switch (-(Target.getConstant() + (1 << Log2Size))) {
601 case 1: Type = RIT_X86_64_Signed1; break;
602 case 2: Type = RIT_X86_64_Signed2; break;
603 case 4: Type = RIT_X86_64_Signed4; break;
607 if (Modifier == MCSymbolRefExpr::VK_GOT)
608 Type = RIT_X86_64_GOT;
609 else if (Modifier != MCSymbolRefExpr::VK_None)
610 llvm_report_error("unsupported symbol modifier in relocation");
612 Type = RIT_X86_64_Unsigned;
616 // x86_64 always writes custom values into the fixups.
619 // struct relocation_info (8 bytes)
620 MachRelocationEntry MRE;
622 MRE.Word1 = ((Index << 0) |
627 Relocations[Fragment.getParent()].push_back(MRE);
630 void RecordScatteredRelocation(const MCAssembler &Asm,
631 const MCFragment &Fragment,
632 const MCAsmFixup &Fixup, MCValue Target,
633 uint64_t &FixedValue) {
634 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
635 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
636 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
637 unsigned Type = RIT_Vanilla;
640 const MCSymbol *A = &Target.getSymA()->getSymbol();
641 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
643 if (!A_SD->getFragment())
644 llvm_report_error("symbol '" + A->getName() +
645 "' can not be undefined in a subtraction expression");
647 uint32_t Value = A_SD->getAddress();
650 if (const MCSymbolRefExpr *B = Target.getSymB()) {
651 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
653 if (!B_SD->getFragment())
654 llvm_report_error("symbol '" + B->getSymbol().getName() +
655 "' can not be undefined in a subtraction expression");
657 // Select the appropriate difference relocation type.
659 // Note that there is no longer any semantic difference between these two
660 // relocation types from the linkers point of view, this is done solely
661 // for pedantic compatibility with 'as'.
662 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
663 Value2 = B_SD->getAddress();
666 // Relocations are written out in reverse order, so the PAIR comes first.
667 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
668 MachRelocationEntry MRE;
669 MRE.Word0 = ((0 << 0) |
675 Relocations[Fragment.getParent()].push_back(MRE);
678 MachRelocationEntry MRE;
679 MRE.Word0 = ((Address << 0) |
685 Relocations[Fragment.getParent()].push_back(MRE);
688 virtual void RecordRelocation(const MCAssembler &Asm,
689 const MCDataFragment &Fragment,
690 const MCAsmFixup &Fixup, MCValue Target,
691 uint64_t &FixedValue) {
693 RecordX86_64Relocation(Asm, Fragment, Fixup, Target, FixedValue);
697 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
698 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
700 // If this is a difference or a defined symbol plus an offset, then we need
701 // a scattered relocation entry.
702 uint32_t Offset = Target.getConstant();
704 Offset += 1 << Log2Size;
705 if (Target.getSymB() ||
706 (Target.getSymA() && !Target.getSymA()->getSymbol().isUndefined() &&
708 RecordScatteredRelocation(Asm, Fragment, Fixup, Target, FixedValue);
713 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
716 unsigned IsExtern = 0;
719 if (Target.isAbsolute()) { // constant
720 // SymbolNum of 0 indicates the absolute section.
722 // FIXME: Currently, these are never generated (see code below). I cannot
723 // find a case where they are actually emitted.
727 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
728 MCSymbolData *SD = &Asm.getSymbolData(*Symbol);
730 if (Symbol->isUndefined()) {
732 Index = SD->getIndex();
735 // The index is the section ordinal.
739 MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
740 for (; it != ie; ++it, ++Index)
741 if (&*it == SD->getFragment()->getParent())
743 assert(it != ie && "Unable to find section index!");
744 Value = SD->getAddress();
750 // struct relocation_info (8 bytes)
751 MachRelocationEntry MRE;
753 MRE.Word1 = ((Index << 0) |
758 Relocations[Fragment.getParent()].push_back(MRE);
761 void BindIndirectSymbols(MCAssembler &Asm) {
762 // This is the point where 'as' creates actual symbols for indirect symbols
763 // (in the following two passes). It would be easier for us to do this
764 // sooner when we see the attribute, but that makes getting the order in the
765 // symbol table much more complicated than it is worth.
767 // FIXME: Revisit this when the dust settles.
769 // Bind non lazy symbol pointers first.
770 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
771 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
772 // FIXME: cast<> support!
773 const MCSectionMachO &Section =
774 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
776 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
779 Asm.getOrCreateSymbolData(*it->Symbol);
782 // Then lazy symbol pointers and symbol stubs.
783 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
784 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
785 // FIXME: cast<> support!
786 const MCSectionMachO &Section =
787 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
789 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
790 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
793 // Set the symbol type to undefined lazy, but only on construction.
795 // FIXME: Do not hardcode.
797 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
799 Entry.setFlags(Entry.getFlags() | 0x0001);
803 /// ComputeSymbolTable - Compute the symbol table data
805 /// \param StringTable [out] - The string table data.
806 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
808 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
809 std::vector<MachSymbolData> &LocalSymbolData,
810 std::vector<MachSymbolData> &ExternalSymbolData,
811 std::vector<MachSymbolData> &UndefinedSymbolData) {
812 // Build section lookup table.
813 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
815 for (MCAssembler::iterator it = Asm.begin(),
816 ie = Asm.end(); it != ie; ++it, ++Index)
817 SectionIndexMap[&it->getSection()] = Index;
818 assert(Index <= 256 && "Too many sections!");
820 // Index 0 is always the empty string.
821 StringMap<uint64_t> StringIndexMap;
822 StringTable += '\x00';
824 // Build the symbol arrays and the string table, but only for non-local
827 // The particular order that we collect the symbols and create the string
828 // table, then sort the symbols is chosen to match 'as'. Even though it
829 // doesn't matter for correctness, this is important for letting us diff .o
831 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
832 ie = Asm.symbol_end(); it != ie; ++it) {
833 const MCSymbol &Symbol = it->getSymbol();
835 // Ignore non-linker visible symbols.
836 if (!Asm.isSymbolLinkerVisible(it))
839 if (!it->isExternal() && !Symbol.isUndefined())
842 uint64_t &Entry = StringIndexMap[Symbol.getName()];
844 Entry = StringTable.size();
845 StringTable += Symbol.getName();
846 StringTable += '\x00';
851 MSD.StringIndex = Entry;
853 if (Symbol.isUndefined()) {
854 MSD.SectionIndex = 0;
855 UndefinedSymbolData.push_back(MSD);
856 } else if (Symbol.isAbsolute()) {
857 MSD.SectionIndex = 0;
858 ExternalSymbolData.push_back(MSD);
860 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
861 assert(MSD.SectionIndex && "Invalid section index!");
862 ExternalSymbolData.push_back(MSD);
866 // Now add the data for local symbols.
867 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
868 ie = Asm.symbol_end(); it != ie; ++it) {
869 const MCSymbol &Symbol = it->getSymbol();
871 // Ignore non-linker visible symbols.
872 if (!Asm.isSymbolLinkerVisible(it))
875 if (it->isExternal() || Symbol.isUndefined())
878 uint64_t &Entry = StringIndexMap[Symbol.getName()];
880 Entry = StringTable.size();
881 StringTable += Symbol.getName();
882 StringTable += '\x00';
887 MSD.StringIndex = Entry;
889 if (Symbol.isAbsolute()) {
890 MSD.SectionIndex = 0;
891 LocalSymbolData.push_back(MSD);
893 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
894 assert(MSD.SectionIndex && "Invalid section index!");
895 LocalSymbolData.push_back(MSD);
899 // External and undefined symbols are required to be in lexicographic order.
900 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
901 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
903 // Set the symbol indices.
905 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
906 LocalSymbolData[i].SymbolData->setIndex(Index++);
907 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
908 ExternalSymbolData[i].SymbolData->setIndex(Index++);
909 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
910 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
912 // The string table is padded to a multiple of 4.
913 while (StringTable.size() % 4)
914 StringTable += '\x00';
917 virtual void ExecutePostLayoutBinding(MCAssembler &Asm) {
918 // Create symbol data for any indirect symbols.
919 BindIndirectSymbols(Asm);
921 // Compute symbol table information and bind symbol indices.
922 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
923 UndefinedSymbolData);
926 virtual void WriteObject(const MCAssembler &Asm) {
927 unsigned NumSections = Asm.size();
929 // The section data starts after the header, the segment load command (and
930 // section headers) and the symbol table.
931 unsigned NumLoadCommands = 1;
932 uint64_t LoadCommandsSize = Is64Bit ?
933 SegmentLoadCommand64Size + NumSections * Section64Size :
934 SegmentLoadCommand32Size + NumSections * Section32Size;
936 // Add the symbol table load command sizes, if used.
937 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
938 UndefinedSymbolData.size();
940 NumLoadCommands += 2;
941 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
944 // Compute the total size of the section data, as well as its file size and
946 uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
948 uint64_t SectionDataSize = 0;
949 uint64_t SectionDataFileSize = 0;
951 for (MCAssembler::const_iterator it = Asm.begin(),
952 ie = Asm.end(); it != ie; ++it) {
953 const MCSectionData &SD = *it;
955 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
957 if (Asm.getBackend().isVirtualSection(SD.getSection()))
960 SectionDataSize = std::max(SectionDataSize,
961 SD.getAddress() + SD.getSize());
962 SectionDataFileSize = std::max(SectionDataFileSize,
963 SD.getAddress() + SD.getFileSize());
966 // The section data is padded to 4 bytes.
968 // FIXME: Is this machine dependent?
969 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
970 SectionDataFileSize += SectionDataPadding;
972 // Write the prolog, starting with the header and load command...
973 WriteHeader(NumLoadCommands, LoadCommandsSize,
974 Asm.getSubsectionsViaSymbols());
975 WriteSegmentLoadCommand(NumSections, VMSize,
976 SectionDataStart, SectionDataSize);
978 // ... and then the section headers.
979 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
980 for (MCAssembler::const_iterator it = Asm.begin(),
981 ie = Asm.end(); it != ie; ++it) {
982 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
983 unsigned NumRelocs = Relocs.size();
984 uint64_t SectionStart = SectionDataStart + it->getAddress();
985 WriteSection(Asm, *it, SectionStart, RelocTableEnd, NumRelocs);
986 RelocTableEnd += NumRelocs * RelocationInfoSize;
989 // Write the symbol table load command, if used.
991 unsigned FirstLocalSymbol = 0;
992 unsigned NumLocalSymbols = LocalSymbolData.size();
993 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
994 unsigned NumExternalSymbols = ExternalSymbolData.size();
995 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
996 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
997 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
998 unsigned NumSymTabSymbols =
999 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1000 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1001 uint64_t IndirectSymbolOffset = 0;
1003 // If used, the indirect symbols are written after the section data.
1004 if (NumIndirectSymbols)
1005 IndirectSymbolOffset = RelocTableEnd;
1007 // The symbol table is written after the indirect symbol data.
1008 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1010 // The string table is written after symbol table.
1011 uint64_t StringTableOffset =
1012 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
1014 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1015 StringTableOffset, StringTable.size());
1017 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1018 FirstExternalSymbol, NumExternalSymbols,
1019 FirstUndefinedSymbol, NumUndefinedSymbols,
1020 IndirectSymbolOffset, NumIndirectSymbols);
1023 // Write the actual section data.
1024 for (MCAssembler::const_iterator it = Asm.begin(),
1025 ie = Asm.end(); it != ie; ++it)
1026 Asm.WriteSectionData(it, Writer);
1028 // Write the extra padding.
1029 WriteZeros(SectionDataPadding);
1031 // Write the relocation entries.
1032 for (MCAssembler::const_iterator it = Asm.begin(),
1033 ie = Asm.end(); it != ie; ++it) {
1034 // Write the section relocation entries, in reverse order to match 'as'
1035 // (approximately, the exact algorithm is more complicated than this).
1036 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1037 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1038 Write32(Relocs[e - i - 1].Word0);
1039 Write32(Relocs[e - i - 1].Word1);
1043 // Write the symbol table data, if used.
1045 // Write the indirect symbol entries.
1046 for (MCAssembler::const_indirect_symbol_iterator
1047 it = Asm.indirect_symbol_begin(),
1048 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1049 // Indirect symbols in the non lazy symbol pointer section have some
1050 // special handling.
1051 const MCSectionMachO &Section =
1052 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1053 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1054 // If this symbol is defined and internal, mark it as such.
1055 if (it->Symbol->isDefined() &&
1056 !Asm.getSymbolData(*it->Symbol).isExternal()) {
1057 uint32_t Flags = ISF_Local;
1058 if (it->Symbol->isAbsolute())
1059 Flags |= ISF_Absolute;
1065 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1068 // FIXME: Check that offsets match computed ones.
1070 // Write the symbol table entries.
1071 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1072 WriteNlist(LocalSymbolData[i]);
1073 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1074 WriteNlist(ExternalSymbolData[i]);
1075 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1076 WriteNlist(UndefinedSymbolData[i]);
1078 // Write the string table.
1079 OS << StringTable.str();
1086 MachObjectWriter::MachObjectWriter(raw_ostream &OS,
1088 bool IsLittleEndian)
1089 : MCObjectWriter(OS, IsLittleEndian)
1091 Impl = new MachObjectWriterImpl(this, Is64Bit);
1094 MachObjectWriter::~MachObjectWriter() {
1095 delete (MachObjectWriterImpl*) Impl;
1098 void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1099 ((MachObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1102 void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
1103 const MCDataFragment &Fragment,
1104 const MCAsmFixup &Fixup, MCValue Target,
1105 uint64_t &FixedValue) {
1106 ((MachObjectWriterImpl*) Impl)->RecordRelocation(Asm, Fragment, Fixup,
1107 Target, FixedValue);
1110 void MachObjectWriter::WriteObject(const MCAssembler &Asm) {
1111 ((MachObjectWriterImpl*) Impl)->WriteObject(Asm);