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/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/MachO.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Support/Debug.h"
28 #include "../Target/X86/X86FixupKinds.h"
33 class MachObjectWriter;
35 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
37 // FIXME FIXME FIXME: There are number of places in this file where we convert
38 // what is a 64-bit assembler value used for computation into a value in the
39 // object file, which may truncate it. We should detect that truncation where
40 // invalid and report errors back.
42 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
43 MachObjectWriter &MOW);
45 static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW);
47 /// isVirtualSection - Check if this is a section which does not actually exist
48 /// in the object file.
49 static bool isVirtualSection(const MCSection &Section) {
51 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
52 unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
53 return (Type == MCSectionMachO::S_ZEROFILL);
56 static unsigned getFixupKindLog2Size(unsigned Kind) {
58 default: llvm_unreachable("invalid fixup kind!");
59 case X86::reloc_pcrel_1byte:
60 case FK_Data_1: return 0;
61 case FK_Data_2: return 1;
62 case X86::reloc_pcrel_4byte:
63 case X86::reloc_riprel_4byte:
64 case FK_Data_4: return 2;
65 case FK_Data_8: return 3;
69 static bool isFixupKindPCRel(unsigned Kind) {
73 case X86::reloc_pcrel_1byte:
74 case X86::reloc_pcrel_4byte:
75 case X86::reloc_riprel_4byte:
80 class MachObjectWriter {
81 // See <mach-o/loader.h>.
83 Header_Magic32 = 0xFEEDFACE,
84 Header_Magic64 = 0xFEEDFACF
87 static const unsigned Header32Size = 28;
88 static const unsigned Header64Size = 32;
89 static const unsigned SegmentLoadCommand32Size = 56;
90 static const unsigned Section32Size = 68;
91 static const unsigned SymtabLoadCommandSize = 24;
92 static const unsigned DysymtabLoadCommandSize = 80;
93 static const unsigned Nlist32Size = 12;
94 static const unsigned RelocationInfoSize = 8;
101 HF_SubsectionsViaSymbols = 0x2000
104 enum LoadCommandType {
110 // See <mach-o/nlist.h>.
111 enum SymbolTypeType {
112 STT_Undefined = 0x00,
117 enum SymbolTypeFlags {
118 // If any of these bits are set, then the entry is a stab entry number (see
119 // <mach-o/stab.h>. Otherwise the other masks apply.
120 STF_StabsEntryMask = 0xe0,
124 STF_PrivateExtern = 0x10
127 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
129 enum IndirectSymbolFlags {
130 ISF_Local = 0x80000000,
131 ISF_Absolute = 0x40000000
134 /// RelocationFlags - Special flags for addresses.
135 enum RelocationFlags {
136 RF_Scattered = 0x80000000
139 enum RelocationInfoType {
143 RIT_PreboundLazyPointer = 3,
144 RIT_LocalDifference = 4
147 /// MachSymbolData - Helper struct for containing some precomputed information
149 struct MachSymbolData {
150 MCSymbolData *SymbolData;
151 uint64_t StringIndex;
152 uint8_t SectionIndex;
154 // Support lexicographic sorting.
155 bool operator<(const MachSymbolData &RHS) const {
156 const std::string &Name = SymbolData->getSymbol().getName();
157 return Name < RHS.SymbolData->getSymbol().getName();
165 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
166 : OS(_OS), IsLSB(_IsLSB) {
169 /// @name Helper Methods
172 void Write8(uint8_t Value) {
176 void Write16(uint16_t Value) {
178 Write8(uint8_t(Value >> 0));
179 Write8(uint8_t(Value >> 8));
181 Write8(uint8_t(Value >> 8));
182 Write8(uint8_t(Value >> 0));
186 void Write32(uint32_t Value) {
188 Write16(uint16_t(Value >> 0));
189 Write16(uint16_t(Value >> 16));
191 Write16(uint16_t(Value >> 16));
192 Write16(uint16_t(Value >> 0));
196 void Write64(uint64_t Value) {
198 Write32(uint32_t(Value >> 0));
199 Write32(uint32_t(Value >> 32));
201 Write32(uint32_t(Value >> 32));
202 Write32(uint32_t(Value >> 0));
206 void WriteZeros(unsigned N) {
207 const char Zeros[16] = { 0 };
209 for (unsigned i = 0, e = N / 16; i != e; ++i)
210 OS << StringRef(Zeros, 16);
212 OS << StringRef(Zeros, N % 16);
215 void WriteString(StringRef Str, unsigned ZeroFillSize = 0) {
218 WriteZeros(ZeroFillSize - Str.size());
223 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
224 bool SubsectionsViaSymbols) {
227 if (SubsectionsViaSymbols)
228 Flags |= HF_SubsectionsViaSymbols;
230 // struct mach_header (28 bytes)
232 uint64_t Start = OS.tell();
235 Write32(Header_Magic32);
237 // FIXME: Support cputype.
238 Write32(MachO::CPUTypeI386);
239 // FIXME: Support cpusubtype.
240 Write32(MachO::CPUSubType_I386_ALL);
242 Write32(NumLoadCommands); // Object files have a single load command, the
244 Write32(LoadCommandsSize);
247 assert(OS.tell() - Start == Header32Size);
250 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
252 /// \arg NumSections - The number of sections in this segment.
253 /// \arg SectionDataSize - The total size of the sections.
254 void WriteSegmentLoadCommand32(unsigned NumSections,
256 uint64_t SectionDataStartOffset,
257 uint64_t SectionDataSize) {
258 // struct segment_command (56 bytes)
260 uint64_t Start = OS.tell();
263 Write32(LCT_Segment);
264 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
267 Write32(0); // vmaddr
268 Write32(VMSize); // vmsize
269 Write32(SectionDataStartOffset); // file offset
270 Write32(SectionDataSize); // file size
271 Write32(0x7); // maxprot
272 Write32(0x7); // initprot
273 Write32(NumSections);
276 assert(OS.tell() - Start == SegmentLoadCommand32Size);
279 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
280 uint64_t RelocationsStart, unsigned NumRelocations) {
281 // The offset is unused for virtual sections.
282 if (isVirtualSection(SD.getSection())) {
283 assert(SD.getFileSize() == 0 && "Invalid file size!");
287 // struct section (68 bytes)
289 uint64_t Start = OS.tell();
292 // FIXME: cast<> support!
293 const MCSectionMachO &Section =
294 static_cast<const MCSectionMachO&>(SD.getSection());
295 WriteString(Section.getSectionName(), 16);
296 WriteString(Section.getSegmentName(), 16);
297 Write32(SD.getAddress()); // address
298 Write32(SD.getSize()); // size
301 unsigned Flags = Section.getTypeAndAttributes();
302 if (SD.hasInstructions())
303 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
305 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
306 Write32(Log2_32(SD.getAlignment()));
307 Write32(NumRelocations ? RelocationsStart : 0);
308 Write32(NumRelocations);
310 Write32(0); // reserved1
311 Write32(Section.getStubSize()); // reserved2
313 assert(OS.tell() - Start == Section32Size);
316 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
317 uint32_t StringTableOffset,
318 uint32_t StringTableSize) {
319 // struct symtab_command (24 bytes)
321 uint64_t Start = OS.tell();
325 Write32(SymtabLoadCommandSize);
326 Write32(SymbolOffset);
328 Write32(StringTableOffset);
329 Write32(StringTableSize);
331 assert(OS.tell() - Start == SymtabLoadCommandSize);
334 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
335 uint32_t NumLocalSymbols,
336 uint32_t FirstExternalSymbol,
337 uint32_t NumExternalSymbols,
338 uint32_t FirstUndefinedSymbol,
339 uint32_t NumUndefinedSymbols,
340 uint32_t IndirectSymbolOffset,
341 uint32_t NumIndirectSymbols) {
342 // struct dysymtab_command (80 bytes)
344 uint64_t Start = OS.tell();
347 Write32(LCT_Dysymtab);
348 Write32(DysymtabLoadCommandSize);
349 Write32(FirstLocalSymbol);
350 Write32(NumLocalSymbols);
351 Write32(FirstExternalSymbol);
352 Write32(NumExternalSymbols);
353 Write32(FirstUndefinedSymbol);
354 Write32(NumUndefinedSymbols);
355 Write32(0); // tocoff
357 Write32(0); // modtaboff
358 Write32(0); // nmodtab
359 Write32(0); // extrefsymoff
360 Write32(0); // nextrefsyms
361 Write32(IndirectSymbolOffset);
362 Write32(NumIndirectSymbols);
363 Write32(0); // extreloff
364 Write32(0); // nextrel
365 Write32(0); // locreloff
366 Write32(0); // nlocrel
368 assert(OS.tell() - Start == DysymtabLoadCommandSize);
371 void WriteNlist32(MachSymbolData &MSD) {
372 MCSymbolData &Data = *MSD.SymbolData;
373 const MCSymbol &Symbol = Data.getSymbol();
375 uint16_t Flags = Data.getFlags();
376 uint32_t Address = 0;
378 // Set the N_TYPE bits. See <mach-o/nlist.h>.
380 // FIXME: Are the prebound or indirect fields possible here?
381 if (Symbol.isUndefined())
382 Type = STT_Undefined;
383 else if (Symbol.isAbsolute())
388 // FIXME: Set STAB bits.
390 if (Data.isPrivateExtern())
391 Type |= STF_PrivateExtern;
394 if (Data.isExternal() || Symbol.isUndefined())
395 Type |= STF_External;
397 // Compute the symbol address.
398 if (Symbol.isDefined()) {
399 if (Symbol.isAbsolute()) {
400 llvm_unreachable("FIXME: Not yet implemented!");
402 Address = Data.getFragment()->getAddress() + Data.getOffset();
404 } else if (Data.isCommon()) {
405 // Common symbols are encoded with the size in the address
406 // field, and their alignment in the flags.
407 Address = Data.getCommonSize();
409 // Common alignment is packed into the 'desc' bits.
410 if (unsigned Align = Data.getCommonAlignment()) {
411 unsigned Log2Size = Log2_32(Align);
412 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
414 llvm_report_error("invalid 'common' alignment '" +
416 // FIXME: Keep this mask with the SymbolFlags enumeration.
417 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
421 // struct nlist (12 bytes)
423 Write32(MSD.StringIndex);
425 Write8(MSD.SectionIndex);
427 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
433 struct MachRelocationEntry {
437 void ComputeScatteredRelocationInfo(MCAssembler &Asm, MCFragment &Fragment,
439 const MCValue &Target,
440 std::vector<MachRelocationEntry> &Relocs) {
441 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
442 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
443 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
444 unsigned Type = RIT_Vanilla;
447 const MCSymbol *A = Target.getSymA();
448 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
450 if (!A_SD->getFragment())
451 llvm_report_error("symbol '" + A->getName() +
452 "' can not be undefined in a subtraction expression");
454 uint32_t Value = A_SD->getFragment()->getAddress() + A_SD->getOffset();
457 if (const MCSymbol *B = Target.getSymB()) {
458 MCSymbolData *B_SD = &Asm.getSymbolData(*B);
460 if (!B_SD->getFragment())
461 llvm_report_error("symbol '" + B->getName() +
462 "' can not be undefined in a subtraction expression");
464 // Select the appropriate difference relocation type.
466 // Note that there is no longer any semantic difference between these two
467 // relocation types from the linkers point of view, this is done solely
468 // for pedantic compatibility with 'as'.
469 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
470 Value2 = B_SD->getFragment()->getAddress() + B_SD->getOffset();
473 // The value which goes in the fixup is current value of the expression.
474 Fixup.FixedValue = Value - Value2 + Target.getConstant();
476 Fixup.FixedValue -= Address;
478 // If this fixup is a vanilla PC relative relocation for a local label, we
479 // don't need a relocation.
481 // FIXME: Implement proper atom support.
482 if (IsPCRel && Target.getSymA() && Target.getSymA()->isTemporary() &&
486 MachRelocationEntry MRE;
487 MRE.Word0 = ((Address << 0) |
493 Relocs.push_back(MRE);
495 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
496 MachRelocationEntry MRE;
497 MRE.Word0 = ((0 << 0) |
503 Relocs.push_back(MRE);
507 void ComputeRelocationInfo(MCAssembler &Asm, MCDataFragment &Fragment,
509 std::vector<MachRelocationEntry> &Relocs) {
510 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
511 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
514 if (!Fixup.Value->EvaluateAsRelocatable(Target))
515 llvm_report_error("expected relocatable expression");
517 // If this is a difference or a defined symbol plus an offset, then we need
518 // a scattered relocation entry.
519 uint32_t Offset = Target.getConstant();
521 Offset += 1 << Log2Size;
522 if (Target.getSymB() ||
523 (Target.getSymA() && !Target.getSymA()->isUndefined() &&
525 return ComputeScatteredRelocationInfo(Asm, Fragment, Fixup, Target,
529 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
532 unsigned IsExtern = 0;
535 if (Target.isAbsolute()) { // constant
536 // SymbolNum of 0 indicates the absolute section.
538 // FIXME: When is this generated?
541 llvm_unreachable("FIXME: Not yet implemented!");
543 const MCSymbol *Symbol = Target.getSymA();
544 MCSymbolData *SD = &Asm.getSymbolData(*Symbol);
546 if (Symbol->isUndefined()) {
548 Index = SD->getIndex();
551 // The index is the section ordinal.
555 MCAssembler::iterator it = Asm.begin(), ie = Asm.end();
556 for (; it != ie; ++it, ++Index)
557 if (&*it == SD->getFragment()->getParent())
559 assert(it != ie && "Unable to find section index!");
560 Value = SD->getFragment()->getAddress() + SD->getOffset();
566 // The value which goes in the fixup is current value of the expression.
567 Fixup.FixedValue = Value + Target.getConstant();
569 Fixup.FixedValue -= Address;
571 // If this fixup is a vanilla PC relative relocation for a local label, we
572 // don't need a relocation.
574 // FIXME: Implement proper atom support.
575 if (IsPCRel && Target.getSymA() && Target.getSymA()->isTemporary())
578 // struct relocation_info (8 bytes)
579 MachRelocationEntry MRE;
581 MRE.Word1 = ((Index << 0) |
586 Relocs.push_back(MRE);
589 void BindIndirectSymbols(MCAssembler &Asm) {
590 // This is the point where 'as' creates actual symbols for indirect symbols
591 // (in the following two passes). It would be easier for us to do this
592 // sooner when we see the attribute, but that makes getting the order in the
593 // symbol table much more complicated than it is worth.
595 // FIXME: Revisit this when the dust settles.
597 // Bind non lazy symbol pointers first.
598 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
599 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
600 // FIXME: cast<> support!
601 const MCSectionMachO &Section =
602 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
605 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
606 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
609 Asm.getOrCreateSymbolData(*it->Symbol);
612 // Then lazy symbol pointers and symbol stubs.
613 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
614 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
615 // FIXME: cast<> support!
616 const MCSectionMachO &Section =
617 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
620 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
621 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
622 Type != MCSectionMachO::S_SYMBOL_STUBS)
625 // Set the symbol type to undefined lazy, but only on construction.
627 // FIXME: Do not hardcode.
629 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
631 Entry.setFlags(Entry.getFlags() | 0x0001);
635 /// ComputeSymbolTable - Compute the symbol table data
637 /// \param StringTable [out] - The string table data.
638 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
640 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
641 std::vector<MachSymbolData> &LocalSymbolData,
642 std::vector<MachSymbolData> &ExternalSymbolData,
643 std::vector<MachSymbolData> &UndefinedSymbolData) {
644 // Build section lookup table.
645 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
647 for (MCAssembler::iterator it = Asm.begin(),
648 ie = Asm.end(); it != ie; ++it, ++Index)
649 SectionIndexMap[&it->getSection()] = Index;
650 assert(Index <= 256 && "Too many sections!");
652 // Index 0 is always the empty string.
653 StringMap<uint64_t> StringIndexMap;
654 StringTable += '\x00';
656 // Build the symbol arrays and the string table, but only for non-local
659 // The particular order that we collect the symbols and create the string
660 // table, then sort the symbols is chosen to match 'as'. Even though it
661 // doesn't matter for correctness, this is important for letting us diff .o
663 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
664 ie = Asm.symbol_end(); it != ie; ++it) {
665 const MCSymbol &Symbol = it->getSymbol();
667 // Ignore assembler temporaries.
668 if (it->getSymbol().isTemporary())
671 if (!it->isExternal() && !Symbol.isUndefined())
674 uint64_t &Entry = StringIndexMap[Symbol.getName()];
676 Entry = StringTable.size();
677 StringTable += Symbol.getName();
678 StringTable += '\x00';
683 MSD.StringIndex = Entry;
685 if (Symbol.isUndefined()) {
686 MSD.SectionIndex = 0;
687 UndefinedSymbolData.push_back(MSD);
688 } else if (Symbol.isAbsolute()) {
689 MSD.SectionIndex = 0;
690 ExternalSymbolData.push_back(MSD);
692 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
693 assert(MSD.SectionIndex && "Invalid section index!");
694 ExternalSymbolData.push_back(MSD);
698 // Now add the data for local symbols.
699 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
700 ie = Asm.symbol_end(); it != ie; ++it) {
701 const MCSymbol &Symbol = it->getSymbol();
703 // Ignore assembler temporaries.
704 if (it->getSymbol().isTemporary())
707 if (it->isExternal() || Symbol.isUndefined())
710 uint64_t &Entry = StringIndexMap[Symbol.getName()];
712 Entry = StringTable.size();
713 StringTable += Symbol.getName();
714 StringTable += '\x00';
719 MSD.StringIndex = Entry;
721 if (Symbol.isAbsolute()) {
722 MSD.SectionIndex = 0;
723 LocalSymbolData.push_back(MSD);
725 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
726 assert(MSD.SectionIndex && "Invalid section index!");
727 LocalSymbolData.push_back(MSD);
731 // External and undefined symbols are required to be in lexicographic order.
732 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
733 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
735 // Set the symbol indices.
737 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
738 LocalSymbolData[i].SymbolData->setIndex(Index++);
739 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
740 ExternalSymbolData[i].SymbolData->setIndex(Index++);
741 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
742 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
744 // The string table is padded to a multiple of 4.
745 while (StringTable.size() % 4)
746 StringTable += '\x00';
749 void WriteObject(MCAssembler &Asm) {
750 unsigned NumSections = Asm.size();
752 // Create symbol data for any indirect symbols.
753 BindIndirectSymbols(Asm);
755 // Compute symbol table information.
756 SmallString<256> StringTable;
757 std::vector<MachSymbolData> LocalSymbolData;
758 std::vector<MachSymbolData> ExternalSymbolData;
759 std::vector<MachSymbolData> UndefinedSymbolData;
760 unsigned NumSymbols = Asm.symbol_size();
762 // No symbol table command is written if there are no symbols.
764 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
765 UndefinedSymbolData);
767 // The section data starts after the header, the segment load command (and
768 // section headers) and the symbol table.
769 unsigned NumLoadCommands = 1;
770 uint64_t LoadCommandsSize =
771 SegmentLoadCommand32Size + NumSections * Section32Size;
773 // Add the symbol table load command sizes, if used.
775 NumLoadCommands += 2;
776 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
779 // Compute the total size of the section data, as well as its file size and
781 uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
782 uint64_t SectionDataSize = 0;
783 uint64_t SectionDataFileSize = 0;
785 for (MCAssembler::iterator it = Asm.begin(),
786 ie = Asm.end(); it != ie; ++it) {
787 MCSectionData &SD = *it;
789 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
791 if (isVirtualSection(SD.getSection()))
794 SectionDataSize = std::max(SectionDataSize,
795 SD.getAddress() + SD.getSize());
796 SectionDataFileSize = std::max(SectionDataFileSize,
797 SD.getAddress() + SD.getFileSize());
800 // The section data is padded to 4 bytes.
802 // FIXME: Is this machine dependent?
803 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
804 SectionDataFileSize += SectionDataPadding;
806 // Write the prolog, starting with the header and load command...
807 WriteHeader32(NumLoadCommands, LoadCommandsSize,
808 Asm.getSubsectionsViaSymbols());
809 WriteSegmentLoadCommand32(NumSections, VMSize,
810 SectionDataStart, SectionDataSize);
812 // ... and then the section headers.
814 // We also compute the section relocations while we do this. Note that
815 // computing relocation info will also update the fixup to have the correct
816 // value; this will overwrite the appropriate data in the fragment when it
818 std::vector<MachRelocationEntry> RelocInfos;
819 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
820 for (MCAssembler::iterator it = Asm.begin(),
821 ie = Asm.end(); it != ie; ++it) {
822 MCSectionData &SD = *it;
824 // The assembler writes relocations in the reverse order they were seen.
826 // FIXME: It is probably more complicated than this.
827 unsigned NumRelocsStart = RelocInfos.size();
828 for (MCSectionData::reverse_iterator it2 = SD.rbegin(),
829 ie2 = SD.rend(); it2 != ie2; ++it2)
830 if (MCDataFragment *DF = dyn_cast<MCDataFragment>(&*it2))
831 for (unsigned i = 0, e = DF->fixup_size(); i != e; ++i)
832 ComputeRelocationInfo(Asm, *DF, DF->getFixups()[e - i - 1],
835 unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
836 uint64_t SectionStart = SectionDataStart + SD.getAddress();
837 WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
838 RelocTableEnd += NumRelocs * RelocationInfoSize;
841 // Write the symbol table load command, if used.
843 unsigned FirstLocalSymbol = 0;
844 unsigned NumLocalSymbols = LocalSymbolData.size();
845 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
846 unsigned NumExternalSymbols = ExternalSymbolData.size();
847 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
848 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
849 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
850 unsigned NumSymTabSymbols =
851 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
852 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
853 uint64_t IndirectSymbolOffset = 0;
855 // If used, the indirect symbols are written after the section data.
856 if (NumIndirectSymbols)
857 IndirectSymbolOffset = RelocTableEnd;
859 // The symbol table is written after the indirect symbol data.
860 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
862 // The string table is written after symbol table.
863 uint64_t StringTableOffset =
864 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
865 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
866 StringTableOffset, StringTable.size());
868 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
869 FirstExternalSymbol, NumExternalSymbols,
870 FirstUndefinedSymbol, NumUndefinedSymbols,
871 IndirectSymbolOffset, NumIndirectSymbols);
874 // Write the actual section data.
875 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
876 WriteFileData(OS, *it, *this);
878 // Write the extra padding.
879 WriteZeros(SectionDataPadding);
881 // Write the relocation entries.
882 for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
883 Write32(RelocInfos[i].Word0);
884 Write32(RelocInfos[i].Word1);
887 // Write the symbol table data, if used.
889 // Write the indirect symbol entries.
890 for (MCAssembler::indirect_symbol_iterator
891 it = Asm.indirect_symbol_begin(),
892 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
893 // Indirect symbols in the non lazy symbol pointer section have some
895 const MCSectionMachO &Section =
896 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
898 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
899 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
900 // If this symbol is defined and internal, mark it as such.
901 if (it->Symbol->isDefined() &&
902 !Asm.getSymbolData(*it->Symbol).isExternal()) {
903 uint32_t Flags = ISF_Local;
904 if (it->Symbol->isAbsolute())
905 Flags |= ISF_Absolute;
911 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
914 // FIXME: Check that offsets match computed ones.
916 // Write the symbol table entries.
917 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
918 WriteNlist32(LocalSymbolData[i]);
919 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
920 WriteNlist32(ExternalSymbolData[i]);
921 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
922 WriteNlist32(UndefinedSymbolData[i]);
924 // Write the string table.
925 OS << StringTable.str();
929 void ApplyFixup(const MCAsmFixup &Fixup, MCDataFragment &DF) {
930 unsigned Size = 1 << getFixupKindLog2Size(Fixup.Kind);
932 // FIXME: Endianness assumption.
933 assert(Fixup.Offset + Size <= DF.getContents().size() &&
934 "Invalid fixup offset!");
935 for (unsigned i = 0; i != Size; ++i)
936 DF.getContents()[Fixup.Offset + i] = uint8_t(Fixup.FixedValue >> (i * 8));
942 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
945 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
948 FileSize(~UINT64_C(0))
951 Parent->getFragmentList().push_back(this);
954 MCFragment::~MCFragment() {
957 uint64_t MCFragment::getAddress() const {
958 assert(getParent() && "Missing Section!");
959 return getParent()->getAddress() + Offset;
964 MCSectionData::MCSectionData() : Section(0) {}
966 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
967 : Section(&_Section),
969 Address(~UINT64_C(0)),
971 FileSize(~UINT64_C(0)),
972 HasInstructions(false)
975 A->getSectionList().push_back(this);
980 MCSymbolData::MCSymbolData() : Symbol(0) {}
982 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
983 uint64_t _Offset, MCAssembler *A)
984 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
985 IsExternal(false), IsPrivateExtern(false),
986 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
989 A->getSymbolList().push_back(this);
994 MCAssembler::MCAssembler(MCContext &_Context, raw_ostream &_OS)
995 : Context(_Context), OS(_OS), SubsectionsViaSymbols(false)
999 MCAssembler::~MCAssembler() {
1002 void MCAssembler::LayoutSection(MCSectionData &SD) {
1003 uint64_t Address = SD.getAddress();
1005 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
1006 MCFragment &F = *it;
1008 F.setOffset(Address - SD.getAddress());
1010 // Evaluate fragment size.
1011 switch (F.getKind()) {
1012 case MCFragment::FT_Align: {
1013 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1015 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
1016 if (Size > AF.getMaxBytesToEmit())
1019 AF.setFileSize(Size);
1023 case MCFragment::FT_Data:
1024 case MCFragment::FT_Fill:
1025 F.setFileSize(F.getMaxFileSize());
1028 case MCFragment::FT_Org: {
1029 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1032 if (!OF.getOffset().EvaluateAsRelocatable(Target))
1033 llvm_report_error("expected relocatable expression");
1035 if (!Target.isAbsolute())
1036 llvm_unreachable("FIXME: Not yet implemented!");
1037 uint64_t OrgOffset = Target.getConstant();
1038 uint64_t Offset = Address - SD.getAddress();
1040 // FIXME: We need a way to communicate this error.
1041 if (OrgOffset < Offset)
1042 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
1043 "' (at offset '" + Twine(Offset) + "'");
1045 F.setFileSize(OrgOffset - Offset);
1049 case MCFragment::FT_ZeroFill: {
1050 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1052 // Align the fragment offset; it is safe to adjust the offset freely since
1053 // this is only in virtual sections.
1054 Address = RoundUpToAlignment(Address, ZFF.getAlignment());
1055 F.setOffset(Address - SD.getAddress());
1057 // FIXME: This is misnamed.
1058 F.setFileSize(ZFF.getSize());
1063 Address += F.getFileSize();
1066 // Set the section sizes.
1067 SD.setSize(Address - SD.getAddress());
1068 if (isVirtualSection(SD.getSection()))
1071 SD.setFileSize(Address - SD.getAddress());
1074 /// WriteNopData - Write optimal nops to the output file for the \arg Count
1075 /// bytes. This returns the number of bytes written. It may return 0 if
1076 /// the \arg Count is more than the maximum optimal nops.
1078 /// FIXME this is X86 32-bit specific and should move to a better place.
1079 static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW) {
1080 static const uint8_t Nops[16][16] = {
1088 {0x0f, 0x1f, 0x40, 0x00},
1089 // nopl 0(%[re]ax,%[re]ax,1)
1090 {0x0f, 0x1f, 0x44, 0x00, 0x00},
1091 // nopw 0(%[re]ax,%[re]ax,1)
1092 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1094 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1095 // nopl 0L(%[re]ax,%[re]ax,1)
1096 {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1097 // nopw 0L(%[re]ax,%[re]ax,1)
1098 {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1099 // nopw %cs:0L(%[re]ax,%[re]ax,1)
1100 {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1101 // nopl 0(%[re]ax,%[re]ax,1)
1102 // nopw 0(%[re]ax,%[re]ax,1)
1103 {0x0f, 0x1f, 0x44, 0x00, 0x00,
1104 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1105 // nopw 0(%[re]ax,%[re]ax,1)
1106 // nopw 0(%[re]ax,%[re]ax,1)
1107 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1108 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1109 // nopw 0(%[re]ax,%[re]ax,1)
1110 // nopl 0L(%[re]ax) */
1111 {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1112 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1115 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1116 0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1118 // nopl 0L(%[re]ax,%[re]ax,1)
1119 {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1120 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
1126 for (uint64_t i = 0; i < Count; i++)
1127 MOW.Write8 (uint8_t(Nops[Count - 1][i]));
1132 /// WriteFileData - Write the \arg F data to the output file.
1133 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1134 MachObjectWriter &MOW) {
1135 uint64_t Start = OS.tell();
1140 // FIXME: Embed in fragments instead?
1141 switch (F.getKind()) {
1142 case MCFragment::FT_Align: {
1143 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1144 uint64_t Count = AF.getFileSize() / AF.getValueSize();
1146 // FIXME: This error shouldn't actually occur (the front end should emit
1147 // multiple .align directives to enforce the semantics it wants), but is
1148 // severe enough that we want to report it. How to handle this?
1149 if (Count * AF.getValueSize() != AF.getFileSize())
1150 llvm_report_error("undefined .align directive, value size '" +
1151 Twine(AF.getValueSize()) +
1152 "' is not a divisor of padding size '" +
1153 Twine(AF.getFileSize()) + "'");
1155 // See if we are aligning with nops, and if so do that first to try to fill
1156 // the Count bytes. Then if that did not fill any bytes or there are any
1157 // bytes left to fill use the the Value and ValueSize to fill the rest.
1158 if (AF.getEmitNops()) {
1159 uint64_t NopByteCount = WriteNopData(Count, MOW);
1160 Count -= NopByteCount;
1163 for (uint64_t i = 0; i != Count; ++i) {
1164 switch (AF.getValueSize()) {
1166 assert(0 && "Invalid size!");
1167 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1168 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1169 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1170 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1176 case MCFragment::FT_Data: {
1177 MCDataFragment &DF = cast<MCDataFragment>(F);
1179 // Apply the fixups.
1181 // FIXME: Move elsewhere.
1182 for (MCDataFragment::const_fixup_iterator it = DF.fixup_begin(),
1183 ie = DF.fixup_end(); it != ie; ++it)
1184 MOW.ApplyFixup(*it, DF);
1186 OS << cast<MCDataFragment>(F).getContents().str();
1190 case MCFragment::FT_Fill: {
1191 MCFillFragment &FF = cast<MCFillFragment>(F);
1192 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1193 switch (FF.getValueSize()) {
1195 assert(0 && "Invalid size!");
1196 case 1: MOW.Write8 (uint8_t (FF.getValue())); break;
1197 case 2: MOW.Write16(uint16_t(FF.getValue())); break;
1198 case 4: MOW.Write32(uint32_t(FF.getValue())); break;
1199 case 8: MOW.Write64(uint64_t(FF.getValue())); break;
1205 case MCFragment::FT_Org: {
1206 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1208 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1209 MOW.Write8(uint8_t(OF.getValue()));
1214 case MCFragment::FT_ZeroFill: {
1215 assert(0 && "Invalid zero fill fragment in concrete section!");
1220 assert(OS.tell() - Start == F.getFileSize());
1223 /// WriteFileData - Write the \arg SD data to the output file.
1224 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1225 MachObjectWriter &MOW) {
1226 // Ignore virtual sections.
1227 if (isVirtualSection(SD.getSection())) {
1228 assert(SD.getFileSize() == 0);
1232 uint64_t Start = OS.tell();
1235 for (MCSectionData::const_iterator it = SD.begin(),
1236 ie = SD.end(); it != ie; ++it)
1237 WriteFileData(OS, *it, MOW);
1239 // Add section padding.
1240 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1241 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1243 assert(OS.tell() - Start == SD.getFileSize());
1246 void MCAssembler::Finish() {
1247 DEBUG_WITH_TYPE("mc-dump", {
1248 llvm::errs() << "assembler backend - pre-layout\n--\n";
1251 // Layout the concrete sections and fragments.
1252 uint64_t Address = 0;
1253 MCSectionData *Prev = 0;
1254 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1255 MCSectionData &SD = *it;
1257 // Skip virtual sections.
1258 if (isVirtualSection(SD.getSection()))
1261 // Align this section if necessary by adding padding bytes to the previous
1263 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1264 assert(Prev && "Missing prev section!");
1265 Prev->setFileSize(Prev->getFileSize() + Pad);
1269 // Layout the section fragments and its size.
1270 SD.setAddress(Address);
1272 Address += SD.getFileSize();
1277 // Layout the virtual sections.
1278 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1279 MCSectionData &SD = *it;
1281 if (!isVirtualSection(SD.getSection()))
1284 // Align this section if necessary by adding padding bytes to the previous
1286 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
1289 SD.setAddress(Address);
1291 Address += SD.getSize();
1295 DEBUG_WITH_TYPE("mc-dump", {
1296 llvm::errs() << "assembler backend - post-layout\n--\n";
1299 // Write the object file.
1300 MachObjectWriter MOW(OS);
1301 MOW.WriteObject(*this);
1307 // Debugging methods
1311 raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
1312 OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
1313 << " Kind:" << AF.Kind << ">";
1319 void MCFragment::dump() {
1320 raw_ostream &OS = llvm::errs();
1322 OS << "<MCFragment " << (void*) this << " Offset:" << Offset
1323 << " FileSize:" << FileSize;
1328 void MCAlignFragment::dump() {
1329 raw_ostream &OS = llvm::errs();
1331 OS << "<MCAlignFragment ";
1332 this->MCFragment::dump();
1334 OS << " Alignment:" << getAlignment()
1335 << " Value:" << getValue() << " ValueSize:" << getValueSize()
1336 << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
1339 void MCDataFragment::dump() {
1340 raw_ostream &OS = llvm::errs();
1342 OS << "<MCDataFragment ";
1343 this->MCFragment::dump();
1345 OS << " Contents:[";
1346 for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
1348 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1350 OS << "] (" << getContents().size() << " bytes)";
1352 if (!getFixups().empty()) {
1355 for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
1356 if (it != fixup_begin()) OS << ",\n ";
1365 void MCFillFragment::dump() {
1366 raw_ostream &OS = llvm::errs();
1368 OS << "<MCFillFragment ";
1369 this->MCFragment::dump();
1371 OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
1372 << " Count:" << getCount() << ">";
1375 void MCOrgFragment::dump() {
1376 raw_ostream &OS = llvm::errs();
1378 OS << "<MCOrgFragment ";
1379 this->MCFragment::dump();
1381 OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
1384 void MCZeroFillFragment::dump() {
1385 raw_ostream &OS = llvm::errs();
1387 OS << "<MCZeroFillFragment ";
1388 this->MCFragment::dump();
1390 OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
1393 void MCSectionData::dump() {
1394 raw_ostream &OS = llvm::errs();
1396 OS << "<MCSectionData";
1397 OS << " Alignment:" << getAlignment() << " Address:" << Address
1398 << " Size:" << Size << " FileSize:" << FileSize
1399 << " Fragments:[\n ";
1400 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1401 if (it != begin()) OS << ",\n ";
1407 void MCSymbolData::dump() {
1408 raw_ostream &OS = llvm::errs();
1410 OS << "<MCSymbolData Symbol:" << getSymbol()
1411 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1412 << " Flags:" << getFlags() << " Index:" << getIndex();
1414 OS << " (common, size:" << getCommonSize()
1415 << " align: " << getCommonAlignment() << ")";
1417 OS << " (external)";
1418 if (isPrivateExtern())
1419 OS << " (private extern)";
1423 void MCAssembler::dump() {
1424 raw_ostream &OS = llvm::errs();
1426 OS << "<MCAssembler\n";
1427 OS << " Sections:[\n ";
1428 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1429 if (it != begin()) OS << ",\n ";
1435 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1436 if (it != symbol_begin()) OS << ",\n ";