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/StringMap.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MachO.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(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(MachO::CPUTypeI386);
207 // FIXME: Support cpusubtype.
208 Write32(MachO::CPUSubType_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 unsigned Flags = Section.getTypeAndAttributes();
270 if (SD.hasInstructions())
271 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
273 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
274 Write32(Log2_32(SD.getAlignment()));
275 Write32(NumRelocations ? RelocationsStart : 0);
276 Write32(NumRelocations);
278 Write32(0); // reserved1
279 Write32(Section.getStubSize()); // reserved2
281 assert(OS.tell() - Start == Section32Size);
284 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
285 uint32_t StringTableOffset,
286 uint32_t StringTableSize) {
287 // struct symtab_command (24 bytes)
289 uint64_t Start = OS.tell();
293 Write32(SymtabLoadCommandSize);
294 Write32(SymbolOffset);
296 Write32(StringTableOffset);
297 Write32(StringTableSize);
299 assert(OS.tell() - Start == SymtabLoadCommandSize);
302 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
303 uint32_t NumLocalSymbols,
304 uint32_t FirstExternalSymbol,
305 uint32_t NumExternalSymbols,
306 uint32_t FirstUndefinedSymbol,
307 uint32_t NumUndefinedSymbols,
308 uint32_t IndirectSymbolOffset,
309 uint32_t NumIndirectSymbols) {
310 // struct dysymtab_command (80 bytes)
312 uint64_t Start = OS.tell();
315 Write32(LCT_Dysymtab);
316 Write32(DysymtabLoadCommandSize);
317 Write32(FirstLocalSymbol);
318 Write32(NumLocalSymbols);
319 Write32(FirstExternalSymbol);
320 Write32(NumExternalSymbols);
321 Write32(FirstUndefinedSymbol);
322 Write32(NumUndefinedSymbols);
323 Write32(0); // tocoff
325 Write32(0); // modtaboff
326 Write32(0); // nmodtab
327 Write32(0); // extrefsymoff
328 Write32(0); // nextrefsyms
329 Write32(IndirectSymbolOffset);
330 Write32(NumIndirectSymbols);
331 Write32(0); // extreloff
332 Write32(0); // nextrel
333 Write32(0); // locreloff
334 Write32(0); // nlocrel
336 assert(OS.tell() - Start == DysymtabLoadCommandSize);
339 void WriteNlist32(MachSymbolData &MSD) {
340 MCSymbolData &Data = *MSD.SymbolData;
341 const MCSymbol &Symbol = Data.getSymbol();
343 uint16_t Flags = Data.getFlags();
344 uint32_t Address = 0;
346 // Set the N_TYPE bits. See <mach-o/nlist.h>.
348 // FIXME: Are the prebound or indirect fields possible here?
349 if (Symbol.isUndefined())
350 Type = STT_Undefined;
351 else if (Symbol.isAbsolute())
356 // FIXME: Set STAB bits.
358 if (Data.isPrivateExtern())
359 Type |= STF_PrivateExtern;
362 if (Data.isExternal() || Symbol.isUndefined())
363 Type |= STF_External;
365 // Compute the symbol address.
366 if (Symbol.isDefined()) {
367 if (Symbol.isAbsolute()) {
368 llvm_unreachable("FIXME: Not yet implemented!");
370 Address = Data.getFragment()->getAddress() + Data.getOffset();
372 } else if (Data.isCommon()) {
373 // Common symbols are encoded with the size in the address
374 // field, and their alignment in the flags.
375 Address = Data.getCommonSize();
377 // Common alignment is packed into the 'desc' bits.
378 if (unsigned Align = Data.getCommonAlignment()) {
379 unsigned Log2Size = Log2_32(Align);
380 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
382 llvm_report_error("invalid 'common' alignment '" +
384 // FIXME: Keep this mask with the SymbolFlags enumeration.
385 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
389 // struct nlist (12 bytes)
391 Write32(MSD.StringIndex);
393 Write8(MSD.SectionIndex);
395 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
401 struct MachRelocationEntry {
405 void ComputeScatteredRelocationInfo(MCAssembler &Asm, MCFragment &Fragment,
407 const MCValue &Target,
408 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
409 std::vector<MachRelocationEntry> &Relocs) {
410 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
411 unsigned IsPCRel = 0;
412 unsigned Type = RIT_Vanilla;
415 const MCSymbol *A = Target.getSymA();
416 MCSymbolData *SD = SymbolMap.lookup(A);
417 uint32_t Value = SD->getFragment()->getAddress() + SD->getOffset();
420 if (const MCSymbol *B = Target.getSymB()) {
421 Type = RIT_LocalDifference;
423 MCSymbolData *SD = SymbolMap.lookup(B);
424 Value2 = SD->getFragment()->getAddress() + SD->getOffset();
427 unsigned Log2Size = Log2_32(Fixup.Size);
428 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
430 // The value which goes in the fixup is current value of the expression.
431 Fixup.FixedValue = Value - Value2 + Target.getConstant();
433 MachRelocationEntry MRE;
434 MRE.Word0 = ((Address << 0) |
440 Relocs.push_back(MRE);
442 if (Type == RIT_LocalDifference) {
445 MachRelocationEntry MRE;
446 MRE.Word0 = ((0 << 0) |
452 Relocs.push_back(MRE);
456 void ComputeRelocationInfo(MCAssembler &Asm, MCFragment &Fragment,
458 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
459 std::vector<MachRelocationEntry> &Relocs) {
461 if (!Fixup.Value->EvaluateAsRelocatable(Target))
462 llvm_report_error("expected relocatable expression");
464 // If this is a difference or a local symbol plus an offset, then we need a
465 // scattered relocation entry.
466 if (Target.getSymB() ||
467 (Target.getSymA() && !Target.getSymA()->isUndefined() &&
468 Target.getConstant()))
469 return ComputeScatteredRelocationInfo(Asm, Fragment, Fixup, Target,
473 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
476 unsigned IsPCRel = 0;
477 unsigned IsExtern = 0;
480 if (Target.isAbsolute()) { // constant
481 // SymbolNum of 0 indicates the absolute section.
484 llvm_unreachable("FIXME: Not yet implemented!");
486 const MCSymbol *Symbol = Target.getSymA();
487 MCSymbolData *SD = SymbolMap.lookup(Symbol);
489 if (Symbol->isUndefined()) {
491 Index = SD->getIndex();
494 // The index is the section ordinal.
498 for (MCAssembler::iterator it = Asm.begin(),
499 ie = Asm.end(); it != ie; ++it, ++Index)
500 if (&*it == SD->getFragment()->getParent())
502 Value = SD->getFragment()->getAddress() + SD->getOffset();
508 // The value which goes in the fixup is current value of the expression.
509 Fixup.FixedValue = Value + Target.getConstant();
511 unsigned Log2Size = Log2_32(Fixup.Size);
512 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
514 // struct relocation_info (8 bytes)
515 MachRelocationEntry MRE;
517 MRE.Word1 = ((Index << 0) |
522 Relocs.push_back(MRE);
525 void BindIndirectSymbols(MCAssembler &Asm,
526 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap) {
527 // This is the point where 'as' creates actual symbols for indirect symbols
528 // (in the following two passes). It would be easier for us to do this
529 // sooner when we see the attribute, but that makes getting the order in the
530 // symbol table much more complicated than it is worth.
532 // FIXME: Revisit this when the dust settles.
534 // Bind non lazy symbol pointers first.
535 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
536 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
537 // FIXME: cast<> support!
538 const MCSectionMachO &Section =
539 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
542 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
543 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
546 MCSymbolData *&Entry = SymbolMap[it->Symbol];
548 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
551 // Then lazy symbol pointers and symbol stubs.
552 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
553 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
554 // FIXME: cast<> support!
555 const MCSectionMachO &Section =
556 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
559 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
560 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
561 Type != MCSectionMachO::S_SYMBOL_STUBS)
564 MCSymbolData *&Entry = SymbolMap[it->Symbol];
566 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
568 // Set the symbol type to undefined lazy, but only on construction.
570 // FIXME: Do not hardcode.
571 Entry->setFlags(Entry->getFlags() | 0x0001);
576 /// ComputeSymbolTable - Compute the symbol table data
578 /// \param StringTable [out] - The string table data.
579 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
581 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
582 std::vector<MachSymbolData> &LocalSymbolData,
583 std::vector<MachSymbolData> &ExternalSymbolData,
584 std::vector<MachSymbolData> &UndefinedSymbolData) {
585 // Build section lookup table.
586 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
588 for (MCAssembler::iterator it = Asm.begin(),
589 ie = Asm.end(); it != ie; ++it, ++Index)
590 SectionIndexMap[&it->getSection()] = Index;
591 assert(Index <= 256 && "Too many sections!");
593 // Index 0 is always the empty string.
594 StringMap<uint64_t> StringIndexMap;
595 StringTable += '\x00';
597 // Build the symbol arrays and the string table, but only for non-local
600 // The particular order that we collect the symbols and create the string
601 // table, then sort the symbols is chosen to match 'as'. Even though it
602 // doesn't matter for correctness, this is important for letting us diff .o
604 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
605 ie = Asm.symbol_end(); it != ie; ++it) {
606 const MCSymbol &Symbol = it->getSymbol();
608 // Ignore assembler temporaries.
609 if (it->getSymbol().isTemporary())
612 if (!it->isExternal() && !Symbol.isUndefined())
615 uint64_t &Entry = StringIndexMap[Symbol.getName()];
617 Entry = StringTable.size();
618 StringTable += Symbol.getName();
619 StringTable += '\x00';
624 MSD.StringIndex = Entry;
626 if (Symbol.isUndefined()) {
627 MSD.SectionIndex = 0;
628 UndefinedSymbolData.push_back(MSD);
629 } else if (Symbol.isAbsolute()) {
630 MSD.SectionIndex = 0;
631 ExternalSymbolData.push_back(MSD);
633 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
634 assert(MSD.SectionIndex && "Invalid section index!");
635 ExternalSymbolData.push_back(MSD);
639 // Now add the data for local symbols.
640 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
641 ie = Asm.symbol_end(); it != ie; ++it) {
642 const MCSymbol &Symbol = it->getSymbol();
644 // Ignore assembler temporaries.
645 if (it->getSymbol().isTemporary())
648 if (it->isExternal() || Symbol.isUndefined())
651 uint64_t &Entry = StringIndexMap[Symbol.getName()];
653 Entry = StringTable.size();
654 StringTable += Symbol.getName();
655 StringTable += '\x00';
660 MSD.StringIndex = Entry;
662 if (Symbol.isAbsolute()) {
663 MSD.SectionIndex = 0;
664 LocalSymbolData.push_back(MSD);
666 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
667 assert(MSD.SectionIndex && "Invalid section index!");
668 LocalSymbolData.push_back(MSD);
672 // External and undefined symbols are required to be in lexicographic order.
673 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
674 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
676 // Set the symbol indices.
678 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
679 LocalSymbolData[i].SymbolData->setIndex(Index++);
680 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
681 ExternalSymbolData[i].SymbolData->setIndex(Index++);
682 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
683 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
685 // The string table is padded to a multiple of 4.
686 while (StringTable.size() % 4)
687 StringTable += '\x00';
690 void WriteObject(MCAssembler &Asm) {
691 unsigned NumSections = Asm.size();
693 // Compute the symbol -> symbol data map.
695 // FIXME: This should not be here.
696 DenseMap<const MCSymbol*, MCSymbolData *> SymbolMap;
697 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
698 ie = Asm.symbol_end(); it != ie; ++it)
699 SymbolMap[&it->getSymbol()] = it;
701 // Create symbol data for any indirect symbols.
702 BindIndirectSymbols(Asm, SymbolMap);
704 // Compute symbol table information.
705 SmallString<256> StringTable;
706 std::vector<MachSymbolData> LocalSymbolData;
707 std::vector<MachSymbolData> ExternalSymbolData;
708 std::vector<MachSymbolData> UndefinedSymbolData;
709 unsigned NumSymbols = Asm.symbol_size();
711 // No symbol table command is written if there are no symbols.
713 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
714 UndefinedSymbolData);
716 // The section data starts after the header, the segment load command (and
717 // section headers) and the symbol table.
718 unsigned NumLoadCommands = 1;
719 uint64_t LoadCommandsSize =
720 SegmentLoadCommand32Size + NumSections * Section32Size;
722 // Add the symbol table load command sizes, if used.
724 NumLoadCommands += 2;
725 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
728 // Compute the total size of the section data, as well as its file size and
730 uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
731 uint64_t SectionDataSize = 0;
732 uint64_t SectionDataFileSize = 0;
734 for (MCAssembler::iterator it = Asm.begin(),
735 ie = Asm.end(); it != ie; ++it) {
736 MCSectionData &SD = *it;
738 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
740 if (isVirtualSection(SD.getSection()))
743 SectionDataSize = std::max(SectionDataSize,
744 SD.getAddress() + SD.getSize());
745 SectionDataFileSize = std::max(SectionDataFileSize,
746 SD.getAddress() + SD.getFileSize());
749 // The section data is padded to 4 bytes.
751 // FIXME: Is this machine dependent?
752 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
753 SectionDataFileSize += SectionDataPadding;
755 // Write the prolog, starting with the header and load command...
756 WriteHeader32(NumLoadCommands, LoadCommandsSize,
757 Asm.getSubsectionsViaSymbols());
758 WriteSegmentLoadCommand32(NumSections, VMSize,
759 SectionDataStart, SectionDataSize);
761 // ... and then the section headers.
763 // We also compute the section relocations while we do this. Note that
764 // computing relocation info will also update the fixup to have the correct
765 // value; this will overwrite the appropriate data in the fragment when it
767 std::vector<MachRelocationEntry> RelocInfos;
768 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
769 for (MCAssembler::iterator it = Asm.begin(),
770 ie = Asm.end(); it != ie; ++it) {
771 MCSectionData &SD = *it;
773 // The assembler writes relocations in the reverse order they were seen.
775 // FIXME: It is probably more complicated than this.
776 unsigned NumRelocsStart = RelocInfos.size();
777 for (MCSectionData::reverse_iterator it2 = SD.rbegin(),
778 ie2 = SD.rend(); it2 != ie2; ++it2)
779 for (unsigned i = 0, e = it2->fixup_size(); i != e; ++i)
780 ComputeRelocationInfo(Asm, *it2, it2->getFixups()[e - i - 1],
781 SymbolMap, RelocInfos);
783 unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
784 uint64_t SectionStart = SectionDataStart + SD.getAddress();
785 WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
786 RelocTableEnd += NumRelocs * RelocationInfoSize;
789 // Write the symbol table load command, if used.
791 unsigned FirstLocalSymbol = 0;
792 unsigned NumLocalSymbols = LocalSymbolData.size();
793 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
794 unsigned NumExternalSymbols = ExternalSymbolData.size();
795 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
796 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
797 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
798 unsigned NumSymTabSymbols =
799 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
800 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
801 uint64_t IndirectSymbolOffset = 0;
803 // If used, the indirect symbols are written after the section data.
804 if (NumIndirectSymbols)
805 IndirectSymbolOffset = RelocTableEnd;
807 // The symbol table is written after the indirect symbol data.
808 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
810 // The string table is written after symbol table.
811 uint64_t StringTableOffset =
812 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
813 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
814 StringTableOffset, StringTable.size());
816 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
817 FirstExternalSymbol, NumExternalSymbols,
818 FirstUndefinedSymbol, NumUndefinedSymbols,
819 IndirectSymbolOffset, NumIndirectSymbols);
822 // Write the actual section data.
823 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
824 WriteFileData(OS, *it, *this);
826 // Write the extra padding.
827 WriteZeros(SectionDataPadding);
829 // Write the relocation entries.
830 for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
831 Write32(RelocInfos[i].Word0);
832 Write32(RelocInfos[i].Word1);
835 // Write the symbol table data, if used.
837 // Write the indirect symbol entries.
838 for (MCAssembler::indirect_symbol_iterator
839 it = Asm.indirect_symbol_begin(),
840 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
841 // Indirect symbols in the non lazy symbol pointer section have some
843 const MCSectionMachO &Section =
844 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
846 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
847 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
848 // If this symbol is defined and internal, mark it as such.
849 if (it->Symbol->isDefined() &&
850 !SymbolMap.lookup(it->Symbol)->isExternal()) {
851 uint32_t Flags = ISF_Local;
852 if (it->Symbol->isAbsolute())
853 Flags |= ISF_Absolute;
859 Write32(SymbolMap[it->Symbol]->getIndex());
862 // FIXME: Check that offsets match computed ones.
864 // Write the symbol table entries.
865 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
866 WriteNlist32(LocalSymbolData[i]);
867 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
868 WriteNlist32(ExternalSymbolData[i]);
869 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
870 WriteNlist32(UndefinedSymbolData[i]);
872 // Write the string table.
873 OS << StringTable.str();
880 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
883 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
886 FileSize(~UINT64_C(0))
889 Parent->getFragmentList().push_back(this);
892 MCFragment::~MCFragment() {
895 uint64_t MCFragment::getAddress() const {
896 assert(getParent() && "Missing Section!");
897 return getParent()->getAddress() + Offset;
902 MCSectionData::MCSectionData() : Section(0) {}
904 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
905 : Section(&_Section),
907 Address(~UINT64_C(0)),
909 FileSize(~UINT64_C(0)),
910 HasInstructions(false)
913 A->getSectionList().push_back(this);
918 MCSymbolData::MCSymbolData() : Symbol(0) {}
920 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
921 uint64_t _Offset, MCAssembler *A)
922 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
923 IsExternal(false), IsPrivateExtern(false),
924 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
927 A->getSymbolList().push_back(this);
932 MCAssembler::MCAssembler(MCContext &_Context, raw_ostream &_OS)
933 : Context(_Context), OS(_OS), SubsectionsViaSymbols(false)
937 MCAssembler::~MCAssembler() {
940 void MCAssembler::LayoutSection(MCSectionData &SD) {
941 uint64_t Address = SD.getAddress();
943 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
946 F.setOffset(Address - SD.getAddress());
948 // Evaluate fragment size.
949 switch (F.getKind()) {
950 case MCFragment::FT_Align: {
951 MCAlignFragment &AF = cast<MCAlignFragment>(F);
953 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
954 if (Size > AF.getMaxBytesToEmit())
957 AF.setFileSize(Size);
961 case MCFragment::FT_Data:
962 F.setFileSize(F.getMaxFileSize());
965 case MCFragment::FT_Fill: {
966 MCFillFragment &FF = cast<MCFillFragment>(F);
968 F.setFileSize(F.getMaxFileSize());
971 if (!FF.getValue().EvaluateAsRelocatable(Target))
972 llvm_report_error("expected relocatable expression");
974 // If the fill value is constant, thats it.
975 if (Target.isAbsolute())
978 // Otherwise, add fixups for the values.
980 // FIXME: What we want to do here is lower this to a data fragment once we
981 // realize it will need relocations. This means that the only place we
982 // need to worry about relocations and fixing is on data fragments.
983 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i)
984 FF.getFixups().push_back(MCAsmFixup(i*FF.getValueSize(), FF.getValue(),
989 case MCFragment::FT_Org: {
990 MCOrgFragment &OF = cast<MCOrgFragment>(F);
993 if (!OF.getOffset().EvaluateAsRelocatable(Target))
994 llvm_report_error("expected relocatable expression");
996 if (!Target.isAbsolute())
997 llvm_unreachable("FIXME: Not yet implemented!");
998 uint64_t OrgOffset = Target.getConstant();
999 uint64_t Offset = Address - SD.getAddress();
1001 // FIXME: We need a way to communicate this error.
1002 if (OrgOffset < Offset)
1003 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
1004 "' (at offset '" + Twine(Offset) + "'");
1006 F.setFileSize(OrgOffset - Offset);
1010 case MCFragment::FT_ZeroFill: {
1011 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1013 // Align the fragment offset; it is safe to adjust the offset freely since
1014 // this is only in virtual sections.
1015 uint64_t Aligned = RoundUpToAlignment(Address, ZFF.getAlignment());
1016 F.setOffset(Aligned - SD.getAddress());
1018 // FIXME: This is misnamed.
1019 F.setFileSize(ZFF.getSize());
1024 Address += F.getFileSize();
1027 // Set the section sizes.
1028 SD.setSize(Address - SD.getAddress());
1029 if (isVirtualSection(SD.getSection()))
1032 SD.setFileSize(Address - SD.getAddress());
1035 /// WriteFileData - Write the \arg F data to the output file.
1036 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1037 MachObjectWriter &MOW) {
1038 uint64_t Start = OS.tell();
1043 // FIXME: Embed in fragments instead?
1044 switch (F.getKind()) {
1045 case MCFragment::FT_Align: {
1046 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1047 uint64_t Count = AF.getFileSize() / AF.getValueSize();
1049 // FIXME: This error shouldn't actually occur (the front end should emit
1050 // multiple .align directives to enforce the semantics it wants), but is
1051 // severe enough that we want to report it. How to handle this?
1052 if (Count * AF.getValueSize() != AF.getFileSize())
1053 llvm_report_error("undefined .align directive, value size '" +
1054 Twine(AF.getValueSize()) +
1055 "' is not a divisor of padding size '" +
1056 Twine(AF.getFileSize()) + "'");
1058 for (uint64_t i = 0; i != Count; ++i) {
1059 switch (AF.getValueSize()) {
1061 assert(0 && "Invalid size!");
1062 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1063 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1064 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1065 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1071 case MCFragment::FT_Data:
1072 OS << cast<MCDataFragment>(F).getContents().str();
1075 case MCFragment::FT_Fill: {
1076 MCFillFragment &FF = cast<MCFillFragment>(F);
1081 if (!FF.getValue().EvaluateAsRelocatable(Target))
1082 llvm_report_error("expected relocatable expression");
1084 if (Target.isAbsolute())
1085 Value = Target.getConstant();
1086 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1087 if (!Target.isAbsolute()) {
1090 // FIXME: Find a better way to write in the fixes (move to
1092 const MCAsmFixup *Fixup = FF.LookupFixup(i * FF.getValueSize());
1093 assert(Fixup && "Missing fixup for fill value!");
1094 Value = Fixup->FixedValue;
1097 switch (FF.getValueSize()) {
1099 assert(0 && "Invalid size!");
1100 case 1: MOW.Write8 (uint8_t (Value)); break;
1101 case 2: MOW.Write16(uint16_t(Value)); break;
1102 case 4: MOW.Write32(uint32_t(Value)); break;
1103 case 8: MOW.Write64(uint64_t(Value)); break;
1109 case MCFragment::FT_Org: {
1110 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1112 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1113 MOW.Write8(uint8_t(OF.getValue()));
1118 case MCFragment::FT_ZeroFill: {
1119 assert(0 && "Invalid zero fill fragment in concrete section!");
1124 assert(OS.tell() - Start == F.getFileSize());
1127 /// WriteFileData - Write the \arg SD data to the output file.
1128 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1129 MachObjectWriter &MOW) {
1130 // Ignore virtual sections.
1131 if (isVirtualSection(SD.getSection())) {
1132 assert(SD.getFileSize() == 0);
1136 uint64_t Start = OS.tell();
1139 for (MCSectionData::const_iterator it = SD.begin(),
1140 ie = SD.end(); it != ie; ++it)
1141 WriteFileData(OS, *it, MOW);
1143 // Add section padding.
1144 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1145 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1147 assert(OS.tell() - Start == SD.getFileSize());
1150 void MCAssembler::Finish() {
1151 // Layout the concrete sections and fragments.
1152 uint64_t Address = 0;
1153 MCSectionData *Prev = 0;
1154 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1155 MCSectionData &SD = *it;
1157 // Skip virtual sections.
1158 if (isVirtualSection(SD.getSection()))
1161 // Align this section if necessary by adding padding bytes to the previous
1163 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1164 assert(Prev && "Missing prev section!");
1165 Prev->setFileSize(Prev->getFileSize() + Pad);
1169 // Layout the section fragments and its size.
1170 SD.setAddress(Address);
1172 Address += SD.getFileSize();
1177 // Layout the virtual sections.
1178 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1179 MCSectionData &SD = *it;
1181 if (!isVirtualSection(SD.getSection()))
1184 SD.setAddress(Address);
1186 Address += SD.getSize();
1189 // Write the object file.
1190 MachObjectWriter MOW(OS);
1191 MOW.WriteObject(*this);