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 class MachObjectWriter {
32 // See <mach-o/loader.h>.
34 Header_Magic32 = 0xFEEDFACE,
35 Header_Magic64 = 0xFEEDFACF
38 static const unsigned Header32Size = 28;
39 static const unsigned Header64Size = 32;
40 static const unsigned SegmentLoadCommand32Size = 56;
41 static const unsigned Section32Size = 68;
42 static const unsigned SymtabLoadCommandSize = 24;
43 static const unsigned DysymtabLoadCommandSize = 80;
44 static const unsigned Nlist32Size = 12;
45 static const unsigned RelocationInfoSize = 8;
52 HF_SubsectionsViaSymbols = 0x2000
55 enum LoadCommandType {
61 // See <mach-o/nlist.h>.
68 enum SymbolTypeFlags {
69 // If any of these bits are set, then the entry is a stab entry number (see
70 // <mach-o/stab.h>. Otherwise the other masks apply.
71 STF_StabsEntryMask = 0xe0,
75 STF_PrivateExtern = 0x10
78 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
80 enum IndirectSymbolFlags {
81 ISF_Local = 0x80000000,
82 ISF_Absolute = 0x40000000
85 /// RelocationFlags - Special flags for addresses.
86 enum RelocationFlags {
87 RF_Scattered = 0x80000000
90 enum RelocationInfoType {
94 RIT_PreboundLazyPointer = 3,
95 RIT_LocalDifference = 4
98 /// MachSymbolData - Helper struct for containing some precomputed information
100 struct MachSymbolData {
101 MCSymbolData *SymbolData;
102 uint64_t StringIndex;
103 uint8_t SectionIndex;
105 // Support lexicographic sorting.
106 bool operator<(const MachSymbolData &RHS) const {
107 const std::string &Name = SymbolData->getSymbol().getName();
108 return Name < RHS.SymbolData->getSymbol().getName();
116 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
117 : OS(_OS), IsLSB(_IsLSB) {
120 /// @name Helper Methods
123 void Write8(uint8_t Value) {
127 void Write16(uint16_t Value) {
129 Write8(uint8_t(Value >> 0));
130 Write8(uint8_t(Value >> 8));
132 Write8(uint8_t(Value >> 8));
133 Write8(uint8_t(Value >> 0));
137 void Write32(uint32_t Value) {
139 Write16(uint16_t(Value >> 0));
140 Write16(uint16_t(Value >> 16));
142 Write16(uint16_t(Value >> 16));
143 Write16(uint16_t(Value >> 0));
147 void Write64(uint64_t Value) {
149 Write32(uint32_t(Value >> 0));
150 Write32(uint32_t(Value >> 32));
152 Write32(uint32_t(Value >> 32));
153 Write32(uint32_t(Value >> 0));
157 void WriteZeros(unsigned N) {
158 const char Zeros[16] = { 0 };
160 for (unsigned i = 0, e = N / 16; i != e; ++i)
161 OS << StringRef(Zeros, 16);
163 OS << StringRef(Zeros, N % 16);
166 void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
169 WriteZeros(ZeroFillSize - Str.size());
174 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
175 bool SubsectionsViaSymbols) {
178 if (SubsectionsViaSymbols)
179 Flags |= HF_SubsectionsViaSymbols;
181 // struct mach_header (28 bytes)
183 uint64_t Start = OS.tell();
186 Write32(Header_Magic32);
188 // FIXME: Support cputype.
189 Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
190 // FIXME: Support cpusubtype.
191 Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
193 Write32(NumLoadCommands); // Object files have a single load command, the
195 Write32(LoadCommandsSize);
198 assert(OS.tell() - Start == Header32Size);
201 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
203 /// \arg NumSections - The number of sections in this segment.
204 /// \arg SectionDataSize - The total size of the sections.
205 void WriteSegmentLoadCommand32(unsigned NumSections,
207 uint64_t SectionDataStartOffset,
208 uint64_t SectionDataSize) {
209 // struct segment_command (56 bytes)
211 uint64_t Start = OS.tell();
214 Write32(LCT_Segment);
215 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
218 Write32(0); // vmaddr
219 Write32(VMSize); // vmsize
220 Write32(SectionDataStartOffset); // file offset
221 Write32(SectionDataSize); // file size
222 Write32(0x7); // maxprot
223 Write32(0x7); // initprot
224 Write32(NumSections);
227 assert(OS.tell() - Start == SegmentLoadCommand32Size);
230 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
231 uint64_t RelocationsStart, unsigned NumRelocations) {
232 // struct section (68 bytes)
234 uint64_t Start = OS.tell();
237 // FIXME: cast<> support!
238 const MCSectionMachO &Section =
239 static_cast<const MCSectionMachO&>(SD.getSection());
240 WriteString(Section.getSectionName(), 16);
241 WriteString(Section.getSegmentName(), 16);
242 Write32(SD.getAddress()); // address
243 Write32(SD.getSize()); // size
246 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
247 Write32(Log2_32(SD.getAlignment()));
248 Write32(NumRelocations ? RelocationsStart : 0);
249 Write32(NumRelocations);
250 Write32(Section.getTypeAndAttributes());
251 Write32(0); // reserved1
252 Write32(Section.getStubSize()); // reserved2
254 assert(OS.tell() - Start == Section32Size);
257 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
258 uint32_t StringTableOffset,
259 uint32_t StringTableSize) {
260 // struct symtab_command (24 bytes)
262 uint64_t Start = OS.tell();
266 Write32(SymtabLoadCommandSize);
267 Write32(SymbolOffset);
269 Write32(StringTableOffset);
270 Write32(StringTableSize);
272 assert(OS.tell() - Start == SymtabLoadCommandSize);
275 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
276 uint32_t NumLocalSymbols,
277 uint32_t FirstExternalSymbol,
278 uint32_t NumExternalSymbols,
279 uint32_t FirstUndefinedSymbol,
280 uint32_t NumUndefinedSymbols,
281 uint32_t IndirectSymbolOffset,
282 uint32_t NumIndirectSymbols) {
283 // struct dysymtab_command (80 bytes)
285 uint64_t Start = OS.tell();
288 Write32(LCT_Dysymtab);
289 Write32(DysymtabLoadCommandSize);
290 Write32(FirstLocalSymbol);
291 Write32(NumLocalSymbols);
292 Write32(FirstExternalSymbol);
293 Write32(NumExternalSymbols);
294 Write32(FirstUndefinedSymbol);
295 Write32(NumUndefinedSymbols);
296 Write32(0); // tocoff
298 Write32(0); // modtaboff
299 Write32(0); // nmodtab
300 Write32(0); // extrefsymoff
301 Write32(0); // nextrefsyms
302 Write32(IndirectSymbolOffset);
303 Write32(NumIndirectSymbols);
304 Write32(0); // extreloff
305 Write32(0); // nextrel
306 Write32(0); // locreloff
307 Write32(0); // nlocrel
309 assert(OS.tell() - Start == DysymtabLoadCommandSize);
312 void WriteNlist32(MachSymbolData &MSD) {
313 MCSymbolData &Data = *MSD.SymbolData;
314 MCSymbol &Symbol = Data.getSymbol();
317 // Set the N_TYPE bits. See <mach-o/nlist.h>.
319 // FIXME: Are the prebound or indirect fields possible here?
320 if (Symbol.isUndefined())
321 Type = STT_Undefined;
322 else if (Symbol.isAbsolute())
327 // FIXME: Set STAB bits.
329 if (Data.isPrivateExtern())
330 Type |= STF_PrivateExtern;
333 if (Data.isExternal() || Symbol.isUndefined())
334 Type |= STF_External;
336 // struct nlist (12 bytes)
338 Write32(MSD.StringIndex);
340 Write8(MSD.SectionIndex);
342 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
344 Write16(Data.getFlags() & 0xFFFF);
346 // Write the symbol address.
347 uint32_t Address = 0;
348 if (Symbol.isDefined()) {
349 if (Symbol.isAbsolute()) {
350 llvm_unreachable("FIXME: Not yet implemented!");
352 Address = Data.getFragment()->getAddress() + Data.getOffset();
358 struct MachRelocationEntry {
362 void ComputeScatteredRelocationInfo(MCAssembler &Asm,
363 MCSectionData::Fixup &Fixup,
364 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
365 std::vector<MachRelocationEntry> &Relocs) {
366 uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
367 unsigned IsPCRel = 0;
368 unsigned Type = RIT_Vanilla;
372 const MCSymbol *A = Fixup.Value.getSymA();
373 MCSymbolData *SD = SymbolMap.lookup(A);
374 uint32_t Value = SD->getFragment()->getAddress() + SD->getOffset();
377 if (const MCSymbol *B = Fixup.Value.getSymB()) {
378 Type = RIT_LocalDifference;
380 MCSymbolData *SD = SymbolMap.lookup(B);
381 Value2 = SD->getFragment()->getAddress() + SD->getOffset();
384 unsigned Log2Size = Log2_32(Fixup.Size);
385 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
387 // The value which goes in the fixup is current value of the expression.
388 Fixup.FixedValue = Value - Value2 + Fixup.Value.getConstant();
390 MachRelocationEntry MRE;
391 MRE.Word0 = ((Address << 0) |
397 Relocs.push_back(MRE);
399 if (Type == RIT_LocalDifference) {
402 MachRelocationEntry MRE;
403 MRE.Word0 = ((0 << 0) |
409 Relocs.push_back(MRE);
413 void ComputeRelocationInfo(MCAssembler &Asm,
414 MCSectionData::Fixup &Fixup,
415 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
416 std::vector<MachRelocationEntry> &Relocs) {
417 // If this is a local symbol plus an offset or a difference, then we need a
418 // scattered relocation entry.
419 if (Fixup.Value.getSymB()) // a - b
420 return ComputeScatteredRelocationInfo(Asm, Fixup, SymbolMap, Relocs);
421 if (Fixup.Value.getSymA() && Fixup.Value.getConstant())
422 if (!Fixup.Value.getSymA()->isUndefined())
423 return ComputeScatteredRelocationInfo(Asm, Fixup, SymbolMap, Relocs);
426 uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
429 unsigned IsPCRel = 0;
430 unsigned IsExtern = 0;
433 if (Fixup.Value.isAbsolute()) { // constant
434 // SymbolNum of 0 indicates the absolute section.
437 llvm_unreachable("FIXME: Not yet implemented!");
439 const MCSymbol *Symbol = Fixup.Value.getSymA();
440 MCSymbolData *SD = SymbolMap.lookup(Symbol);
442 if (Symbol->isUndefined()) {
444 Index = SD->getIndex();
447 // The index is the section ordinal.
451 for (MCAssembler::iterator it = Asm.begin(),
452 ie = Asm.end(); it != ie; ++it, ++Index)
453 if (&*it == SD->getFragment()->getParent())
455 Value = SD->getFragment()->getAddress() + SD->getOffset();
461 // The value which goes in the fixup is current value of the expression.
462 Fixup.FixedValue = Value + Fixup.Value.getConstant();
464 unsigned Log2Size = Log2_32(Fixup.Size);
465 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
467 // struct relocation_info (8 bytes)
468 MachRelocationEntry MRE;
470 MRE.Word1 = ((Index << 0) |
475 Relocs.push_back(MRE);
478 void BindIndirectSymbols(MCAssembler &Asm,
479 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap) {
480 // This is the point where 'as' creates actual symbols for indirect symbols
481 // (in the following two passes). It would be easier for us to do this
482 // sooner when we see the attribute, but that makes getting the order in the
483 // symbol table much more complicated than it is worth.
485 // FIXME: Revisit this when the dust settles.
487 // Bind non lazy symbol pointers first.
488 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
489 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
490 // FIXME: cast<> support!
491 const MCSectionMachO &Section =
492 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
495 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
496 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
499 MCSymbolData *&Entry = SymbolMap[it->Symbol];
501 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
504 // Then lazy symbol pointers and symbol stubs.
505 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
506 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
507 // FIXME: cast<> support!
508 const MCSectionMachO &Section =
509 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
512 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
513 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
514 Type != MCSectionMachO::S_SYMBOL_STUBS)
517 MCSymbolData *&Entry = SymbolMap[it->Symbol];
519 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
521 // Set the symbol type to undefined lazy, but only on construction.
523 // FIXME: Do not hardcode.
524 Entry->setFlags(Entry->getFlags() | 0x0001);
529 /// ComputeSymbolTable - Compute the symbol table data
531 /// \param StringTable [out] - The string table data.
532 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
534 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
535 std::vector<MachSymbolData> &LocalSymbolData,
536 std::vector<MachSymbolData> &ExternalSymbolData,
537 std::vector<MachSymbolData> &UndefinedSymbolData) {
538 // Build section lookup table.
539 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
541 for (MCAssembler::iterator it = Asm.begin(),
542 ie = Asm.end(); it != ie; ++it, ++Index)
543 SectionIndexMap[&it->getSection()] = Index;
544 assert(Index <= 256 && "Too many sections!");
546 // Index 0 is always the empty string.
547 StringMap<uint64_t> StringIndexMap;
548 StringTable += '\x00';
550 // Build the symbol arrays and the string table, but only for non-local
553 // The particular order that we collect the symbols and create the string
554 // table, then sort the symbols is chosen to match 'as'. Even though it
555 // doesn't matter for correctness, this is important for letting us diff .o
557 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
558 ie = Asm.symbol_end(); it != ie; ++it) {
559 MCSymbol &Symbol = it->getSymbol();
561 // Ignore assembler temporaries.
562 if (it->getSymbol().isTemporary())
565 if (!it->isExternal() && !Symbol.isUndefined())
568 uint64_t &Entry = StringIndexMap[Symbol.getName()];
570 Entry = StringTable.size();
571 StringTable += Symbol.getName();
572 StringTable += '\x00';
577 MSD.StringIndex = Entry;
579 if (Symbol.isUndefined()) {
580 MSD.SectionIndex = 0;
581 UndefinedSymbolData.push_back(MSD);
582 } else if (Symbol.isAbsolute()) {
583 MSD.SectionIndex = 0;
584 ExternalSymbolData.push_back(MSD);
586 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
587 assert(MSD.SectionIndex && "Invalid section index!");
588 ExternalSymbolData.push_back(MSD);
592 // Now add the data for local symbols.
593 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
594 ie = Asm.symbol_end(); it != ie; ++it) {
595 MCSymbol &Symbol = it->getSymbol();
597 // Ignore assembler temporaries.
598 if (it->getSymbol().isTemporary())
601 if (it->isExternal() || Symbol.isUndefined())
604 uint64_t &Entry = StringIndexMap[Symbol.getName()];
606 Entry = StringTable.size();
607 StringTable += Symbol.getName();
608 StringTable += '\x00';
613 MSD.StringIndex = Entry;
615 if (Symbol.isAbsolute()) {
616 MSD.SectionIndex = 0;
617 LocalSymbolData.push_back(MSD);
619 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
620 assert(MSD.SectionIndex && "Invalid section index!");
621 LocalSymbolData.push_back(MSD);
625 // External and undefined symbols are required to be in lexicographic order.
626 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
627 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
629 // Set the symbol indices.
631 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
632 LocalSymbolData[i].SymbolData->setIndex(Index++);
633 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
634 ExternalSymbolData[i].SymbolData->setIndex(Index++);
635 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
636 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
638 // The string table is padded to a multiple of 4.
640 // FIXME: Check to see if this varies per arch.
641 while (StringTable.size() % 4)
642 StringTable += '\x00';
645 void WriteObject(MCAssembler &Asm) {
646 unsigned NumSections = Asm.size();
648 // Compute the symbol -> symbol data map.
650 // FIXME: This should not be here.
651 DenseMap<const MCSymbol*, MCSymbolData *> SymbolMap;
652 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
653 ie = Asm.symbol_end(); it != ie; ++it)
654 SymbolMap[&it->getSymbol()] = it;
656 // Create symbol data for any indirect symbols.
657 BindIndirectSymbols(Asm, SymbolMap);
659 // Compute symbol table information.
660 SmallString<256> StringTable;
661 std::vector<MachSymbolData> LocalSymbolData;
662 std::vector<MachSymbolData> ExternalSymbolData;
663 std::vector<MachSymbolData> UndefinedSymbolData;
664 unsigned NumSymbols = Asm.symbol_size();
666 // No symbol table command is written if there are no symbols.
668 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
669 UndefinedSymbolData);
671 // The section data starts after the header, the segment load command (and
672 // section headers) and the symbol table.
673 unsigned NumLoadCommands = 1;
674 uint64_t LoadCommandsSize =
675 SegmentLoadCommand32Size + NumSections * Section32Size;
677 // Add the symbol table load command sizes, if used.
679 NumLoadCommands += 2;
680 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
683 // Compute the total size of the section data, as well as its file size and
685 uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
686 uint64_t SectionDataSize = 0;
687 uint64_t SectionDataFileSize = 0;
689 for (MCAssembler::iterator it = Asm.begin(),
690 ie = Asm.end(); it != ie; ++it) {
691 MCSectionData &SD = *it;
693 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
695 SectionDataSize = std::max(SectionDataSize,
696 SD.getAddress() + SD.getSize());
697 SectionDataFileSize = std::max(SectionDataFileSize,
698 SD.getAddress() + SD.getFileSize());
701 // The section data is passed to 4 bytes.
703 // FIXME: Is this machine dependent?
704 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
705 SectionDataFileSize += SectionDataPadding;
707 // Write the prolog, starting with the header and load command...
708 WriteHeader32(NumLoadCommands, LoadCommandsSize,
709 Asm.getSubsectionsViaSymbols());
710 WriteSegmentLoadCommand32(NumSections, VMSize,
711 SectionDataStart, SectionDataSize);
713 // ... and then the section headers.
715 // We also compute the section relocations while we do this. Note that
716 // compute relocation info will also update the fixup to have the correct
717 // value; this will be overwrite the appropriate data in the fragment when
719 std::vector<MachRelocationEntry> RelocInfos;
720 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
721 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie;
723 MCSectionData &SD = *it;
725 // The assembler writes relocations in the reverse order they were seen.
727 // FIXME: It is probably more complicated than this.
728 unsigned NumRelocsStart = RelocInfos.size();
729 for (unsigned i = 0, e = SD.fixup_size(); i != e; ++i)
730 ComputeRelocationInfo(Asm, SD.getFixups()[e - i - 1], SymbolMap,
733 unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
734 uint64_t SectionStart = SectionDataStart + SD.getAddress();
735 WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
736 RelocTableEnd += NumRelocs * RelocationInfoSize;
739 // Write the symbol table load command, if used.
741 unsigned FirstLocalSymbol = 0;
742 unsigned NumLocalSymbols = LocalSymbolData.size();
743 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
744 unsigned NumExternalSymbols = ExternalSymbolData.size();
745 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
746 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
747 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
748 unsigned NumSymTabSymbols =
749 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
750 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
751 uint64_t IndirectSymbolOffset = 0;
753 // If used, the indirect symbols are written after the section data.
754 if (NumIndirectSymbols)
755 IndirectSymbolOffset = RelocTableEnd;
757 // The symbol table is written after the indirect symbol data.
758 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
760 // The string table is written after symbol table.
761 uint64_t StringTableOffset =
762 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
763 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
764 StringTableOffset, StringTable.size());
766 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
767 FirstExternalSymbol, NumExternalSymbols,
768 FirstUndefinedSymbol, NumUndefinedSymbols,
769 IndirectSymbolOffset, NumIndirectSymbols);
772 // Write the actual section data.
773 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
774 WriteFileData(OS, *it, *this);
776 // Write the extra padding.
777 WriteZeros(SectionDataPadding);
779 // Write the relocation entries.
780 for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
781 Write32(RelocInfos[i].Word0);
782 Write32(RelocInfos[i].Word1);
785 // Write the symbol table data, if used.
787 // Write the indirect symbol entries.
788 for (MCAssembler::indirect_symbol_iterator
789 it = Asm.indirect_symbol_begin(),
790 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
791 // Indirect symbols in the non lazy symbol pointer section have some
793 const MCSectionMachO &Section =
794 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
796 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
797 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
798 // If this symbol is defined and internal, mark it as such.
799 if (it->Symbol->isDefined() &&
800 !SymbolMap.lookup(it->Symbol)->isExternal()) {
801 uint32_t Flags = ISF_Local;
802 if (it->Symbol->isAbsolute())
803 Flags |= ISF_Absolute;
809 Write32(SymbolMap[it->Symbol]->getIndex());
812 // FIXME: Check that offsets match computed ones.
814 // Write the symbol table entries.
815 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
816 WriteNlist32(LocalSymbolData[i]);
817 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
818 WriteNlist32(ExternalSymbolData[i]);
819 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
820 WriteNlist32(UndefinedSymbolData[i]);
822 // Write the string table.
823 OS << StringTable.str();
830 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
833 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
836 FileSize(~UINT64_C(0))
839 Parent->getFragmentList().push_back(this);
842 MCFragment::~MCFragment() {
845 uint64_t MCFragment::getAddress() const {
846 assert(getParent() && "Missing Section!");
847 return getParent()->getAddress() + Offset;
852 MCSectionData::MCSectionData() : Section(0) {}
854 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
855 : Section(&_Section),
857 Address(~UINT64_C(0)),
859 FileSize(~UINT64_C(0)),
863 A->getSectionList().push_back(this);
866 const MCSectionData::Fixup *
867 MCSectionData::LookupFixup(const MCFragment *Fragment, uint64_t Offset) const {
868 // Use a one level cache to turn the common case of accessing the fixups in
869 // order into O(1) instead of O(N).
870 unsigned i = LastFixupLookup, Count = Fixups.size(), End = Fixups.size();
874 const Fixup &F = Fixups[i];
875 if (F.Fragment == Fragment && F.Offset == Offset) {
890 MCSymbolData::MCSymbolData() : Symbol(*(MCSymbol*)0) {}
892 MCSymbolData::MCSymbolData(MCSymbol &_Symbol, MCFragment *_Fragment,
893 uint64_t _Offset, MCAssembler *A)
894 : Symbol(_Symbol), Fragment(_Fragment), Offset(_Offset),
895 IsExternal(false), IsPrivateExtern(false), Flags(0), Index(0)
898 A->getSymbolList().push_back(this);
903 MCAssembler::MCAssembler(raw_ostream &_OS)
905 SubsectionsViaSymbols(false)
909 MCAssembler::~MCAssembler() {
912 void MCAssembler::LayoutSection(MCSectionData &SD) {
913 uint64_t Address = SD.getAddress();
915 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
918 F.setOffset(Address - SD.getAddress());
920 // Evaluate fragment size.
921 switch (F.getKind()) {
922 case MCFragment::FT_Align: {
923 MCAlignFragment &AF = cast<MCAlignFragment>(F);
925 uint64_t Size = RoundUpToAlignment(Address, AF.getAlignment()) - Address;
926 if (Size > AF.getMaxBytesToEmit())
929 AF.setFileSize(Size);
933 case MCFragment::FT_Data:
934 F.setFileSize(F.getMaxFileSize());
937 case MCFragment::FT_Fill: {
938 MCFillFragment &FF = cast<MCFillFragment>(F);
940 F.setFileSize(F.getMaxFileSize());
942 // If the fill value is constant, thats it.
943 if (FF.getValue().isAbsolute())
946 // Otherwise, add fixups for the values.
947 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
948 MCSectionData::Fixup Fix(F, i * FF.getValueSize(),
949 FF.getValue(),FF.getValueSize());
950 SD.getFixups().push_back(Fix);
955 case MCFragment::FT_Org: {
956 MCOrgFragment &OF = cast<MCOrgFragment>(F);
958 if (!OF.getOffset().isAbsolute())
959 llvm_unreachable("FIXME: Not yet implemented!");
960 uint64_t OrgOffset = OF.getOffset().getConstant();
961 uint64_t Offset = Address - SD.getAddress();
963 // FIXME: We need a way to communicate this error.
964 if (OrgOffset < Offset)
965 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
966 "' (at offset '" + Twine(Offset) + "'");
968 F.setFileSize(OrgOffset - Offset);
973 Address += F.getFileSize();
976 // Set the section sizes.
977 SD.setSize(Address - SD.getAddress());
978 SD.setFileSize(Address - SD.getAddress());
981 /// WriteFileData - Write the \arg F data to the output file.
982 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
983 MachObjectWriter &MOW) {
984 uint64_t Start = OS.tell();
989 // FIXME: Embed in fragments instead?
990 switch (F.getKind()) {
991 case MCFragment::FT_Align: {
992 MCAlignFragment &AF = cast<MCAlignFragment>(F);
993 uint64_t Count = AF.getFileSize() / AF.getValueSize();
995 // FIXME: This error shouldn't actually occur (the front end should emit
996 // multiple .align directives to enforce the semantics it wants), but is
997 // severe enough that we want to report it. How to handle this?
998 if (Count * AF.getValueSize() != AF.getFileSize())
999 llvm_report_error("undefined .align directive, value size '" +
1000 Twine(AF.getValueSize()) +
1001 "' is not a divisor of padding size '" +
1002 Twine(AF.getFileSize()) + "'");
1004 for (uint64_t i = 0; i != Count; ++i) {
1005 switch (AF.getValueSize()) {
1007 assert(0 && "Invalid size!");
1008 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1009 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1010 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1011 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1017 case MCFragment::FT_Data:
1018 OS << cast<MCDataFragment>(F).getContents().str();
1021 case MCFragment::FT_Fill: {
1022 MCFillFragment &FF = cast<MCFillFragment>(F);
1025 if (FF.getValue().isAbsolute())
1026 Value = FF.getValue().getConstant();
1027 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1028 if (!FF.getValue().isAbsolute()) {
1031 // FIXME: Find a better way to write in the fixes.
1032 const MCSectionData::Fixup *Fixup =
1033 F.getParent()->LookupFixup(&F, i * FF.getValueSize());
1034 assert(Fixup && "Missing fixup for fill value!");
1035 Value = Fixup->FixedValue;
1038 switch (FF.getValueSize()) {
1040 assert(0 && "Invalid size!");
1041 case 1: MOW.Write8 (uint8_t (Value)); break;
1042 case 2: MOW.Write16(uint16_t(Value)); break;
1043 case 4: MOW.Write32(uint32_t(Value)); break;
1044 case 8: MOW.Write64(uint64_t(Value)); break;
1050 case MCFragment::FT_Org: {
1051 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1053 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1054 MOW.Write8(uint8_t(OF.getValue()));
1060 assert(OS.tell() - Start == F.getFileSize());
1063 /// WriteFileData - Write the \arg SD data to the output file.
1064 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1065 MachObjectWriter &MOW) {
1066 uint64_t Start = OS.tell();
1069 for (MCSectionData::const_iterator it = SD.begin(),
1070 ie = SD.end(); it != ie; ++it)
1071 WriteFileData(OS, *it, MOW);
1073 // Add section padding.
1074 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1075 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1077 assert(OS.tell() - Start == SD.getFileSize());
1080 void MCAssembler::Finish() {
1081 // Layout the sections and fragments.
1082 uint64_t Address = 0;
1083 MCSectionData *Prev = 0;
1084 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1085 MCSectionData &SD = *it;
1087 // Align this section if necessary by adding padding bytes to the previous
1089 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1090 assert(Prev && "Missing prev section!");
1091 Prev->setFileSize(Prev->getFileSize() + Pad);
1095 // Layout the section fragments and its size.
1096 SD.setAddress(Address);
1098 Address += SD.getFileSize();
1103 // Write the object file.
1104 MachObjectWriter MOW(OS);
1105 MOW.WriteObject(*this);