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/MCExpr.h"
13 #include "llvm/MC/MCSectionMachO.h"
14 #include "llvm/MC/MCSymbol.h"
15 #include "llvm/MC/MCValue.h"
16 #include "llvm/Target/TargetMachOWriterInfo.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/raw_ostream.h"
27 class MachObjectWriter;
29 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
31 // FIXME FIXME FIXME: There are number of places in this file where we convert
32 // what is a 64-bit assembler value used for computation into a value in the
33 // object file, which may truncate it. We should detect that truncation where
34 // invalid and report errors back.
36 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
37 MachObjectWriter &MOW);
39 /// isVirtualSection - Check if this is a section which does not actually exist
40 /// in the object file.
41 static bool isVirtualSection(const MCSection &Section) {
43 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
44 unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
45 return (Type == MCSectionMachO::S_ZEROFILL);
48 class MachObjectWriter {
49 // See <mach-o/loader.h>.
51 Header_Magic32 = 0xFEEDFACE,
52 Header_Magic64 = 0xFEEDFACF
55 static const unsigned Header32Size = 28;
56 static const unsigned Header64Size = 32;
57 static const unsigned SegmentLoadCommand32Size = 56;
58 static const unsigned Section32Size = 68;
59 static const unsigned SymtabLoadCommandSize = 24;
60 static const unsigned DysymtabLoadCommandSize = 80;
61 static const unsigned Nlist32Size = 12;
62 static const unsigned RelocationInfoSize = 8;
69 HF_SubsectionsViaSymbols = 0x2000
72 enum LoadCommandType {
78 // See <mach-o/nlist.h>.
85 enum SymbolTypeFlags {
86 // If any of these bits are set, then the entry is a stab entry number (see
87 // <mach-o/stab.h>. Otherwise the other masks apply.
88 STF_StabsEntryMask = 0xe0,
92 STF_PrivateExtern = 0x10
95 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
97 enum IndirectSymbolFlags {
98 ISF_Local = 0x80000000,
99 ISF_Absolute = 0x40000000
102 /// RelocationFlags - Special flags for addresses.
103 enum RelocationFlags {
104 RF_Scattered = 0x80000000
107 enum RelocationInfoType {
111 RIT_PreboundLazyPointer = 3,
112 RIT_LocalDifference = 4
115 /// MachSymbolData - Helper struct for containing some precomputed information
117 struct MachSymbolData {
118 MCSymbolData *SymbolData;
119 uint64_t StringIndex;
120 uint8_t SectionIndex;
122 // Support lexicographic sorting.
123 bool operator<(const MachSymbolData &RHS) const {
124 const std::string &Name = SymbolData->getSymbol().getName();
125 return Name < RHS.SymbolData->getSymbol().getName();
133 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
134 : OS(_OS), IsLSB(_IsLSB) {
137 /// @name Helper Methods
140 void Write8(uint8_t Value) {
144 void Write16(uint16_t Value) {
146 Write8(uint8_t(Value >> 0));
147 Write8(uint8_t(Value >> 8));
149 Write8(uint8_t(Value >> 8));
150 Write8(uint8_t(Value >> 0));
154 void Write32(uint32_t Value) {
156 Write16(uint16_t(Value >> 0));
157 Write16(uint16_t(Value >> 16));
159 Write16(uint16_t(Value >> 16));
160 Write16(uint16_t(Value >> 0));
164 void Write64(uint64_t Value) {
166 Write32(uint32_t(Value >> 0));
167 Write32(uint32_t(Value >> 32));
169 Write32(uint32_t(Value >> 32));
170 Write32(uint32_t(Value >> 0));
174 void WriteZeros(unsigned N) {
175 const char Zeros[16] = { 0 };
177 for (unsigned i = 0, e = N / 16; i != e; ++i)
178 OS << StringRef(Zeros, 16);
180 OS << StringRef(Zeros, N % 16);
183 void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
186 WriteZeros(ZeroFillSize - Str.size());
191 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
192 bool SubsectionsViaSymbols) {
195 if (SubsectionsViaSymbols)
196 Flags |= HF_SubsectionsViaSymbols;
198 // struct mach_header (28 bytes)
200 uint64_t Start = OS.tell();
203 Write32(Header_Magic32);
205 // FIXME: Support cputype.
206 Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
207 // FIXME: Support cpusubtype.
208 Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
210 Write32(NumLoadCommands); // Object files have a single load command, the
212 Write32(LoadCommandsSize);
215 assert(OS.tell() - Start == Header32Size);
218 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
220 /// \arg NumSections - The number of sections in this segment.
221 /// \arg SectionDataSize - The total size of the sections.
222 void WriteSegmentLoadCommand32(unsigned NumSections,
224 uint64_t SectionDataStartOffset,
225 uint64_t SectionDataSize) {
226 // struct segment_command (56 bytes)
228 uint64_t Start = OS.tell();
231 Write32(LCT_Segment);
232 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
235 Write32(0); // vmaddr
236 Write32(VMSize); // vmsize
237 Write32(SectionDataStartOffset); // file offset
238 Write32(SectionDataSize); // file size
239 Write32(0x7); // maxprot
240 Write32(0x7); // initprot
241 Write32(NumSections);
244 assert(OS.tell() - Start == SegmentLoadCommand32Size);
247 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
248 uint64_t RelocationsStart, unsigned NumRelocations) {
249 // The offset is unused for virtual sections.
250 if (isVirtualSection(SD.getSection())) {
251 assert(SD.getFileSize() == 0 && "Invalid file size!");
255 // struct section (68 bytes)
257 uint64_t Start = OS.tell();
260 // FIXME: cast<> support!
261 const MCSectionMachO &Section =
262 static_cast<const MCSectionMachO&>(SD.getSection());
263 WriteString(Section.getSectionName(), 16);
264 WriteString(Section.getSegmentName(), 16);
265 Write32(SD.getAddress()); // address
266 Write32(SD.getSize()); // size
269 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
270 Write32(Log2_32(SD.getAlignment()));
271 Write32(NumRelocations ? RelocationsStart : 0);
272 Write32(NumRelocations);
273 Write32(Section.getTypeAndAttributes());
274 Write32(0); // reserved1
275 Write32(Section.getStubSize()); // reserved2
277 assert(OS.tell() - Start == Section32Size);
280 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
281 uint32_t StringTableOffset,
282 uint32_t StringTableSize) {
283 // struct symtab_command (24 bytes)
285 uint64_t Start = OS.tell();
289 Write32(SymtabLoadCommandSize);
290 Write32(SymbolOffset);
292 Write32(StringTableOffset);
293 Write32(StringTableSize);
295 assert(OS.tell() - Start == SymtabLoadCommandSize);
298 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
299 uint32_t NumLocalSymbols,
300 uint32_t FirstExternalSymbol,
301 uint32_t NumExternalSymbols,
302 uint32_t FirstUndefinedSymbol,
303 uint32_t NumUndefinedSymbols,
304 uint32_t IndirectSymbolOffset,
305 uint32_t NumIndirectSymbols) {
306 // struct dysymtab_command (80 bytes)
308 uint64_t Start = OS.tell();
311 Write32(LCT_Dysymtab);
312 Write32(DysymtabLoadCommandSize);
313 Write32(FirstLocalSymbol);
314 Write32(NumLocalSymbols);
315 Write32(FirstExternalSymbol);
316 Write32(NumExternalSymbols);
317 Write32(FirstUndefinedSymbol);
318 Write32(NumUndefinedSymbols);
319 Write32(0); // tocoff
321 Write32(0); // modtaboff
322 Write32(0); // nmodtab
323 Write32(0); // extrefsymoff
324 Write32(0); // nextrefsyms
325 Write32(IndirectSymbolOffset);
326 Write32(NumIndirectSymbols);
327 Write32(0); // extreloff
328 Write32(0); // nextrel
329 Write32(0); // locreloff
330 Write32(0); // nlocrel
332 assert(OS.tell() - Start == DysymtabLoadCommandSize);
335 void WriteNlist32(MachSymbolData &MSD) {
336 MCSymbolData &Data = *MSD.SymbolData;
337 const MCSymbol &Symbol = Data.getSymbol();
339 uint16_t Flags = Data.getFlags();
340 uint32_t Address = 0;
342 // Set the N_TYPE bits. See <mach-o/nlist.h>.
344 // FIXME: Are the prebound or indirect fields possible here?
345 if (Symbol.isUndefined())
346 Type = STT_Undefined;
347 else if (Symbol.isAbsolute())
352 // FIXME: Set STAB bits.
354 if (Data.isPrivateExtern())
355 Type |= STF_PrivateExtern;
358 if (Data.isExternal() || Symbol.isUndefined())
359 Type |= STF_External;
361 // Compute the symbol address.
362 if (Symbol.isDefined()) {
363 if (Symbol.isAbsolute()) {
364 llvm_unreachable("FIXME: Not yet implemented!");
366 Address = Data.getFragment()->getAddress() + Data.getOffset();
368 } else if (Data.isCommon()) {
369 // Common symbols are encoded with the size in the address
370 // field, and their alignment in the flags.
371 Address = Data.getCommonSize();
373 // Common alignment is packed into the 'desc' bits.
374 if (unsigned Align = Data.getCommonAlignment()) {
375 unsigned Log2Size = Log2_32(Align);
376 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
378 llvm_report_error("invalid 'common' alignment '" +
380 // FIXME: Keep this mask with the SymbolFlags enumeration.
381 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
385 // struct nlist (12 bytes)
387 Write32(MSD.StringIndex);
389 Write8(MSD.SectionIndex);
391 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
397 struct MachRelocationEntry {
401 void ComputeScatteredRelocationInfo(MCAssembler &Asm,
402 MCSectionData::Fixup &Fixup,
403 const MCValue &Target,
404 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
405 std::vector<MachRelocationEntry> &Relocs) {
406 uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
407 unsigned IsPCRel = 0;
408 unsigned Type = RIT_Vanilla;
411 const MCSymbol *A = Target.getSymA();
412 MCSymbolData *SD = SymbolMap.lookup(A);
413 uint32_t Value = SD->getFragment()->getAddress() + SD->getOffset();
416 if (const MCSymbol *B = Target.getSymB()) {
417 Type = RIT_LocalDifference;
419 MCSymbolData *SD = SymbolMap.lookup(B);
420 Value2 = SD->getFragment()->getAddress() + SD->getOffset();
423 unsigned Log2Size = Log2_32(Fixup.Size);
424 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
426 // The value which goes in the fixup is current value of the expression.
427 Fixup.FixedValue = Value - Value2 + Target.getConstant();
429 MachRelocationEntry MRE;
430 MRE.Word0 = ((Address << 0) |
436 Relocs.push_back(MRE);
438 if (Type == RIT_LocalDifference) {
441 MachRelocationEntry MRE;
442 MRE.Word0 = ((0 << 0) |
448 Relocs.push_back(MRE);
452 void ComputeRelocationInfo(MCAssembler &Asm,
453 MCSectionData::Fixup &Fixup,
454 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
455 std::vector<MachRelocationEntry> &Relocs) {
457 if (!Fixup.Value->EvaluateAsRelocatable(Target))
458 llvm_report_error("expected relocatable expression");
460 // If this is a difference or a local symbol plus an offset, then we need a
461 // scattered relocation entry.
462 if (Target.getSymB() ||
463 (Target.getSymA() && !Target.getSymA()->isUndefined() &&
464 Target.getConstant()))
465 return ComputeScatteredRelocationInfo(Asm, Fixup, Target,
469 uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
472 unsigned IsPCRel = 0;
473 unsigned IsExtern = 0;
476 if (Target.isAbsolute()) { // constant
477 // SymbolNum of 0 indicates the absolute section.
480 llvm_unreachable("FIXME: Not yet implemented!");
482 const MCSymbol *Symbol = Target.getSymA();
483 MCSymbolData *SD = SymbolMap.lookup(Symbol);
485 if (Symbol->isUndefined()) {
487 Index = SD->getIndex();
490 // The index is the section ordinal.
494 for (MCAssembler::iterator it = Asm.begin(),
495 ie = Asm.end(); it != ie; ++it, ++Index)
496 if (&*it == SD->getFragment()->getParent())
498 Value = SD->getFragment()->getAddress() + SD->getOffset();
504 // The value which goes in the fixup is current value of the expression.
505 Fixup.FixedValue = Value + Target.getConstant();
507 unsigned Log2Size = Log2_32(Fixup.Size);
508 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
510 // struct relocation_info (8 bytes)
511 MachRelocationEntry MRE;
513 MRE.Word1 = ((Index << 0) |
518 Relocs.push_back(MRE);
521 void BindIndirectSymbols(MCAssembler &Asm,
522 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap) {
523 // This is the point where 'as' creates actual symbols for indirect symbols
524 // (in the following two passes). It would be easier for us to do this
525 // sooner when we see the attribute, but that makes getting the order in the
526 // symbol table much more complicated than it is worth.
528 // FIXME: Revisit this when the dust settles.
530 // Bind non lazy symbol pointers first.
531 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
532 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
533 // FIXME: cast<> support!
534 const MCSectionMachO &Section =
535 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
538 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
539 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
542 MCSymbolData *&Entry = SymbolMap[it->Symbol];
544 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
547 // Then lazy symbol pointers and symbol stubs.
548 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
549 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
550 // FIXME: cast<> support!
551 const MCSectionMachO &Section =
552 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
555 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
556 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
557 Type != MCSectionMachO::S_SYMBOL_STUBS)
560 MCSymbolData *&Entry = SymbolMap[it->Symbol];
562 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
564 // Set the symbol type to undefined lazy, but only on construction.
566 // FIXME: Do not hardcode.
567 Entry->setFlags(Entry->getFlags() | 0x0001);
572 /// ComputeSymbolTable - Compute the symbol table data
574 /// \param StringTable [out] - The string table data.
575 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
577 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
578 std::vector<MachSymbolData> &LocalSymbolData,
579 std::vector<MachSymbolData> &ExternalSymbolData,
580 std::vector<MachSymbolData> &UndefinedSymbolData) {
581 // Build section lookup table.
582 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
584 for (MCAssembler::iterator it = Asm.begin(),
585 ie = Asm.end(); it != ie; ++it, ++Index)
586 SectionIndexMap[&it->getSection()] = Index;
587 assert(Index <= 256 && "Too many sections!");
589 // Index 0 is always the empty string.
590 StringMap<uint64_t> StringIndexMap;
591 StringTable += '\x00';
593 // Build the symbol arrays and the string table, but only for non-local
596 // The particular order that we collect the symbols and create the string
597 // table, then sort the symbols is chosen to match 'as'. Even though it
598 // doesn't matter for correctness, this is important for letting us diff .o
600 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
601 ie = Asm.symbol_end(); it != ie; ++it) {
602 const MCSymbol &Symbol = it->getSymbol();
604 // Ignore assembler temporaries.
605 if (it->getSymbol().isTemporary())
608 if (!it->isExternal() && !Symbol.isUndefined())
611 uint64_t &Entry = StringIndexMap[Symbol.getName()];
613 Entry = StringTable.size();
614 StringTable += Symbol.getName();
615 StringTable += '\x00';
620 MSD.StringIndex = Entry;
622 if (Symbol.isUndefined()) {
623 MSD.SectionIndex = 0;
624 UndefinedSymbolData.push_back(MSD);
625 } else if (Symbol.isAbsolute()) {
626 MSD.SectionIndex = 0;
627 ExternalSymbolData.push_back(MSD);
629 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
630 assert(MSD.SectionIndex && "Invalid section index!");
631 ExternalSymbolData.push_back(MSD);
635 // Now add the data for local symbols.
636 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
637 ie = Asm.symbol_end(); it != ie; ++it) {
638 const MCSymbol &Symbol = it->getSymbol();
640 // Ignore assembler temporaries.
641 if (it->getSymbol().isTemporary())
644 if (it->isExternal() || Symbol.isUndefined())
647 uint64_t &Entry = StringIndexMap[Symbol.getName()];
649 Entry = StringTable.size();
650 StringTable += Symbol.getName();
651 StringTable += '\x00';
656 MSD.StringIndex = Entry;
658 if (Symbol.isAbsolute()) {
659 MSD.SectionIndex = 0;
660 LocalSymbolData.push_back(MSD);
662 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
663 assert(MSD.SectionIndex && "Invalid section index!");
664 LocalSymbolData.push_back(MSD);
668 // External and undefined symbols are required to be in lexicographic order.
669 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
670 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
672 // Set the symbol indices.
674 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
675 LocalSymbolData[i].SymbolData->setIndex(Index++);
676 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
677 ExternalSymbolData[i].SymbolData->setIndex(Index++);
678 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
679 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
681 // The string table is padded to a multiple of 4.
683 // FIXME: Check to see if this varies per arch.
684 while (StringTable.size() % 4)
685 StringTable += '\x00';
688 void WriteObject(MCAssembler &Asm) {
689 unsigned NumSections = Asm.size();
691 // Compute the symbol -> symbol data map.
693 // FIXME: This should not be here.
694 DenseMap<const MCSymbol*, MCSymbolData *> SymbolMap;
695 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
696 ie = Asm.symbol_end(); it != ie; ++it)
697 SymbolMap[&it->getSymbol()] = it;
699 // Create symbol data for any indirect symbols.
700 BindIndirectSymbols(Asm, SymbolMap);
702 // Compute symbol table information.
703 SmallString<256> StringTable;
704 std::vector<MachSymbolData> LocalSymbolData;
705 std::vector<MachSymbolData> ExternalSymbolData;
706 std::vector<MachSymbolData> UndefinedSymbolData;
707 unsigned NumSymbols = Asm.symbol_size();
709 // No symbol table command is written if there are no symbols.
711 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
712 UndefinedSymbolData);
714 // The section data starts after the header, the segment load command (and
715 // section headers) and the symbol table.
716 unsigned NumLoadCommands = 1;
717 uint64_t LoadCommandsSize =
718 SegmentLoadCommand32Size + NumSections * Section32Size;
720 // Add the symbol table load command sizes, if used.
722 NumLoadCommands += 2;
723 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
726 // Compute the total size of the section data, as well as its file size and
728 uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
729 uint64_t SectionDataSize = 0;
730 uint64_t SectionDataFileSize = 0;
732 for (MCAssembler::iterator it = Asm.begin(),
733 ie = Asm.end(); it != ie; ++it) {
734 MCSectionData &SD = *it;
736 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
738 if (isVirtualSection(SD.getSection()))
741 SectionDataSize = std::max(SectionDataSize,
742 SD.getAddress() + SD.getSize());
743 SectionDataFileSize = std::max(SectionDataFileSize,
744 SD.getAddress() + SD.getFileSize());
747 // The section data is passed to 4 bytes.
749 // FIXME: Is this machine dependent?
750 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
751 SectionDataFileSize += SectionDataPadding;
753 // Write the prolog, starting with the header and load command...
754 WriteHeader32(NumLoadCommands, LoadCommandsSize,
755 Asm.getSubsectionsViaSymbols());
756 WriteSegmentLoadCommand32(NumSections, VMSize,
757 SectionDataStart, SectionDataSize);
759 // ... and then the section headers.
761 // We also compute the section relocations while we do this. Note that
762 // compute relocation info will also update the fixup to have the correct
763 // value; this will be overwrite the appropriate data in the fragment when
765 std::vector<MachRelocationEntry> RelocInfos;
766 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
767 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie;
769 MCSectionData &SD = *it;
771 // The assembler writes relocations in the reverse order they were seen.
773 // FIXME: It is probably more complicated than this.
774 unsigned NumRelocsStart = RelocInfos.size();
775 for (unsigned i = 0, e = SD.fixup_size(); i != e; ++i)
776 ComputeRelocationInfo(Asm, SD.getFixups()[e - i - 1], SymbolMap,
779 unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
780 uint64_t SectionStart = SectionDataStart + SD.getAddress();
781 WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
782 RelocTableEnd += NumRelocs * RelocationInfoSize;
785 // Write the symbol table load command, if used.
787 unsigned FirstLocalSymbol = 0;
788 unsigned NumLocalSymbols = LocalSymbolData.size();
789 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
790 unsigned NumExternalSymbols = ExternalSymbolData.size();
791 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
792 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
793 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
794 unsigned NumSymTabSymbols =
795 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
796 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
797 uint64_t IndirectSymbolOffset = 0;
799 // If used, the indirect symbols are written after the section data.
800 if (NumIndirectSymbols)
801 IndirectSymbolOffset = RelocTableEnd;
803 // The symbol table is written after the indirect symbol data.
804 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
806 // The string table is written after symbol table.
807 uint64_t StringTableOffset =
808 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
809 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
810 StringTableOffset, StringTable.size());
812 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
813 FirstExternalSymbol, NumExternalSymbols,
814 FirstUndefinedSymbol, NumUndefinedSymbols,
815 IndirectSymbolOffset, NumIndirectSymbols);
818 // Write the actual section data.
819 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
820 WriteFileData(OS, *it, *this);
822 // Write the extra padding.
823 WriteZeros(SectionDataPadding);
825 // Write the relocation entries.
826 for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
827 Write32(RelocInfos[i].Word0);
828 Write32(RelocInfos[i].Word1);
831 // Write the symbol table data, if used.
833 // Write the indirect symbol entries.
834 for (MCAssembler::indirect_symbol_iterator
835 it = Asm.indirect_symbol_begin(),
836 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
837 // Indirect symbols in the non lazy symbol pointer section have some
839 const MCSectionMachO &Section =
840 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
842 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
843 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
844 // If this symbol is defined and internal, mark it as such.
845 if (it->Symbol->isDefined() &&
846 !SymbolMap.lookup(it->Symbol)->isExternal()) {
847 uint32_t Flags = ISF_Local;
848 if (it->Symbol->isAbsolute())
849 Flags |= ISF_Absolute;
855 Write32(SymbolMap[it->Symbol]->getIndex());
858 // FIXME: Check that offsets match computed ones.
860 // Write the symbol table entries.
861 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
862 WriteNlist32(LocalSymbolData[i]);
863 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
864 WriteNlist32(ExternalSymbolData[i]);
865 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
866 WriteNlist32(UndefinedSymbolData[i]);
868 // Write the string table.
869 OS << StringTable.str();
876 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
879 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
882 FileSize(~UINT64_C(0))
885 Parent->getFragmentList().push_back(this);
888 MCFragment::~MCFragment() {
891 uint64_t MCFragment::getAddress() const {
892 assert(getParent() && "Missing Section!");
893 return getParent()->getAddress() + Offset;
898 MCSectionData::MCSectionData() : Section(0) {}
900 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
901 : Section(&_Section),
903 Address(~UINT64_C(0)),
905 FileSize(~UINT64_C(0)),
909 A->getSectionList().push_back(this);
912 const MCSectionData::Fixup *
913 MCSectionData::LookupFixup(const MCFragment *Fragment, uint64_t Offset) const {
914 // Use a one level cache to turn the common case of accessing the fixups in
915 // order into O(1) instead of O(N).
916 unsigned i = LastFixupLookup, Count = Fixups.size(), End = Fixups.size();
920 const Fixup &F = Fixups[i];
921 if (F.Fragment == Fragment && F.Offset == Offset) {
936 MCSymbolData::MCSymbolData() : Symbol(0) {}
938 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
939 uint64_t _Offset, MCAssembler *A)
940 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
941 IsExternal(false), IsPrivateExtern(false),
942 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
945 A->getSymbolList().push_back(this);
950 MCAssembler::MCAssembler(MCContext &_Context, raw_ostream &_OS)
951 : Context(_Context), OS(_OS), SubsectionsViaSymbols(false)
955 MCAssembler::~MCAssembler() {
958 void MCAssembler::LayoutSection(MCSectionData &SD) {
959 uint64_t Address = SD.getAddress();
961 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
964 F.setOffset(Address - SD.getAddress());
966 // Evaluate fragment size.
967 switch (F.getKind()) {
968 case MCFragment::FT_Align: {
969 MCAlignFragment &AF = cast<MCAlignFragment>(F);
971 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
972 if (Size > AF.getMaxBytesToEmit())
975 AF.setFileSize(Size);
979 case MCFragment::FT_Data:
980 F.setFileSize(F.getMaxFileSize());
983 case MCFragment::FT_Fill: {
984 MCFillFragment &FF = cast<MCFillFragment>(F);
986 F.setFileSize(F.getMaxFileSize());
989 if (!FF.getValue().EvaluateAsRelocatable(Target))
990 llvm_report_error("expected relocatable expression");
992 // If the fill value is constant, thats it.
993 if (Target.isAbsolute())
996 // Otherwise, add fixups for the values.
997 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
998 MCSectionData::Fixup Fix(F, i * FF.getValueSize(),
999 FF.getValue(),FF.getValueSize());
1000 SD.getFixups().push_back(Fix);
1005 case MCFragment::FT_Org: {
1006 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1009 if (!OF.getOffset().EvaluateAsRelocatable(Target))
1010 llvm_report_error("expected relocatable expression");
1012 if (!Target.isAbsolute())
1013 llvm_unreachable("FIXME: Not yet implemented!");
1014 uint64_t OrgOffset = Target.getConstant();
1015 uint64_t Offset = Address - SD.getAddress();
1017 // FIXME: We need a way to communicate this error.
1018 if (OrgOffset < Offset)
1019 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
1020 "' (at offset '" + Twine(Offset) + "'");
1022 F.setFileSize(OrgOffset - Offset);
1026 case MCFragment::FT_ZeroFill: {
1027 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1029 // Align the fragment offset; it is safe to adjust the offset freely since
1030 // this is only in virtual sections.
1031 uint64_t Aligned = RoundUpToAlignment(Address, ZFF.getAlignment());
1032 F.setOffset(Aligned - SD.getAddress());
1034 // FIXME: This is misnamed.
1035 F.setFileSize(ZFF.getSize());
1040 Address += F.getFileSize();
1043 // Set the section sizes.
1044 SD.setSize(Address - SD.getAddress());
1045 if (isVirtualSection(SD.getSection()))
1048 SD.setFileSize(Address - SD.getAddress());
1051 /// WriteFileData - Write the \arg F data to the output file.
1052 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1053 MachObjectWriter &MOW) {
1054 uint64_t Start = OS.tell();
1059 // FIXME: Embed in fragments instead?
1060 switch (F.getKind()) {
1061 case MCFragment::FT_Align: {
1062 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1063 uint64_t Count = AF.getFileSize() / AF.getValueSize();
1065 // FIXME: This error shouldn't actually occur (the front end should emit
1066 // multiple .align directives to enforce the semantics it wants), but is
1067 // severe enough that we want to report it. How to handle this?
1068 if (Count * AF.getValueSize() != AF.getFileSize())
1069 llvm_report_error("undefined .align directive, value size '" +
1070 Twine(AF.getValueSize()) +
1071 "' is not a divisor of padding size '" +
1072 Twine(AF.getFileSize()) + "'");
1074 for (uint64_t i = 0; i != Count; ++i) {
1075 switch (AF.getValueSize()) {
1077 assert(0 && "Invalid size!");
1078 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1079 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1080 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1081 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1087 case MCFragment::FT_Data:
1088 OS << cast<MCDataFragment>(F).getContents().str();
1091 case MCFragment::FT_Fill: {
1092 MCFillFragment &FF = cast<MCFillFragment>(F);
1097 if (!FF.getValue().EvaluateAsRelocatable(Target))
1098 llvm_report_error("expected relocatable expression");
1100 if (Target.isAbsolute())
1101 Value = Target.getConstant();
1102 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1103 if (!Target.isAbsolute()) {
1106 // FIXME: Find a better way to write in the fixes.
1107 const MCSectionData::Fixup *Fixup =
1108 F.getParent()->LookupFixup(&F, i * FF.getValueSize());
1109 assert(Fixup && "Missing fixup for fill value!");
1110 Value = Fixup->FixedValue;
1113 switch (FF.getValueSize()) {
1115 assert(0 && "Invalid size!");
1116 case 1: MOW.Write8 (uint8_t (Value)); break;
1117 case 2: MOW.Write16(uint16_t(Value)); break;
1118 case 4: MOW.Write32(uint32_t(Value)); break;
1119 case 8: MOW.Write64(uint64_t(Value)); break;
1125 case MCFragment::FT_Org: {
1126 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1128 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1129 MOW.Write8(uint8_t(OF.getValue()));
1134 case MCFragment::FT_ZeroFill: {
1135 assert(0 && "Invalid zero fill fragment in concrete section!");
1140 assert(OS.tell() - Start == F.getFileSize());
1143 /// WriteFileData - Write the \arg SD data to the output file.
1144 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1145 MachObjectWriter &MOW) {
1146 // Ignore virtual sections.
1147 if (isVirtualSection(SD.getSection())) {
1148 assert(SD.getFileSize() == 0);
1152 uint64_t Start = OS.tell();
1155 for (MCSectionData::const_iterator it = SD.begin(),
1156 ie = SD.end(); it != ie; ++it)
1157 WriteFileData(OS, *it, MOW);
1159 // Add section padding.
1160 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1161 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1163 assert(OS.tell() - Start == SD.getFileSize());
1166 void MCAssembler::Finish() {
1167 // Layout the concrete sections and fragments.
1168 uint64_t Address = 0;
1169 MCSectionData *Prev = 0;
1170 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1171 MCSectionData &SD = *it;
1173 // Skip virtual sections.
1174 if (isVirtualSection(SD.getSection()))
1177 // Align this section if necessary by adding padding bytes to the previous
1179 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1180 assert(Prev && "Missing prev section!");
1181 Prev->setFileSize(Prev->getFileSize() + Pad);
1185 // Layout the section fragments and its size.
1186 SD.setAddress(Address);
1188 Address += SD.getFileSize();
1193 // Layout the virtual sections.
1194 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1195 MCSectionData &SD = *it;
1197 if (!isVirtualSection(SD.getSection()))
1200 SD.setAddress(Address);
1202 Address += SD.getSize();
1205 // Write the object file.
1206 MachObjectWriter MOW(OS);
1207 MOW.WriteObject(*this);