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"
29 class MachObjectWriter;
31 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
33 // FIXME FIXME FIXME: There are number of places in this file where we convert
34 // what is a 64-bit assembler value used for computation into a value in the
35 // object file, which may truncate it. We should detect that truncation where
36 // invalid and report errors back.
38 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
39 MachObjectWriter &MOW);
41 /// isVirtualSection - Check if this is a section which does not actually exist
42 /// in the object file.
43 static bool isVirtualSection(const MCSection &Section) {
45 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
46 unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
47 return (Type == MCSectionMachO::S_ZEROFILL);
50 static unsigned getFixupKindLog2Size(MCFixupKind Kind) {
52 default: llvm_unreachable("invalid fixup kind!");
53 case FK_Data_1: return 0;
54 case FK_Data_2: return 1;
55 case FK_Data_4: return 2;
56 case FK_Data_8: return 3;
60 class MachObjectWriter {
61 // See <mach-o/loader.h>.
63 Header_Magic32 = 0xFEEDFACE,
64 Header_Magic64 = 0xFEEDFACF
67 static const unsigned Header32Size = 28;
68 static const unsigned Header64Size = 32;
69 static const unsigned SegmentLoadCommand32Size = 56;
70 static const unsigned Section32Size = 68;
71 static const unsigned SymtabLoadCommandSize = 24;
72 static const unsigned DysymtabLoadCommandSize = 80;
73 static const unsigned Nlist32Size = 12;
74 static const unsigned RelocationInfoSize = 8;
81 HF_SubsectionsViaSymbols = 0x2000
84 enum LoadCommandType {
90 // See <mach-o/nlist.h>.
97 enum SymbolTypeFlags {
98 // If any of these bits are set, then the entry is a stab entry number (see
99 // <mach-o/stab.h>. Otherwise the other masks apply.
100 STF_StabsEntryMask = 0xe0,
104 STF_PrivateExtern = 0x10
107 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
109 enum IndirectSymbolFlags {
110 ISF_Local = 0x80000000,
111 ISF_Absolute = 0x40000000
114 /// RelocationFlags - Special flags for addresses.
115 enum RelocationFlags {
116 RF_Scattered = 0x80000000
119 enum RelocationInfoType {
123 RIT_PreboundLazyPointer = 3,
124 RIT_LocalDifference = 4
127 /// MachSymbolData - Helper struct for containing some precomputed information
129 struct MachSymbolData {
130 MCSymbolData *SymbolData;
131 uint64_t StringIndex;
132 uint8_t SectionIndex;
134 // Support lexicographic sorting.
135 bool operator<(const MachSymbolData &RHS) const {
136 const std::string &Name = SymbolData->getSymbol().getName();
137 return Name < RHS.SymbolData->getSymbol().getName();
145 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
146 : OS(_OS), IsLSB(_IsLSB) {
149 /// @name Helper Methods
152 void Write8(uint8_t Value) {
156 void Write16(uint16_t Value) {
158 Write8(uint8_t(Value >> 0));
159 Write8(uint8_t(Value >> 8));
161 Write8(uint8_t(Value >> 8));
162 Write8(uint8_t(Value >> 0));
166 void Write32(uint32_t Value) {
168 Write16(uint16_t(Value >> 0));
169 Write16(uint16_t(Value >> 16));
171 Write16(uint16_t(Value >> 16));
172 Write16(uint16_t(Value >> 0));
176 void Write64(uint64_t Value) {
178 Write32(uint32_t(Value >> 0));
179 Write32(uint32_t(Value >> 32));
181 Write32(uint32_t(Value >> 32));
182 Write32(uint32_t(Value >> 0));
186 void WriteZeros(unsigned N) {
187 const char Zeros[16] = { 0 };
189 for (unsigned i = 0, e = N / 16; i != e; ++i)
190 OS << StringRef(Zeros, 16);
192 OS << StringRef(Zeros, N % 16);
195 void WriteString(StringRef Str, unsigned ZeroFillSize = 0) {
198 WriteZeros(ZeroFillSize - Str.size());
203 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
204 bool SubsectionsViaSymbols) {
207 if (SubsectionsViaSymbols)
208 Flags |= HF_SubsectionsViaSymbols;
210 // struct mach_header (28 bytes)
212 uint64_t Start = OS.tell();
215 Write32(Header_Magic32);
217 // FIXME: Support cputype.
218 Write32(MachO::CPUTypeI386);
219 // FIXME: Support cpusubtype.
220 Write32(MachO::CPUSubType_I386_ALL);
222 Write32(NumLoadCommands); // Object files have a single load command, the
224 Write32(LoadCommandsSize);
227 assert(OS.tell() - Start == Header32Size);
230 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
232 /// \arg NumSections - The number of sections in this segment.
233 /// \arg SectionDataSize - The total size of the sections.
234 void WriteSegmentLoadCommand32(unsigned NumSections,
236 uint64_t SectionDataStartOffset,
237 uint64_t SectionDataSize) {
238 // struct segment_command (56 bytes)
240 uint64_t Start = OS.tell();
243 Write32(LCT_Segment);
244 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
247 Write32(0); // vmaddr
248 Write32(VMSize); // vmsize
249 Write32(SectionDataStartOffset); // file offset
250 Write32(SectionDataSize); // file size
251 Write32(0x7); // maxprot
252 Write32(0x7); // initprot
253 Write32(NumSections);
256 assert(OS.tell() - Start == SegmentLoadCommand32Size);
259 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
260 uint64_t RelocationsStart, unsigned NumRelocations) {
261 // The offset is unused for virtual sections.
262 if (isVirtualSection(SD.getSection())) {
263 assert(SD.getFileSize() == 0 && "Invalid file size!");
267 // struct section (68 bytes)
269 uint64_t Start = OS.tell();
272 // FIXME: cast<> support!
273 const MCSectionMachO &Section =
274 static_cast<const MCSectionMachO&>(SD.getSection());
275 WriteString(Section.getSectionName(), 16);
276 WriteString(Section.getSegmentName(), 16);
277 Write32(SD.getAddress()); // address
278 Write32(SD.getSize()); // size
281 unsigned Flags = Section.getTypeAndAttributes();
282 if (SD.hasInstructions())
283 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
285 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
286 Write32(Log2_32(SD.getAlignment()));
287 Write32(NumRelocations ? RelocationsStart : 0);
288 Write32(NumRelocations);
290 Write32(0); // reserved1
291 Write32(Section.getStubSize()); // reserved2
293 assert(OS.tell() - Start == Section32Size);
296 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
297 uint32_t StringTableOffset,
298 uint32_t StringTableSize) {
299 // struct symtab_command (24 bytes)
301 uint64_t Start = OS.tell();
305 Write32(SymtabLoadCommandSize);
306 Write32(SymbolOffset);
308 Write32(StringTableOffset);
309 Write32(StringTableSize);
311 assert(OS.tell() - Start == SymtabLoadCommandSize);
314 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
315 uint32_t NumLocalSymbols,
316 uint32_t FirstExternalSymbol,
317 uint32_t NumExternalSymbols,
318 uint32_t FirstUndefinedSymbol,
319 uint32_t NumUndefinedSymbols,
320 uint32_t IndirectSymbolOffset,
321 uint32_t NumIndirectSymbols) {
322 // struct dysymtab_command (80 bytes)
324 uint64_t Start = OS.tell();
327 Write32(LCT_Dysymtab);
328 Write32(DysymtabLoadCommandSize);
329 Write32(FirstLocalSymbol);
330 Write32(NumLocalSymbols);
331 Write32(FirstExternalSymbol);
332 Write32(NumExternalSymbols);
333 Write32(FirstUndefinedSymbol);
334 Write32(NumUndefinedSymbols);
335 Write32(0); // tocoff
337 Write32(0); // modtaboff
338 Write32(0); // nmodtab
339 Write32(0); // extrefsymoff
340 Write32(0); // nextrefsyms
341 Write32(IndirectSymbolOffset);
342 Write32(NumIndirectSymbols);
343 Write32(0); // extreloff
344 Write32(0); // nextrel
345 Write32(0); // locreloff
346 Write32(0); // nlocrel
348 assert(OS.tell() - Start == DysymtabLoadCommandSize);
351 void WriteNlist32(MachSymbolData &MSD) {
352 MCSymbolData &Data = *MSD.SymbolData;
353 const MCSymbol &Symbol = Data.getSymbol();
355 uint16_t Flags = Data.getFlags();
356 uint32_t Address = 0;
358 // Set the N_TYPE bits. See <mach-o/nlist.h>.
360 // FIXME: Are the prebound or indirect fields possible here?
361 if (Symbol.isUndefined())
362 Type = STT_Undefined;
363 else if (Symbol.isAbsolute())
368 // FIXME: Set STAB bits.
370 if (Data.isPrivateExtern())
371 Type |= STF_PrivateExtern;
374 if (Data.isExternal() || Symbol.isUndefined())
375 Type |= STF_External;
377 // Compute the symbol address.
378 if (Symbol.isDefined()) {
379 if (Symbol.isAbsolute()) {
380 llvm_unreachable("FIXME: Not yet implemented!");
382 Address = Data.getFragment()->getAddress() + Data.getOffset();
384 } else if (Data.isCommon()) {
385 // Common symbols are encoded with the size in the address
386 // field, and their alignment in the flags.
387 Address = Data.getCommonSize();
389 // Common alignment is packed into the 'desc' bits.
390 if (unsigned Align = Data.getCommonAlignment()) {
391 unsigned Log2Size = Log2_32(Align);
392 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
394 llvm_report_error("invalid 'common' alignment '" +
396 // FIXME: Keep this mask with the SymbolFlags enumeration.
397 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
401 // struct nlist (12 bytes)
403 Write32(MSD.StringIndex);
405 Write8(MSD.SectionIndex);
407 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
413 struct MachRelocationEntry {
417 void ComputeScatteredRelocationInfo(MCAssembler &Asm, MCFragment &Fragment,
419 const MCValue &Target,
420 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
421 std::vector<MachRelocationEntry> &Relocs) {
422 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
423 unsigned IsPCRel = 0;
424 unsigned Type = RIT_Vanilla;
427 const MCSymbol *A = Target.getSymA();
428 MCSymbolData *SD = SymbolMap.lookup(A);
429 uint32_t Value = SD->getFragment()->getAddress() + SD->getOffset();
432 if (const MCSymbol *B = Target.getSymB()) {
433 Type = RIT_LocalDifference;
435 MCSymbolData *SD = SymbolMap.lookup(B);
436 Value2 = SD->getFragment()->getAddress() + SD->getOffset();
439 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
441 // The value which goes in the fixup is current value of the expression.
442 Fixup.FixedValue = Value - Value2 + Target.getConstant();
444 MachRelocationEntry MRE;
445 MRE.Word0 = ((Address << 0) |
451 Relocs.push_back(MRE);
453 if (Type == RIT_LocalDifference) {
456 MachRelocationEntry MRE;
457 MRE.Word0 = ((0 << 0) |
463 Relocs.push_back(MRE);
467 void ComputeRelocationInfo(MCAssembler &Asm, MCDataFragment &Fragment,
469 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
470 std::vector<MachRelocationEntry> &Relocs) {
472 if (!Fixup.Value->EvaluateAsRelocatable(Target))
473 llvm_report_error("expected relocatable expression");
475 // If this is a difference or a local symbol plus an offset, then we need a
476 // scattered relocation entry.
477 if (Target.getSymB() ||
478 (Target.getSymA() && !Target.getSymA()->isUndefined() &&
479 Target.getConstant()))
480 return ComputeScatteredRelocationInfo(Asm, Fragment, Fixup, Target,
484 uint32_t Address = Fragment.getOffset() + Fixup.Offset;
487 unsigned IsPCRel = 0;
488 unsigned IsExtern = 0;
491 if (Target.isAbsolute()) { // constant
492 // SymbolNum of 0 indicates the absolute section.
494 // FIXME: When is this generated?
497 llvm_unreachable("FIXME: Not yet implemented!");
499 const MCSymbol *Symbol = Target.getSymA();
500 MCSymbolData *SD = SymbolMap.lookup(Symbol);
502 if (Symbol->isUndefined()) {
504 Index = SD->getIndex();
507 // The index is the section ordinal.
511 for (MCAssembler::iterator it = Asm.begin(),
512 ie = Asm.end(); it != ie; ++it, ++Index)
513 if (&*it == SD->getFragment()->getParent())
515 Value = SD->getFragment()->getAddress() + SD->getOffset();
521 // The value which goes in the fixup is current value of the expression.
522 Fixup.FixedValue = Value + Target.getConstant();
524 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
526 // struct relocation_info (8 bytes)
527 MachRelocationEntry MRE;
529 MRE.Word1 = ((Index << 0) |
534 Relocs.push_back(MRE);
537 void BindIndirectSymbols(MCAssembler &Asm,
538 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap) {
539 // This is the point where 'as' creates actual symbols for indirect symbols
540 // (in the following two passes). It would be easier for us to do this
541 // sooner when we see the attribute, but that makes getting the order in the
542 // symbol table much more complicated than it is worth.
544 // FIXME: Revisit this when the dust settles.
546 // Bind non lazy symbol pointers first.
547 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
548 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
549 // FIXME: cast<> support!
550 const MCSectionMachO &Section =
551 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
554 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
555 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
558 MCSymbolData *&Entry = SymbolMap[it->Symbol];
560 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
563 // Then lazy symbol pointers and symbol stubs.
564 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
565 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
566 // FIXME: cast<> support!
567 const MCSectionMachO &Section =
568 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
571 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
572 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
573 Type != MCSectionMachO::S_SYMBOL_STUBS)
576 MCSymbolData *&Entry = SymbolMap[it->Symbol];
578 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
580 // Set the symbol type to undefined lazy, but only on construction.
582 // FIXME: Do not hardcode.
583 Entry->setFlags(Entry->getFlags() | 0x0001);
588 /// ComputeSymbolTable - Compute the symbol table data
590 /// \param StringTable [out] - The string table data.
591 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
593 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
594 std::vector<MachSymbolData> &LocalSymbolData,
595 std::vector<MachSymbolData> &ExternalSymbolData,
596 std::vector<MachSymbolData> &UndefinedSymbolData) {
597 // Build section lookup table.
598 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
600 for (MCAssembler::iterator it = Asm.begin(),
601 ie = Asm.end(); it != ie; ++it, ++Index)
602 SectionIndexMap[&it->getSection()] = Index;
603 assert(Index <= 256 && "Too many sections!");
605 // Index 0 is always the empty string.
606 StringMap<uint64_t> StringIndexMap;
607 StringTable += '\x00';
609 // Build the symbol arrays and the string table, but only for non-local
612 // The particular order that we collect the symbols and create the string
613 // table, then sort the symbols is chosen to match 'as'. Even though it
614 // doesn't matter for correctness, this is important for letting us diff .o
616 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
617 ie = Asm.symbol_end(); it != ie; ++it) {
618 const MCSymbol &Symbol = it->getSymbol();
620 // Ignore assembler temporaries.
621 if (it->getSymbol().isTemporary())
624 if (!it->isExternal() && !Symbol.isUndefined())
627 uint64_t &Entry = StringIndexMap[Symbol.getName()];
629 Entry = StringTable.size();
630 StringTable += Symbol.getName();
631 StringTable += '\x00';
636 MSD.StringIndex = Entry;
638 if (Symbol.isUndefined()) {
639 MSD.SectionIndex = 0;
640 UndefinedSymbolData.push_back(MSD);
641 } else if (Symbol.isAbsolute()) {
642 MSD.SectionIndex = 0;
643 ExternalSymbolData.push_back(MSD);
645 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
646 assert(MSD.SectionIndex && "Invalid section index!");
647 ExternalSymbolData.push_back(MSD);
651 // Now add the data for local symbols.
652 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
653 ie = Asm.symbol_end(); it != ie; ++it) {
654 const MCSymbol &Symbol = it->getSymbol();
656 // Ignore assembler temporaries.
657 if (it->getSymbol().isTemporary())
660 if (it->isExternal() || Symbol.isUndefined())
663 uint64_t &Entry = StringIndexMap[Symbol.getName()];
665 Entry = StringTable.size();
666 StringTable += Symbol.getName();
667 StringTable += '\x00';
672 MSD.StringIndex = Entry;
674 if (Symbol.isAbsolute()) {
675 MSD.SectionIndex = 0;
676 LocalSymbolData.push_back(MSD);
678 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
679 assert(MSD.SectionIndex && "Invalid section index!");
680 LocalSymbolData.push_back(MSD);
684 // External and undefined symbols are required to be in lexicographic order.
685 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
686 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
688 // Set the symbol indices.
690 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
691 LocalSymbolData[i].SymbolData->setIndex(Index++);
692 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
693 ExternalSymbolData[i].SymbolData->setIndex(Index++);
694 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
695 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
697 // The string table is padded to a multiple of 4.
698 while (StringTable.size() % 4)
699 StringTable += '\x00';
702 void WriteObject(MCAssembler &Asm) {
703 unsigned NumSections = Asm.size();
705 // Compute the symbol -> symbol data map.
707 // FIXME: This should not be here.
708 DenseMap<const MCSymbol*, MCSymbolData *> SymbolMap;
709 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
710 ie = Asm.symbol_end(); it != ie; ++it)
711 SymbolMap[&it->getSymbol()] = it;
713 // Create symbol data for any indirect symbols.
714 BindIndirectSymbols(Asm, SymbolMap);
716 // Compute symbol table information.
717 SmallString<256> StringTable;
718 std::vector<MachSymbolData> LocalSymbolData;
719 std::vector<MachSymbolData> ExternalSymbolData;
720 std::vector<MachSymbolData> UndefinedSymbolData;
721 unsigned NumSymbols = Asm.symbol_size();
723 // No symbol table command is written if there are no symbols.
725 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
726 UndefinedSymbolData);
728 // The section data starts after the header, the segment load command (and
729 // section headers) and the symbol table.
730 unsigned NumLoadCommands = 1;
731 uint64_t LoadCommandsSize =
732 SegmentLoadCommand32Size + NumSections * Section32Size;
734 // Add the symbol table load command sizes, if used.
736 NumLoadCommands += 2;
737 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
740 // Compute the total size of the section data, as well as its file size and
742 uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
743 uint64_t SectionDataSize = 0;
744 uint64_t SectionDataFileSize = 0;
746 for (MCAssembler::iterator it = Asm.begin(),
747 ie = Asm.end(); it != ie; ++it) {
748 MCSectionData &SD = *it;
750 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
752 if (isVirtualSection(SD.getSection()))
755 SectionDataSize = std::max(SectionDataSize,
756 SD.getAddress() + SD.getSize());
757 SectionDataFileSize = std::max(SectionDataFileSize,
758 SD.getAddress() + SD.getFileSize());
761 // The section data is padded to 4 bytes.
763 // FIXME: Is this machine dependent?
764 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
765 SectionDataFileSize += SectionDataPadding;
767 // Write the prolog, starting with the header and load command...
768 WriteHeader32(NumLoadCommands, LoadCommandsSize,
769 Asm.getSubsectionsViaSymbols());
770 WriteSegmentLoadCommand32(NumSections, VMSize,
771 SectionDataStart, SectionDataSize);
773 // ... and then the section headers.
775 // We also compute the section relocations while we do this. Note that
776 // computing relocation info will also update the fixup to have the correct
777 // value; this will overwrite the appropriate data in the fragment when it
779 std::vector<MachRelocationEntry> RelocInfos;
780 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
781 for (MCAssembler::iterator it = Asm.begin(),
782 ie = Asm.end(); it != ie; ++it) {
783 MCSectionData &SD = *it;
785 // The assembler writes relocations in the reverse order they were seen.
787 // FIXME: It is probably more complicated than this.
788 unsigned NumRelocsStart = RelocInfos.size();
789 for (MCSectionData::reverse_iterator it2 = SD.rbegin(),
790 ie2 = SD.rend(); it2 != ie2; ++it2)
791 if (MCDataFragment *DF = dyn_cast<MCDataFragment>(&*it2))
792 for (unsigned i = 0, e = DF->fixup_size(); i != e; ++i)
793 ComputeRelocationInfo(Asm, *DF, DF->getFixups()[e - i - 1],
794 SymbolMap, RelocInfos);
796 unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
797 uint64_t SectionStart = SectionDataStart + SD.getAddress();
798 WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
799 RelocTableEnd += NumRelocs * RelocationInfoSize;
802 // Write the symbol table load command, if used.
804 unsigned FirstLocalSymbol = 0;
805 unsigned NumLocalSymbols = LocalSymbolData.size();
806 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
807 unsigned NumExternalSymbols = ExternalSymbolData.size();
808 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
809 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
810 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
811 unsigned NumSymTabSymbols =
812 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
813 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
814 uint64_t IndirectSymbolOffset = 0;
816 // If used, the indirect symbols are written after the section data.
817 if (NumIndirectSymbols)
818 IndirectSymbolOffset = RelocTableEnd;
820 // The symbol table is written after the indirect symbol data.
821 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
823 // The string table is written after symbol table.
824 uint64_t StringTableOffset =
825 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
826 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
827 StringTableOffset, StringTable.size());
829 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
830 FirstExternalSymbol, NumExternalSymbols,
831 FirstUndefinedSymbol, NumUndefinedSymbols,
832 IndirectSymbolOffset, NumIndirectSymbols);
835 // Write the actual section data.
836 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
837 WriteFileData(OS, *it, *this);
839 // Write the extra padding.
840 WriteZeros(SectionDataPadding);
842 // Write the relocation entries.
843 for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
844 Write32(RelocInfos[i].Word0);
845 Write32(RelocInfos[i].Word1);
848 // Write the symbol table data, if used.
850 // Write the indirect symbol entries.
851 for (MCAssembler::indirect_symbol_iterator
852 it = Asm.indirect_symbol_begin(),
853 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
854 // Indirect symbols in the non lazy symbol pointer section have some
856 const MCSectionMachO &Section =
857 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
859 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
860 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
861 // If this symbol is defined and internal, mark it as such.
862 if (it->Symbol->isDefined() &&
863 !SymbolMap.lookup(it->Symbol)->isExternal()) {
864 uint32_t Flags = ISF_Local;
865 if (it->Symbol->isAbsolute())
866 Flags |= ISF_Absolute;
872 Write32(SymbolMap[it->Symbol]->getIndex());
875 // FIXME: Check that offsets match computed ones.
877 // Write the symbol table entries.
878 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
879 WriteNlist32(LocalSymbolData[i]);
880 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
881 WriteNlist32(ExternalSymbolData[i]);
882 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
883 WriteNlist32(UndefinedSymbolData[i]);
885 // Write the string table.
886 OS << StringTable.str();
890 void ApplyFixup(const MCAsmFixup &Fixup, MCDataFragment &DF) {
891 unsigned Size = 1 << getFixupKindLog2Size(Fixup.Kind);
893 // FIXME: Endianness assumption.
894 assert(Fixup.Offset + Size <= DF.getContents().size() &&
895 "Invalid fixup offset!");
896 for (unsigned i = 0; i != Size; ++i)
897 DF.getContents()[Fixup.Offset + i] = uint8_t(Fixup.FixedValue >> (i * 8));
903 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
906 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
909 FileSize(~UINT64_C(0))
912 Parent->getFragmentList().push_back(this);
915 MCFragment::~MCFragment() {
918 uint64_t MCFragment::getAddress() const {
919 assert(getParent() && "Missing Section!");
920 return getParent()->getAddress() + Offset;
925 MCSectionData::MCSectionData() : Section(0) {}
927 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
928 : Section(&_Section),
930 Address(~UINT64_C(0)),
932 FileSize(~UINT64_C(0)),
933 HasInstructions(false)
936 A->getSectionList().push_back(this);
941 MCSymbolData::MCSymbolData() : Symbol(0) {}
943 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
944 uint64_t _Offset, MCAssembler *A)
945 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
946 IsExternal(false), IsPrivateExtern(false),
947 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
950 A->getSymbolList().push_back(this);
955 MCAssembler::MCAssembler(MCContext &_Context, raw_ostream &_OS)
956 : Context(_Context), OS(_OS), SubsectionsViaSymbols(false)
960 MCAssembler::~MCAssembler() {
963 void MCAssembler::LayoutSection(MCSectionData &SD) {
964 uint64_t Address = SD.getAddress();
966 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
969 F.setOffset(Address - SD.getAddress());
971 // Evaluate fragment size.
972 switch (F.getKind()) {
973 case MCFragment::FT_Align: {
974 MCAlignFragment &AF = cast<MCAlignFragment>(F);
976 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
977 if (Size > AF.getMaxBytesToEmit())
980 AF.setFileSize(Size);
984 case MCFragment::FT_Data:
985 case MCFragment::FT_Fill:
986 F.setFileSize(F.getMaxFileSize());
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 MCDataFragment &DF = cast<MCDataFragment>(F);
1074 // Apply the fixups.
1076 // FIXME: Move elsewhere.
1077 for (MCDataFragment::const_fixup_iterator it = DF.fixup_begin(),
1078 ie = DF.fixup_end(); it != ie; ++it)
1079 MOW.ApplyFixup(*it, DF);
1081 OS << cast<MCDataFragment>(F).getContents().str();
1085 case MCFragment::FT_Fill: {
1086 MCFillFragment &FF = cast<MCFillFragment>(F);
1087 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1088 switch (FF.getValueSize()) {
1090 assert(0 && "Invalid size!");
1091 case 1: MOW.Write8 (uint8_t (FF.getValue())); break;
1092 case 2: MOW.Write16(uint16_t(FF.getValue())); break;
1093 case 4: MOW.Write32(uint32_t(FF.getValue())); break;
1094 case 8: MOW.Write64(uint64_t(FF.getValue())); break;
1100 case MCFragment::FT_Org: {
1101 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1103 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1104 MOW.Write8(uint8_t(OF.getValue()));
1109 case MCFragment::FT_ZeroFill: {
1110 assert(0 && "Invalid zero fill fragment in concrete section!");
1115 assert(OS.tell() - Start == F.getFileSize());
1118 /// WriteFileData - Write the \arg SD data to the output file.
1119 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1120 MachObjectWriter &MOW) {
1121 // Ignore virtual sections.
1122 if (isVirtualSection(SD.getSection())) {
1123 assert(SD.getFileSize() == 0);
1127 uint64_t Start = OS.tell();
1130 for (MCSectionData::const_iterator it = SD.begin(),
1131 ie = SD.end(); it != ie; ++it)
1132 WriteFileData(OS, *it, MOW);
1134 // Add section padding.
1135 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1136 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1138 assert(OS.tell() - Start == SD.getFileSize());
1141 void MCAssembler::Finish() {
1142 DEBUG_WITH_TYPE("mc-dump", {
1143 llvm::errs() << "assembler backend - pre-layout\n--\n";
1146 // Layout the concrete sections and fragments.
1147 uint64_t Address = 0;
1148 MCSectionData *Prev = 0;
1149 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1150 MCSectionData &SD = *it;
1152 // Skip virtual sections.
1153 if (isVirtualSection(SD.getSection()))
1156 // Align this section if necessary by adding padding bytes to the previous
1158 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1159 assert(Prev && "Missing prev section!");
1160 Prev->setFileSize(Prev->getFileSize() + Pad);
1164 // Layout the section fragments and its size.
1165 SD.setAddress(Address);
1167 Address += SD.getFileSize();
1172 // Layout the virtual sections.
1173 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1174 MCSectionData &SD = *it;
1176 if (!isVirtualSection(SD.getSection()))
1179 SD.setAddress(Address);
1181 Address += SD.getSize();
1184 DEBUG_WITH_TYPE("mc-dump", {
1185 llvm::errs() << "assembler backend - post-layout\n--\n";
1188 // Write the object file.
1189 MachObjectWriter MOW(OS);
1190 MOW.WriteObject(*this);
1196 // Debugging methods
1200 raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
1201 OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
1202 << " Kind:" << AF.Kind << ">";
1208 void MCFragment::dump() {
1209 raw_ostream &OS = llvm::errs();
1211 OS << "<MCFragment " << (void*) this << " Offset:" << Offset
1212 << " FileSize:" << FileSize;
1217 void MCAlignFragment::dump() {
1218 raw_ostream &OS = llvm::errs();
1220 OS << "<MCAlignFragment ";
1221 this->MCFragment::dump();
1223 OS << " Alignment:" << getAlignment()
1224 << " Value:" << getValue() << " ValueSize:" << getValueSize()
1225 << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
1228 void MCDataFragment::dump() {
1229 raw_ostream &OS = llvm::errs();
1231 OS << "<MCDataFragment ";
1232 this->MCFragment::dump();
1234 OS << " Contents:[";
1235 for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
1237 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1239 OS << "] (" << getContents().size() << " bytes)";
1241 if (!getFixups().empty()) {
1244 for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
1245 if (it != fixup_begin()) OS << ",\n ";
1254 void MCFillFragment::dump() {
1255 raw_ostream &OS = llvm::errs();
1257 OS << "<MCFillFragment ";
1258 this->MCFragment::dump();
1260 OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
1261 << " Count:" << getCount() << ">";
1264 void MCOrgFragment::dump() {
1265 raw_ostream &OS = llvm::errs();
1267 OS << "<MCOrgFragment ";
1268 this->MCFragment::dump();
1270 OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
1273 void MCZeroFillFragment::dump() {
1274 raw_ostream &OS = llvm::errs();
1276 OS << "<MCZeroFillFragment ";
1277 this->MCFragment::dump();
1279 OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
1282 void MCSectionData::dump() {
1283 raw_ostream &OS = llvm::errs();
1285 OS << "<MCSectionData";
1286 OS << " Alignment:" << getAlignment() << " Address:" << Address
1287 << " Size:" << Size << " FileSize:" << FileSize
1289 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1290 if (it != begin()) OS << ",\n ";
1296 void MCSymbolData::dump() {
1297 raw_ostream &OS = llvm::errs();
1299 OS << "<MCSymbolData Symbol:" << getSymbol()
1300 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1301 << " Flags:" << getFlags() << " Index:" << getIndex();
1303 OS << " (common, size:" << getCommonSize()
1304 << " align: " << getCommonAlignment() << ")";
1306 OS << " (external)";
1307 if (isPrivateExtern())
1308 OS << " (private extern)";
1312 void MCAssembler::dump() {
1313 raw_ostream &OS = llvm::errs();
1315 OS << "<MCAssembler\n";
1316 OS << " Sections:[";
1317 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1318 if (it != begin()) OS << ",\n ";
1324 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1325 if (it != symbol_begin()) OS << ",\n ";