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 MCDataFragment &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 virtual void RecordRelocation(const MCAssembler &Asm,
687 const MCDataFragment &Fragment,
688 const MCAsmFixup &Fixup, MCValue Target,
689 uint64_t &FixedValue) {
691 RecordX86_64Relocation(Asm, Fragment, Fixup, Target, FixedValue);
695 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
696 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
698 // If this is a difference or a defined symbol plus an offset, then we need
699 // a scattered relocation entry.
700 uint32_t Offset = Target.getConstant();
702 Offset += 1 << Log2Size;
703 if (Target.getSymB() ||
704 (Target.getSymA() && !Target.getSymA()->getSymbol().isUndefined() &&
706 RecordScatteredRelocation(Asm, Fragment, Fixup, Target, FixedValue);
711 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
714 unsigned IsExtern = 0;
717 if (Target.isAbsolute()) { // constant
718 // SymbolNum of 0 indicates the absolute section.
720 // FIXME: Currently, these are never generated (see code below). I cannot
721 // find a case where they are actually emitted.
725 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
726 MCSymbolData *SD = &Asm.getSymbolData(*Symbol);
728 if (Symbol->isUndefined()) {
730 Index = SD->getIndex();
733 // The index is the section ordinal.
737 MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
738 for (; it != ie; ++it, ++Index)
739 if (&*it == SD->getFragment()->getParent())
741 assert(it != ie && "Unable to find section index!");
742 Value = SD->getAddress();
748 // struct relocation_info (8 bytes)
749 MachRelocationEntry MRE;
751 MRE.Word1 = ((Index << 0) |
756 Relocations[Fragment.getParent()].push_back(MRE);
759 void BindIndirectSymbols(MCAssembler &Asm) {
760 // This is the point where 'as' creates actual symbols for indirect symbols
761 // (in the following two passes). It would be easier for us to do this
762 // sooner when we see the attribute, but that makes getting the order in the
763 // symbol table much more complicated than it is worth.
765 // FIXME: Revisit this when the dust settles.
767 // Bind non lazy symbol pointers first.
768 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
769 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
770 // FIXME: cast<> support!
771 const MCSectionMachO &Section =
772 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
774 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
777 Asm.getOrCreateSymbolData(*it->Symbol);
780 // Then lazy symbol pointers and symbol stubs.
781 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
782 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
783 // FIXME: cast<> support!
784 const MCSectionMachO &Section =
785 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
787 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
788 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
791 // Set the symbol type to undefined lazy, but only on construction.
793 // FIXME: Do not hardcode.
795 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
797 Entry.setFlags(Entry.getFlags() | 0x0001);
801 /// ComputeSymbolTable - Compute the symbol table data
803 /// \param StringTable [out] - The string table data.
804 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
806 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
807 std::vector<MachSymbolData> &LocalSymbolData,
808 std::vector<MachSymbolData> &ExternalSymbolData,
809 std::vector<MachSymbolData> &UndefinedSymbolData) {
810 // Build section lookup table.
811 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
813 for (MCAssembler::iterator it = Asm.begin(),
814 ie = Asm.end(); it != ie; ++it, ++Index)
815 SectionIndexMap[&it->getSection()] = Index;
816 assert(Index <= 256 && "Too many sections!");
818 // Index 0 is always the empty string.
819 StringMap<uint64_t> StringIndexMap;
820 StringTable += '\x00';
822 // Build the symbol arrays and the string table, but only for non-local
825 // The particular order that we collect the symbols and create the string
826 // table, then sort the symbols is chosen to match 'as'. Even though it
827 // doesn't matter for correctness, this is important for letting us diff .o
829 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
830 ie = Asm.symbol_end(); it != ie; ++it) {
831 const MCSymbol &Symbol = it->getSymbol();
833 // Ignore non-linker visible symbols.
834 if (!Asm.isSymbolLinkerVisible(it))
837 if (!it->isExternal() && !Symbol.isUndefined())
840 uint64_t &Entry = StringIndexMap[Symbol.getName()];
842 Entry = StringTable.size();
843 StringTable += Symbol.getName();
844 StringTable += '\x00';
849 MSD.StringIndex = Entry;
851 if (Symbol.isUndefined()) {
852 MSD.SectionIndex = 0;
853 UndefinedSymbolData.push_back(MSD);
854 } else if (Symbol.isAbsolute()) {
855 MSD.SectionIndex = 0;
856 ExternalSymbolData.push_back(MSD);
858 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
859 assert(MSD.SectionIndex && "Invalid section index!");
860 ExternalSymbolData.push_back(MSD);
864 // Now add the data for local symbols.
865 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
866 ie = Asm.symbol_end(); it != ie; ++it) {
867 const MCSymbol &Symbol = it->getSymbol();
869 // Ignore non-linker visible symbols.
870 if (!Asm.isSymbolLinkerVisible(it))
873 if (it->isExternal() || Symbol.isUndefined())
876 uint64_t &Entry = StringIndexMap[Symbol.getName()];
878 Entry = StringTable.size();
879 StringTable += Symbol.getName();
880 StringTable += '\x00';
885 MSD.StringIndex = Entry;
887 if (Symbol.isAbsolute()) {
888 MSD.SectionIndex = 0;
889 LocalSymbolData.push_back(MSD);
891 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
892 assert(MSD.SectionIndex && "Invalid section index!");
893 LocalSymbolData.push_back(MSD);
897 // External and undefined symbols are required to be in lexicographic order.
898 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
899 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
901 // Set the symbol indices.
903 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
904 LocalSymbolData[i].SymbolData->setIndex(Index++);
905 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
906 ExternalSymbolData[i].SymbolData->setIndex(Index++);
907 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
908 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
910 // The string table is padded to a multiple of 4.
911 while (StringTable.size() % 4)
912 StringTable += '\x00';
915 virtual void ExecutePostLayoutBinding(MCAssembler &Asm) {
916 // Create symbol data for any indirect symbols.
917 BindIndirectSymbols(Asm);
919 // Compute symbol table information and bind symbol indices.
920 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
921 UndefinedSymbolData);
924 virtual void WriteObject(const MCAssembler &Asm) {
925 unsigned NumSections = Asm.size();
927 // The section data starts after the header, the segment load command (and
928 // section headers) and the symbol table.
929 unsigned NumLoadCommands = 1;
930 uint64_t LoadCommandsSize = Is64Bit ?
931 SegmentLoadCommand64Size + NumSections * Section64Size :
932 SegmentLoadCommand32Size + NumSections * Section32Size;
934 // Add the symbol table load command sizes, if used.
935 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
936 UndefinedSymbolData.size();
938 NumLoadCommands += 2;
939 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
942 // Compute the total size of the section data, as well as its file size and
944 uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
946 uint64_t SectionDataSize = 0;
947 uint64_t SectionDataFileSize = 0;
949 for (MCAssembler::const_iterator it = Asm.begin(),
950 ie = Asm.end(); it != ie; ++it) {
951 const MCSectionData &SD = *it;
953 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
955 if (Asm.getBackend().isVirtualSection(SD.getSection()))
958 SectionDataSize = std::max(SectionDataSize,
959 SD.getAddress() + SD.getSize());
960 SectionDataFileSize = std::max(SectionDataFileSize,
961 SD.getAddress() + SD.getFileSize());
964 // The section data is padded to 4 bytes.
966 // FIXME: Is this machine dependent?
967 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
968 SectionDataFileSize += SectionDataPadding;
970 // Write the prolog, starting with the header and load command...
971 WriteHeader(NumLoadCommands, LoadCommandsSize,
972 Asm.getSubsectionsViaSymbols());
973 WriteSegmentLoadCommand(NumSections, VMSize,
974 SectionDataStart, SectionDataSize);
976 // ... and then the section headers.
977 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
978 for (MCAssembler::const_iterator it = Asm.begin(),
979 ie = Asm.end(); it != ie; ++it) {
980 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
981 unsigned NumRelocs = Relocs.size();
982 uint64_t SectionStart = SectionDataStart + it->getAddress();
983 WriteSection(Asm, *it, SectionStart, RelocTableEnd, NumRelocs);
984 RelocTableEnd += NumRelocs * RelocationInfoSize;
987 // Write the symbol table load command, if used.
989 unsigned FirstLocalSymbol = 0;
990 unsigned NumLocalSymbols = LocalSymbolData.size();
991 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
992 unsigned NumExternalSymbols = ExternalSymbolData.size();
993 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
994 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
995 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
996 unsigned NumSymTabSymbols =
997 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
998 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
999 uint64_t IndirectSymbolOffset = 0;
1001 // If used, the indirect symbols are written after the section data.
1002 if (NumIndirectSymbols)
1003 IndirectSymbolOffset = RelocTableEnd;
1005 // The symbol table is written after the indirect symbol data.
1006 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1008 // The string table is written after symbol table.
1009 uint64_t StringTableOffset =
1010 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
1012 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1013 StringTableOffset, StringTable.size());
1015 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1016 FirstExternalSymbol, NumExternalSymbols,
1017 FirstUndefinedSymbol, NumUndefinedSymbols,
1018 IndirectSymbolOffset, NumIndirectSymbols);
1021 // Write the actual section data.
1022 for (MCAssembler::const_iterator it = Asm.begin(),
1023 ie = Asm.end(); it != ie; ++it)
1024 Asm.WriteSectionData(it, Writer);
1026 // Write the extra padding.
1027 WriteZeros(SectionDataPadding);
1029 // Write the relocation entries.
1030 for (MCAssembler::const_iterator it = Asm.begin(),
1031 ie = Asm.end(); it != ie; ++it) {
1032 // Write the section relocation entries, in reverse order to match 'as'
1033 // (approximately, the exact algorithm is more complicated than this).
1034 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1035 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1036 Write32(Relocs[e - i - 1].Word0);
1037 Write32(Relocs[e - i - 1].Word1);
1041 // Write the symbol table data, if used.
1043 // Write the indirect symbol entries.
1044 for (MCAssembler::const_indirect_symbol_iterator
1045 it = Asm.indirect_symbol_begin(),
1046 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1047 // Indirect symbols in the non lazy symbol pointer section have some
1048 // special handling.
1049 const MCSectionMachO &Section =
1050 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1051 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1052 // If this symbol is defined and internal, mark it as such.
1053 if (it->Symbol->isDefined() &&
1054 !Asm.getSymbolData(*it->Symbol).isExternal()) {
1055 uint32_t Flags = ISF_Local;
1056 if (it->Symbol->isAbsolute())
1057 Flags |= ISF_Absolute;
1063 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1066 // FIXME: Check that offsets match computed ones.
1068 // Write the symbol table entries.
1069 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1070 WriteNlist(LocalSymbolData[i]);
1071 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1072 WriteNlist(ExternalSymbolData[i]);
1073 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1074 WriteNlist(UndefinedSymbolData[i]);
1076 // Write the string table.
1077 OS << StringTable.str();
1084 MachObjectWriter::MachObjectWriter(raw_ostream &OS,
1086 bool IsLittleEndian)
1087 : MCObjectWriter(OS, IsLittleEndian)
1089 Impl = new MachObjectWriterImpl(this, Is64Bit);
1092 MachObjectWriter::~MachObjectWriter() {
1093 delete (MachObjectWriterImpl*) Impl;
1096 void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1097 ((MachObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1100 void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
1101 const MCDataFragment &Fragment,
1102 const MCAsmFixup &Fixup, MCValue Target,
1103 uint64_t &FixedValue) {
1104 ((MachObjectWriterImpl*) Impl)->RecordRelocation(Asm, Fragment, Fixup,
1105 Target, FixedValue);
1108 void MachObjectWriter::WriteObject(const MCAssembler &Asm) {
1109 ((MachObjectWriterImpl*) Impl)->WriteObject(Asm);