1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
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 #define DEBUG_TYPE "assembler"
11 #include "llvm/MC/MCAssembler.h"
12 #include "llvm/MC/MCSectionMachO.h"
13 #include "llvm/Target/TargetMachOWriterInfo.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/raw_ostream.h"
24 class MachObjectWriter;
26 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
28 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
29 MachObjectWriter &MOW);
31 /// isVirtualSection - Check if this is a section which does not actually exist
32 /// in the object file.
33 static bool isVirtualSection(const MCSection &Section) {
35 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
36 unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
37 return (Type == MCSectionMachO::S_ZEROFILL);
40 class MachObjectWriter {
41 // See <mach-o/loader.h>.
43 Header_Magic32 = 0xFEEDFACE,
44 Header_Magic64 = 0xFEEDFACF
47 static const unsigned Header32Size = 28;
48 static const unsigned Header64Size = 32;
49 static const unsigned SegmentLoadCommand32Size = 56;
50 static const unsigned Section32Size = 68;
51 static const unsigned SymtabLoadCommandSize = 24;
52 static const unsigned DysymtabLoadCommandSize = 80;
53 static const unsigned Nlist32Size = 12;
54 static const unsigned RelocationInfoSize = 8;
61 HF_SubsectionsViaSymbols = 0x2000
64 enum LoadCommandType {
70 // See <mach-o/nlist.h>.
77 enum SymbolTypeFlags {
78 // If any of these bits are set, then the entry is a stab entry number (see
79 // <mach-o/stab.h>. Otherwise the other masks apply.
80 STF_StabsEntryMask = 0xe0,
84 STF_PrivateExtern = 0x10
87 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
89 enum IndirectSymbolFlags {
90 ISF_Local = 0x80000000,
91 ISF_Absolute = 0x40000000
94 /// RelocationFlags - Special flags for addresses.
95 enum RelocationFlags {
96 RF_Scattered = 0x80000000
99 enum RelocationInfoType {
103 RIT_PreboundLazyPointer = 3,
104 RIT_LocalDifference = 4
107 /// MachSymbolData - Helper struct for containing some precomputed information
109 struct MachSymbolData {
110 MCSymbolData *SymbolData;
111 uint64_t StringIndex;
112 uint8_t SectionIndex;
114 // Support lexicographic sorting.
115 bool operator<(const MachSymbolData &RHS) const {
116 const std::string &Name = SymbolData->getSymbol().getName();
117 return Name < RHS.SymbolData->getSymbol().getName();
125 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
126 : OS(_OS), IsLSB(_IsLSB) {
129 /// @name Helper Methods
132 void Write8(uint8_t Value) {
136 void Write16(uint16_t Value) {
138 Write8(uint8_t(Value >> 0));
139 Write8(uint8_t(Value >> 8));
141 Write8(uint8_t(Value >> 8));
142 Write8(uint8_t(Value >> 0));
146 void Write32(uint32_t Value) {
148 Write16(uint16_t(Value >> 0));
149 Write16(uint16_t(Value >> 16));
151 Write16(uint16_t(Value >> 16));
152 Write16(uint16_t(Value >> 0));
156 void Write64(uint64_t Value) {
158 Write32(uint32_t(Value >> 0));
159 Write32(uint32_t(Value >> 32));
161 Write32(uint32_t(Value >> 32));
162 Write32(uint32_t(Value >> 0));
166 void WriteZeros(unsigned N) {
167 const char Zeros[16] = { 0 };
169 for (unsigned i = 0, e = N / 16; i != e; ++i)
170 OS << StringRef(Zeros, 16);
172 OS << StringRef(Zeros, N % 16);
175 void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
178 WriteZeros(ZeroFillSize - Str.size());
183 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
184 bool SubsectionsViaSymbols) {
187 if (SubsectionsViaSymbols)
188 Flags |= HF_SubsectionsViaSymbols;
190 // struct mach_header (28 bytes)
192 uint64_t Start = OS.tell();
195 Write32(Header_Magic32);
197 // FIXME: Support cputype.
198 Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
199 // FIXME: Support cpusubtype.
200 Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
202 Write32(NumLoadCommands); // Object files have a single load command, the
204 Write32(LoadCommandsSize);
207 assert(OS.tell() - Start == Header32Size);
210 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
212 /// \arg NumSections - The number of sections in this segment.
213 /// \arg SectionDataSize - The total size of the sections.
214 void WriteSegmentLoadCommand32(unsigned NumSections,
216 uint64_t SectionDataStartOffset,
217 uint64_t SectionDataSize) {
218 // struct segment_command (56 bytes)
220 uint64_t Start = OS.tell();
223 Write32(LCT_Segment);
224 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
227 Write32(0); // vmaddr
228 Write32(VMSize); // vmsize
229 Write32(SectionDataStartOffset); // file offset
230 Write32(SectionDataSize); // file size
231 Write32(0x7); // maxprot
232 Write32(0x7); // initprot
233 Write32(NumSections);
236 assert(OS.tell() - Start == SegmentLoadCommand32Size);
239 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
240 uint64_t RelocationsStart, unsigned NumRelocations) {
241 // The offset is unused for virtual sections.
242 if (isVirtualSection(SD.getSection())) {
243 assert(SD.getFileSize() == 0 && "Invalid file size!");
247 // struct section (68 bytes)
249 uint64_t Start = OS.tell();
252 // FIXME: cast<> support!
253 const MCSectionMachO &Section =
254 static_cast<const MCSectionMachO&>(SD.getSection());
255 WriteString(Section.getSectionName(), 16);
256 WriteString(Section.getSegmentName(), 16);
257 Write32(SD.getAddress()); // address
258 Write32(SD.getSize()); // size
261 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
262 Write32(Log2_32(SD.getAlignment()));
263 Write32(NumRelocations ? RelocationsStart : 0);
264 Write32(NumRelocations);
265 Write32(Section.getTypeAndAttributes());
266 Write32(0); // reserved1
267 Write32(Section.getStubSize()); // reserved2
269 assert(OS.tell() - Start == Section32Size);
272 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
273 uint32_t StringTableOffset,
274 uint32_t StringTableSize) {
275 // struct symtab_command (24 bytes)
277 uint64_t Start = OS.tell();
281 Write32(SymtabLoadCommandSize);
282 Write32(SymbolOffset);
284 Write32(StringTableOffset);
285 Write32(StringTableSize);
287 assert(OS.tell() - Start == SymtabLoadCommandSize);
290 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
291 uint32_t NumLocalSymbols,
292 uint32_t FirstExternalSymbol,
293 uint32_t NumExternalSymbols,
294 uint32_t FirstUndefinedSymbol,
295 uint32_t NumUndefinedSymbols,
296 uint32_t IndirectSymbolOffset,
297 uint32_t NumIndirectSymbols) {
298 // struct dysymtab_command (80 bytes)
300 uint64_t Start = OS.tell();
303 Write32(LCT_Dysymtab);
304 Write32(DysymtabLoadCommandSize);
305 Write32(FirstLocalSymbol);
306 Write32(NumLocalSymbols);
307 Write32(FirstExternalSymbol);
308 Write32(NumExternalSymbols);
309 Write32(FirstUndefinedSymbol);
310 Write32(NumUndefinedSymbols);
311 Write32(0); // tocoff
313 Write32(0); // modtaboff
314 Write32(0); // nmodtab
315 Write32(0); // extrefsymoff
316 Write32(0); // nextrefsyms
317 Write32(IndirectSymbolOffset);
318 Write32(NumIndirectSymbols);
319 Write32(0); // extreloff
320 Write32(0); // nextrel
321 Write32(0); // locreloff
322 Write32(0); // nlocrel
324 assert(OS.tell() - Start == DysymtabLoadCommandSize);
327 void WriteNlist32(MachSymbolData &MSD) {
328 MCSymbolData &Data = *MSD.SymbolData;
329 MCSymbol &Symbol = Data.getSymbol();
332 // Set the N_TYPE bits. See <mach-o/nlist.h>.
334 // FIXME: Are the prebound or indirect fields possible here?
335 if (Symbol.isUndefined())
336 Type = STT_Undefined;
337 else if (Symbol.isAbsolute())
342 // FIXME: Set STAB bits.
344 if (Data.isPrivateExtern())
345 Type |= STF_PrivateExtern;
348 if (Data.isExternal() || Symbol.isUndefined())
349 Type |= STF_External;
351 // struct nlist (12 bytes)
353 Write32(MSD.StringIndex);
355 Write8(MSD.SectionIndex);
357 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
359 Write16(Data.getFlags() & 0xFFFF);
361 // Write the symbol address.
362 uint32_t Address = 0;
363 if (Symbol.isDefined()) {
364 if (Symbol.isAbsolute()) {
365 llvm_unreachable("FIXME: Not yet implemented!");
367 Address = Data.getFragment()->getAddress() + Data.getOffset();
373 struct MachRelocationEntry {
377 void ComputeScatteredRelocationInfo(MCAssembler &Asm,
378 MCSectionData::Fixup &Fixup,
379 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
380 std::vector<MachRelocationEntry> &Relocs) {
381 uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
382 unsigned IsPCRel = 0;
383 unsigned Type = RIT_Vanilla;
387 const MCSymbol *A = Fixup.Value.getSymA();
388 MCSymbolData *SD = SymbolMap.lookup(A);
389 uint32_t Value = SD->getFragment()->getAddress() + SD->getOffset();
392 if (const MCSymbol *B = Fixup.Value.getSymB()) {
393 Type = RIT_LocalDifference;
395 MCSymbolData *SD = SymbolMap.lookup(B);
396 Value2 = SD->getFragment()->getAddress() + SD->getOffset();
399 unsigned Log2Size = Log2_32(Fixup.Size);
400 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
402 // The value which goes in the fixup is current value of the expression.
403 Fixup.FixedValue = Value - Value2 + Fixup.Value.getConstant();
405 MachRelocationEntry MRE;
406 MRE.Word0 = ((Address << 0) |
412 Relocs.push_back(MRE);
414 if (Type == RIT_LocalDifference) {
417 MachRelocationEntry MRE;
418 MRE.Word0 = ((0 << 0) |
424 Relocs.push_back(MRE);
428 void ComputeRelocationInfo(MCAssembler &Asm,
429 MCSectionData::Fixup &Fixup,
430 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
431 std::vector<MachRelocationEntry> &Relocs) {
432 // If this is a local symbol plus an offset or a difference, then we need a
433 // scattered relocation entry.
434 if (Fixup.Value.getSymB()) // a - b
435 return ComputeScatteredRelocationInfo(Asm, Fixup, SymbolMap, Relocs);
436 if (Fixup.Value.getSymA() && Fixup.Value.getConstant())
437 if (!Fixup.Value.getSymA()->isUndefined())
438 return ComputeScatteredRelocationInfo(Asm, Fixup, SymbolMap, Relocs);
441 uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
444 unsigned IsPCRel = 0;
445 unsigned IsExtern = 0;
448 if (Fixup.Value.isAbsolute()) { // constant
449 // SymbolNum of 0 indicates the absolute section.
452 llvm_unreachable("FIXME: Not yet implemented!");
454 const MCSymbol *Symbol = Fixup.Value.getSymA();
455 MCSymbolData *SD = SymbolMap.lookup(Symbol);
457 if (Symbol->isUndefined()) {
459 Index = SD->getIndex();
462 // The index is the section ordinal.
466 for (MCAssembler::iterator it = Asm.begin(),
467 ie = Asm.end(); it != ie; ++it, ++Index)
468 if (&*it == SD->getFragment()->getParent())
470 Value = SD->getFragment()->getAddress() + SD->getOffset();
476 // The value which goes in the fixup is current value of the expression.
477 Fixup.FixedValue = Value + Fixup.Value.getConstant();
479 unsigned Log2Size = Log2_32(Fixup.Size);
480 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
482 // struct relocation_info (8 bytes)
483 MachRelocationEntry MRE;
485 MRE.Word1 = ((Index << 0) |
490 Relocs.push_back(MRE);
493 void BindIndirectSymbols(MCAssembler &Asm,
494 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap) {
495 // This is the point where 'as' creates actual symbols for indirect symbols
496 // (in the following two passes). It would be easier for us to do this
497 // sooner when we see the attribute, but that makes getting the order in the
498 // symbol table much more complicated than it is worth.
500 // FIXME: Revisit this when the dust settles.
502 // Bind non lazy symbol pointers first.
503 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
504 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
505 // FIXME: cast<> support!
506 const MCSectionMachO &Section =
507 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
510 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
511 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
514 MCSymbolData *&Entry = SymbolMap[it->Symbol];
516 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
519 // Then lazy symbol pointers and symbol stubs.
520 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
521 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
522 // FIXME: cast<> support!
523 const MCSectionMachO &Section =
524 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
527 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
528 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
529 Type != MCSectionMachO::S_SYMBOL_STUBS)
532 MCSymbolData *&Entry = SymbolMap[it->Symbol];
534 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
536 // Set the symbol type to undefined lazy, but only on construction.
538 // FIXME: Do not hardcode.
539 Entry->setFlags(Entry->getFlags() | 0x0001);
544 /// ComputeSymbolTable - Compute the symbol table data
546 /// \param StringTable [out] - The string table data.
547 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
549 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
550 std::vector<MachSymbolData> &LocalSymbolData,
551 std::vector<MachSymbolData> &ExternalSymbolData,
552 std::vector<MachSymbolData> &UndefinedSymbolData) {
553 // Build section lookup table.
554 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
556 for (MCAssembler::iterator it = Asm.begin(),
557 ie = Asm.end(); it != ie; ++it, ++Index)
558 SectionIndexMap[&it->getSection()] = Index;
559 assert(Index <= 256 && "Too many sections!");
561 // Index 0 is always the empty string.
562 StringMap<uint64_t> StringIndexMap;
563 StringTable += '\x00';
565 // Build the symbol arrays and the string table, but only for non-local
568 // The particular order that we collect the symbols and create the string
569 // table, then sort the symbols is chosen to match 'as'. Even though it
570 // doesn't matter for correctness, this is important for letting us diff .o
572 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
573 ie = Asm.symbol_end(); it != ie; ++it) {
574 MCSymbol &Symbol = it->getSymbol();
576 // Ignore assembler temporaries.
577 if (it->getSymbol().isTemporary())
580 if (!it->isExternal() && !Symbol.isUndefined())
583 uint64_t &Entry = StringIndexMap[Symbol.getName()];
585 Entry = StringTable.size();
586 StringTable += Symbol.getName();
587 StringTable += '\x00';
592 MSD.StringIndex = Entry;
594 if (Symbol.isUndefined()) {
595 MSD.SectionIndex = 0;
596 UndefinedSymbolData.push_back(MSD);
597 } else if (Symbol.isAbsolute()) {
598 MSD.SectionIndex = 0;
599 ExternalSymbolData.push_back(MSD);
601 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
602 assert(MSD.SectionIndex && "Invalid section index!");
603 ExternalSymbolData.push_back(MSD);
607 // Now add the data for local symbols.
608 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
609 ie = Asm.symbol_end(); it != ie; ++it) {
610 MCSymbol &Symbol = it->getSymbol();
612 // Ignore assembler temporaries.
613 if (it->getSymbol().isTemporary())
616 if (it->isExternal() || Symbol.isUndefined())
619 uint64_t &Entry = StringIndexMap[Symbol.getName()];
621 Entry = StringTable.size();
622 StringTable += Symbol.getName();
623 StringTable += '\x00';
628 MSD.StringIndex = Entry;
630 if (Symbol.isAbsolute()) {
631 MSD.SectionIndex = 0;
632 LocalSymbolData.push_back(MSD);
634 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
635 assert(MSD.SectionIndex && "Invalid section index!");
636 LocalSymbolData.push_back(MSD);
640 // External and undefined symbols are required to be in lexicographic order.
641 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
642 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
644 // Set the symbol indices.
646 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
647 LocalSymbolData[i].SymbolData->setIndex(Index++);
648 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
649 ExternalSymbolData[i].SymbolData->setIndex(Index++);
650 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
651 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
653 // The string table is padded to a multiple of 4.
655 // FIXME: Check to see if this varies per arch.
656 while (StringTable.size() % 4)
657 StringTable += '\x00';
660 void WriteObject(MCAssembler &Asm) {
661 unsigned NumSections = Asm.size();
663 // Compute the symbol -> symbol data map.
665 // FIXME: This should not be here.
666 DenseMap<const MCSymbol*, MCSymbolData *> SymbolMap;
667 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
668 ie = Asm.symbol_end(); it != ie; ++it)
669 SymbolMap[&it->getSymbol()] = it;
671 // Create symbol data for any indirect symbols.
672 BindIndirectSymbols(Asm, SymbolMap);
674 // Compute symbol table information.
675 SmallString<256> StringTable;
676 std::vector<MachSymbolData> LocalSymbolData;
677 std::vector<MachSymbolData> ExternalSymbolData;
678 std::vector<MachSymbolData> UndefinedSymbolData;
679 unsigned NumSymbols = Asm.symbol_size();
681 // No symbol table command is written if there are no symbols.
683 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
684 UndefinedSymbolData);
686 // The section data starts after the header, the segment load command (and
687 // section headers) and the symbol table.
688 unsigned NumLoadCommands = 1;
689 uint64_t LoadCommandsSize =
690 SegmentLoadCommand32Size + NumSections * Section32Size;
692 // Add the symbol table load command sizes, if used.
694 NumLoadCommands += 2;
695 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
698 // Compute the total size of the section data, as well as its file size and
700 uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
701 uint64_t SectionDataSize = 0;
702 uint64_t SectionDataFileSize = 0;
704 for (MCAssembler::iterator it = Asm.begin(),
705 ie = Asm.end(); it != ie; ++it) {
706 MCSectionData &SD = *it;
708 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
710 if (isVirtualSection(SD.getSection()))
713 SectionDataSize = std::max(SectionDataSize,
714 SD.getAddress() + SD.getSize());
715 SectionDataFileSize = std::max(SectionDataFileSize,
716 SD.getAddress() + SD.getFileSize());
719 // The section data is passed to 4 bytes.
721 // FIXME: Is this machine dependent?
722 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
723 SectionDataFileSize += SectionDataPadding;
725 // Write the prolog, starting with the header and load command...
726 WriteHeader32(NumLoadCommands, LoadCommandsSize,
727 Asm.getSubsectionsViaSymbols());
728 WriteSegmentLoadCommand32(NumSections, VMSize,
729 SectionDataStart, SectionDataSize);
731 // ... and then the section headers.
733 // We also compute the section relocations while we do this. Note that
734 // compute relocation info will also update the fixup to have the correct
735 // value; this will be overwrite the appropriate data in the fragment when
737 std::vector<MachRelocationEntry> RelocInfos;
738 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
739 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie;
741 MCSectionData &SD = *it;
743 // The assembler writes relocations in the reverse order they were seen.
745 // FIXME: It is probably more complicated than this.
746 unsigned NumRelocsStart = RelocInfos.size();
747 for (unsigned i = 0, e = SD.fixup_size(); i != e; ++i)
748 ComputeRelocationInfo(Asm, SD.getFixups()[e - i - 1], SymbolMap,
751 unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
752 uint64_t SectionStart = SectionDataStart + SD.getAddress();
753 WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
754 RelocTableEnd += NumRelocs * RelocationInfoSize;
757 // Write the symbol table load command, if used.
759 unsigned FirstLocalSymbol = 0;
760 unsigned NumLocalSymbols = LocalSymbolData.size();
761 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
762 unsigned NumExternalSymbols = ExternalSymbolData.size();
763 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
764 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
765 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
766 unsigned NumSymTabSymbols =
767 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
768 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
769 uint64_t IndirectSymbolOffset = 0;
771 // If used, the indirect symbols are written after the section data.
772 if (NumIndirectSymbols)
773 IndirectSymbolOffset = RelocTableEnd;
775 // The symbol table is written after the indirect symbol data.
776 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
778 // The string table is written after symbol table.
779 uint64_t StringTableOffset =
780 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
781 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
782 StringTableOffset, StringTable.size());
784 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
785 FirstExternalSymbol, NumExternalSymbols,
786 FirstUndefinedSymbol, NumUndefinedSymbols,
787 IndirectSymbolOffset, NumIndirectSymbols);
790 // Write the actual section data.
791 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
792 WriteFileData(OS, *it, *this);
794 // Write the extra padding.
795 WriteZeros(SectionDataPadding);
797 // Write the relocation entries.
798 for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
799 Write32(RelocInfos[i].Word0);
800 Write32(RelocInfos[i].Word1);
803 // Write the symbol table data, if used.
805 // Write the indirect symbol entries.
806 for (MCAssembler::indirect_symbol_iterator
807 it = Asm.indirect_symbol_begin(),
808 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
809 // Indirect symbols in the non lazy symbol pointer section have some
811 const MCSectionMachO &Section =
812 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
814 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
815 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
816 // If this symbol is defined and internal, mark it as such.
817 if (it->Symbol->isDefined() &&
818 !SymbolMap.lookup(it->Symbol)->isExternal()) {
819 uint32_t Flags = ISF_Local;
820 if (it->Symbol->isAbsolute())
821 Flags |= ISF_Absolute;
827 Write32(SymbolMap[it->Symbol]->getIndex());
830 // FIXME: Check that offsets match computed ones.
832 // Write the symbol table entries.
833 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
834 WriteNlist32(LocalSymbolData[i]);
835 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
836 WriteNlist32(ExternalSymbolData[i]);
837 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
838 WriteNlist32(UndefinedSymbolData[i]);
840 // Write the string table.
841 OS << StringTable.str();
848 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
851 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
854 FileSize(~UINT64_C(0))
857 Parent->getFragmentList().push_back(this);
860 MCFragment::~MCFragment() {
863 uint64_t MCFragment::getAddress() const {
864 assert(getParent() && "Missing Section!");
865 return getParent()->getAddress() + Offset;
870 MCSectionData::MCSectionData() : Section(0) {}
872 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
873 : Section(&_Section),
875 Address(~UINT64_C(0)),
877 FileSize(~UINT64_C(0)),
881 A->getSectionList().push_back(this);
884 const MCSectionData::Fixup *
885 MCSectionData::LookupFixup(const MCFragment *Fragment, uint64_t Offset) const {
886 // Use a one level cache to turn the common case of accessing the fixups in
887 // order into O(1) instead of O(N).
888 unsigned i = LastFixupLookup, Count = Fixups.size(), End = Fixups.size();
892 const Fixup &F = Fixups[i];
893 if (F.Fragment == Fragment && F.Offset == Offset) {
908 MCSymbolData::MCSymbolData() : Symbol(*(MCSymbol*)0) {}
910 MCSymbolData::MCSymbolData(MCSymbol &_Symbol, MCFragment *_Fragment,
911 uint64_t _Offset, MCAssembler *A)
912 : Symbol(_Symbol), Fragment(_Fragment), Offset(_Offset),
913 IsExternal(false), IsPrivateExtern(false), Flags(0), Index(0)
916 A->getSymbolList().push_back(this);
921 MCAssembler::MCAssembler(raw_ostream &_OS)
923 SubsectionsViaSymbols(false)
927 MCAssembler::~MCAssembler() {
930 void MCAssembler::LayoutSection(MCSectionData &SD) {
931 uint64_t Address = SD.getAddress();
933 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
936 F.setOffset(Address - SD.getAddress());
938 // Evaluate fragment size.
939 switch (F.getKind()) {
940 case MCFragment::FT_Align: {
941 MCAlignFragment &AF = cast<MCAlignFragment>(F);
943 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
944 if (Size > AF.getMaxBytesToEmit())
947 AF.setFileSize(Size);
951 case MCFragment::FT_Data:
952 F.setFileSize(F.getMaxFileSize());
955 case MCFragment::FT_Fill: {
956 MCFillFragment &FF = cast<MCFillFragment>(F);
958 F.setFileSize(F.getMaxFileSize());
960 // If the fill value is constant, thats it.
961 if (FF.getValue().isAbsolute())
964 // Otherwise, add fixups for the values.
965 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
966 MCSectionData::Fixup Fix(F, i * FF.getValueSize(),
967 FF.getValue(),FF.getValueSize());
968 SD.getFixups().push_back(Fix);
973 case MCFragment::FT_Org: {
974 MCOrgFragment &OF = cast<MCOrgFragment>(F);
976 if (!OF.getOffset().isAbsolute())
977 llvm_unreachable("FIXME: Not yet implemented!");
978 uint64_t OrgOffset = OF.getOffset().getConstant();
979 uint64_t Offset = Address - SD.getAddress();
981 // FIXME: We need a way to communicate this error.
982 if (OrgOffset < Offset)
983 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
984 "' (at offset '" + Twine(Offset) + "'");
986 F.setFileSize(OrgOffset - Offset);
990 case MCFragment::FT_ZeroFill: {
991 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
993 // Align the fragment offset; it is safe to adjust the offset freely since
994 // this is only in virtual sections.
995 uint64_t Aligned = RoundUpToAlignment(Address, ZFF.getAlignment());
996 F.setOffset(Aligned - SD.getAddress());
998 // FIXME: This is misnamed.
999 F.setFileSize(ZFF.getSize());
1004 Address += F.getFileSize();
1007 // Set the section sizes.
1008 SD.setSize(Address - SD.getAddress());
1009 if (isVirtualSection(SD.getSection()))
1012 SD.setFileSize(Address - SD.getAddress());
1015 /// WriteFileData - Write the \arg F data to the output file.
1016 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1017 MachObjectWriter &MOW) {
1018 uint64_t Start = OS.tell();
1023 // FIXME: Embed in fragments instead?
1024 switch (F.getKind()) {
1025 case MCFragment::FT_Align: {
1026 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1027 uint64_t Count = AF.getFileSize() / AF.getValueSize();
1029 // FIXME: This error shouldn't actually occur (the front end should emit
1030 // multiple .align directives to enforce the semantics it wants), but is
1031 // severe enough that we want to report it. How to handle this?
1032 if (Count * AF.getValueSize() != AF.getFileSize())
1033 llvm_report_error("undefined .align directive, value size '" +
1034 Twine(AF.getValueSize()) +
1035 "' is not a divisor of padding size '" +
1036 Twine(AF.getFileSize()) + "'");
1038 for (uint64_t i = 0; i != Count; ++i) {
1039 switch (AF.getValueSize()) {
1041 assert(0 && "Invalid size!");
1042 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1043 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1044 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1045 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1051 case MCFragment::FT_Data:
1052 OS << cast<MCDataFragment>(F).getContents().str();
1055 case MCFragment::FT_Fill: {
1056 MCFillFragment &FF = cast<MCFillFragment>(F);
1059 if (FF.getValue().isAbsolute())
1060 Value = FF.getValue().getConstant();
1061 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1062 if (!FF.getValue().isAbsolute()) {
1065 // FIXME: Find a better way to write in the fixes.
1066 const MCSectionData::Fixup *Fixup =
1067 F.getParent()->LookupFixup(&F, i * FF.getValueSize());
1068 assert(Fixup && "Missing fixup for fill value!");
1069 Value = Fixup->FixedValue;
1072 switch (FF.getValueSize()) {
1074 assert(0 && "Invalid size!");
1075 case 1: MOW.Write8 (uint8_t (Value)); break;
1076 case 2: MOW.Write16(uint16_t(Value)); break;
1077 case 4: MOW.Write32(uint32_t(Value)); break;
1078 case 8: MOW.Write64(uint64_t(Value)); break;
1084 case MCFragment::FT_Org: {
1085 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1087 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1088 MOW.Write8(uint8_t(OF.getValue()));
1093 case MCFragment::FT_ZeroFill: {
1094 assert(0 && "Invalid zero fill fragment in concrete section!");
1099 assert(OS.tell() - Start == F.getFileSize());
1102 /// WriteFileData - Write the \arg SD data to the output file.
1103 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1104 MachObjectWriter &MOW) {
1105 // Ignore virtual sections.
1106 if (isVirtualSection(SD.getSection())) {
1107 assert(SD.getFileSize() == 0);
1111 uint64_t Start = OS.tell();
1114 for (MCSectionData::const_iterator it = SD.begin(),
1115 ie = SD.end(); it != ie; ++it)
1116 WriteFileData(OS, *it, MOW);
1118 // Add section padding.
1119 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1120 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1122 assert(OS.tell() - Start == SD.getFileSize());
1125 void MCAssembler::Finish() {
1126 // Layout the concrete sections and fragments.
1127 uint64_t Address = 0;
1128 MCSectionData *Prev = 0;
1129 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1130 MCSectionData &SD = *it;
1132 // Skip virtual sections.
1133 if (isVirtualSection(SD.getSection()))
1136 // Align this section if necessary by adding padding bytes to the previous
1138 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1139 assert(Prev && "Missing prev section!");
1140 Prev->setFileSize(Prev->getFileSize() + Pad);
1144 // Layout the section fragments and its size.
1145 SD.setAddress(Address);
1147 Address += SD.getFileSize();
1152 // Layout the virtual sections.
1153 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1154 MCSectionData &SD = *it;
1156 if (!isVirtualSection(SD.getSection()))
1159 SD.setAddress(Address);
1161 Address += SD.getSize();
1164 // Write the object file.
1165 MachObjectWriter MOW(OS);
1166 MOW.WriteObject(*this);