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 #include "llvm/MC/MCAssembler.h"
12 #include "llvm/ADT/DenseMap.h"
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/StringMap.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/MC/MCSectionMachO.h"
17 #include "llvm/Support/DataTypes.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include "llvm/Target/TargetMachOWriterInfo.h"
24 class MachObjectWriter;
26 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
27 MachObjectWriter &MOW);
29 class MachObjectWriter {
30 // See <mach-o/loader.h>.
32 Header_Magic32 = 0xFEEDFACE,
33 Header_Magic64 = 0xFEEDFACF
36 static const unsigned Header32Size = 28;
37 static const unsigned Header64Size = 32;
38 static const unsigned SegmentLoadCommand32Size = 56;
39 static const unsigned Section32Size = 68;
40 static const unsigned SymtabLoadCommandSize = 24;
41 static const unsigned DysymtabLoadCommandSize = 80;
42 static const unsigned Nlist32Size = 12;
48 enum LoadCommandType {
54 // See <mach-o/nlist.h>.
61 enum SymbolTypeFlags {
62 // If any of these bits are set, then the entry is a stab entry number (see
63 // <mach-o/stab.h>. Otherwise the other masks apply.
64 STF_StabsEntryMask = 0xe0,
68 STF_PrivateExtern = 0x10
71 /// MachSymbolData - Helper struct for containing some precomputed information
73 struct MachSymbolData {
74 MCSymbolData *SymbolData;
78 // Support lexicographic sorting.
79 bool operator<(const MachSymbolData &RHS) const {
80 const std::string &Name = SymbolData->getSymbol().getName();
81 return Name < RHS.SymbolData->getSymbol().getName();
89 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
90 : OS(_OS), IsLSB(_IsLSB) {
93 /// @name Helper Methods
96 void Write8(uint8_t Value) {
100 void Write16(uint16_t Value) {
102 Write8(uint8_t(Value >> 0));
103 Write8(uint8_t(Value >> 8));
105 Write8(uint8_t(Value >> 8));
106 Write8(uint8_t(Value >> 0));
110 void Write32(uint32_t Value) {
112 Write16(uint16_t(Value >> 0));
113 Write16(uint16_t(Value >> 16));
115 Write16(uint16_t(Value >> 16));
116 Write16(uint16_t(Value >> 0));
120 void Write64(uint64_t Value) {
122 Write32(uint32_t(Value >> 0));
123 Write32(uint32_t(Value >> 32));
125 Write32(uint32_t(Value >> 32));
126 Write32(uint32_t(Value >> 0));
130 void WriteZeros(unsigned N) {
131 const char Zeros[16] = { 0 };
133 for (unsigned i = 0, e = N / 16; i != e; ++i)
134 OS << StringRef(Zeros, 16);
136 OS << StringRef(Zeros, N % 16);
139 void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
142 WriteZeros(ZeroFillSize - Str.size());
147 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize) {
148 // struct mach_header (28 bytes)
150 uint64_t Start = OS.tell();
153 Write32(Header_Magic32);
155 // FIXME: Support cputype.
156 Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
158 // FIXME: Support cpusubtype.
159 Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
163 // Object files have a single load command, the segment.
164 Write32(NumLoadCommands);
165 Write32(LoadCommandsSize);
168 assert(OS.tell() - Start == Header32Size);
171 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
173 /// \arg NumSections - The number of sections in this segment.
174 /// \arg SectionDataSize - The total size of the sections.
175 void WriteSegmentLoadCommand32(unsigned NumSections,
176 uint64_t SectionDataStartOffset,
177 uint64_t SectionDataSize) {
178 // struct segment_command (56 bytes)
180 uint64_t Start = OS.tell();
183 Write32(LCT_Segment);
184 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
187 Write32(0); // vmaddr
188 Write32(SectionDataSize); // vmsize
189 Write32(SectionDataStartOffset); // file offset
190 Write32(SectionDataSize); // file size
191 Write32(0x7); // maxprot
192 Write32(0x7); // initprot
193 Write32(NumSections);
196 assert(OS.tell() - Start == SegmentLoadCommand32Size);
199 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset) {
200 // struct section (68 bytes)
202 uint64_t Start = OS.tell();
205 // FIXME: cast<> support!
206 const MCSectionMachO &Section =
207 static_cast<const MCSectionMachO&>(SD.getSection());
208 WriteString(Section.getSectionName(), 16);
209 WriteString(Section.getSegmentName(), 16);
210 Write32(0); // address
211 Write32(SD.getFileSize()); // size
214 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
215 Write32(Log2_32(SD.getAlignment()));
216 Write32(0); // file offset of relocation entries
217 Write32(0); // number of relocation entrions
218 Write32(Section.getTypeAndAttributes());
219 Write32(0); // reserved1
220 Write32(Section.getStubSize()); // reserved2
222 assert(OS.tell() - Start == Section32Size);
225 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
226 uint32_t StringTableOffset,
227 uint32_t StringTableSize) {
228 // struct symtab_command (24 bytes)
230 uint64_t Start = OS.tell();
234 Write32(SymtabLoadCommandSize);
235 Write32(SymbolOffset);
237 Write32(StringTableOffset);
238 Write32(StringTableSize);
240 assert(OS.tell() - Start == SymtabLoadCommandSize);
243 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
244 uint32_t NumLocalSymbols,
245 uint32_t FirstExternalSymbol,
246 uint32_t NumExternalSymbols,
247 uint32_t FirstUndefinedSymbol,
248 uint32_t NumUndefinedSymbols,
249 uint32_t IndirectSymbolOffset,
250 uint32_t NumIndirectSymbols) {
251 // struct dysymtab_command (80 bytes)
253 uint64_t Start = OS.tell();
256 Write32(LCT_Dysymtab);
257 Write32(DysymtabLoadCommandSize);
258 Write32(FirstLocalSymbol);
259 Write32(NumLocalSymbols);
260 Write32(FirstExternalSymbol);
261 Write32(NumExternalSymbols);
262 Write32(FirstUndefinedSymbol);
263 Write32(NumUndefinedSymbols);
264 Write32(0); // tocoff
266 Write32(0); // modtaboff
267 Write32(0); // nmodtab
268 Write32(0); // extrefsymoff
269 Write32(0); // nextrefsyms
270 Write32(IndirectSymbolOffset);
271 Write32(NumIndirectSymbols);
272 Write32(0); // extreloff
273 Write32(0); // nextrel
274 Write32(0); // locreloff
275 Write32(0); // nlocrel
277 assert(OS.tell() - Start == DysymtabLoadCommandSize);
280 void WriteNlist32(MachSymbolData &MSD) {
281 MCSymbol &Symbol = MSD.SymbolData->getSymbol();
284 // Set the N_TYPE bits. See <mach-o/nlist.h>.
286 // FIXME: Are the prebound or indirect fields possible here?
287 if (Symbol.isUndefined())
288 Type = STT_Undefined;
289 else if (Symbol.isAbsolute())
294 // FIXME: Set STAB bits.
296 // FIXME: Set private external bit.
299 if (MSD.SymbolData->isExternal())
300 Type |= STF_External;
302 // struct nlist (12 bytes)
304 Write32(MSD.StringIndex);
306 Write8(MSD.SectionIndex);
307 Write16(0); // FIXME: Desc
308 Write32(0); // FIXME: Value
311 /// ComputeSymbolTable - Compute the symbol table data
313 /// \param StringTable [out] - The string table data.
314 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
317 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
318 std::vector<MachSymbolData> &LocalSymbolData,
319 std::vector<MachSymbolData> &ExternalSymbolData,
320 std::vector<MachSymbolData> &UndefinedSymbolData) {
321 // Build section lookup table.
322 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
324 for (MCAssembler::iterator it = Asm.begin(),
325 ie = Asm.end(); it != ie; ++it, ++Index)
326 SectionIndexMap[&it->getSection()] = Index;
327 assert(Index <= 256 && "Too many sections!");
329 // Index 0 is always the empty string.
330 StringMap<uint64_t> StringIndexMap;
331 StringTable += '\x00';
333 // Build the symbol arrays and the string table, but only for non-local
336 // The particular order that we collect the symbols and create the string
337 // table, then sort the symbols is chosen to match 'as'. Even though it
338 // doesn't matter for correctness, this is important for letting us diff .o
340 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
341 ie = Asm.symbol_end(); it != ie; ++it) {
342 MCSymbol &Symbol = it->getSymbol();
344 if (!it->isExternal())
347 uint64_t &Entry = StringIndexMap[Symbol.getName()];
349 Entry = StringTable.size();
350 StringTable += Symbol.getName();
351 StringTable += '\x00';
356 MSD.StringIndex = Entry;
358 if (Symbol.isUndefined()) {
359 MSD.SectionIndex = 0;
360 UndefinedSymbolData.push_back(MSD);
361 } else if (Symbol.isAbsolute()) {
362 MSD.SectionIndex = 0;
363 ExternalSymbolData.push_back(MSD);
365 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
366 assert(MSD.SectionIndex && "Invalid section index!");
367 ExternalSymbolData.push_back(MSD);
371 // Now add the data for local symbols.
372 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
373 ie = Asm.symbol_end(); it != ie; ++it) {
374 MCSymbol &Symbol = it->getSymbol();
376 if (it->isExternal())
379 uint64_t &Entry = StringIndexMap[Symbol.getName()];
381 Entry = StringTable.size();
382 StringTable += Symbol.getName();
383 StringTable += '\x00';
388 MSD.StringIndex = Entry;
390 assert(!Symbol.isUndefined() && "Local symbol can not be undefined!");
391 if (Symbol.isAbsolute()) {
392 MSD.SectionIndex = 0;
393 LocalSymbolData.push_back(MSD);
395 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
396 assert(MSD.SectionIndex && "Invalid section index!");
397 LocalSymbolData.push_back(MSD);
401 // External and undefined symbols are required to be in lexicographic order.
402 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
403 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
405 // The string table is padded to a multiple of 4.
407 // FIXME: Check to see if this varies per arch.
408 while (StringTable.size() % 4)
409 StringTable += '\x00';
412 void WriteObject(MCAssembler &Asm) {
413 unsigned NumSections = Asm.size();
415 // Compute symbol table information.
416 SmallString<256> StringTable;
417 std::vector<MachSymbolData> LocalSymbolData;
418 std::vector<MachSymbolData> ExternalSymbolData;
419 std::vector<MachSymbolData> UndefinedSymbolData;
420 unsigned NumSymbols = Asm.symbol_size();
422 // No symbol table command is written if there are no symbols.
424 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
425 UndefinedSymbolData);
427 // Compute the file offsets for all the sections in advance, so that we can
428 // write things out in order.
429 SmallVector<uint64_t, 16> SectionFileOffsets;
430 SectionFileOffsets.resize(NumSections);
432 // The section data starts after the header, the segment load command (and
433 // section headers) and the symbol table.
434 unsigned NumLoadCommands = 1;
435 uint64_t LoadCommandsSize =
436 SegmentLoadCommand32Size + NumSections * Section32Size;
438 // Add the symbol table load command sizes, if used.
440 NumLoadCommands += 2;
441 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
444 uint64_t FileOffset = Header32Size + LoadCommandsSize;
445 uint64_t SectionDataStartOffset = FileOffset;
446 uint64_t SectionDataSize = 0;
448 for (MCAssembler::iterator it = Asm.begin(),
449 ie = Asm.end(); it != ie; ++it, ++Index) {
450 SectionFileOffsets[Index] = FileOffset;
451 FileOffset += it->getFileSize();
452 SectionDataSize += it->getFileSize();
455 // Write the prolog, starting with the header and load command...
456 WriteHeader32(NumLoadCommands, LoadCommandsSize);
457 WriteSegmentLoadCommand32(NumSections, SectionDataStartOffset,
460 // ... and then the section headers.
462 for (MCAssembler::iterator it = Asm.begin(),
463 ie = Asm.end(); it != ie; ++it, ++Index)
464 WriteSection32(*it, SectionFileOffsets[Index]);
466 // Write the symbol table load command, if used.
468 // The string table is written after all the section data.
469 uint64_t SymbolTableOffset = SectionDataStartOffset + SectionDataSize;
470 uint64_t StringTableOffset =
471 SymbolTableOffset + NumSymbols * Nlist32Size;
472 WriteSymtabLoadCommand(SymbolTableOffset, NumSymbols,
473 StringTableOffset, StringTable.size());
475 unsigned FirstLocalSymbol = 0;
476 unsigned NumLocalSymbols = LocalSymbolData.size();
477 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
478 unsigned NumExternalSymbols = ExternalSymbolData.size();
479 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
480 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
481 // FIXME: Get correct symbol indices and counts for indirect symbols.
482 unsigned IndirectSymbolOffset = 0;
483 unsigned NumIndirectSymbols = 0;
484 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
485 FirstExternalSymbol, NumExternalSymbols,
486 FirstUndefinedSymbol, NumUndefinedSymbols,
487 IndirectSymbolOffset, NumIndirectSymbols);
490 // Write the actual section data.
491 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
492 WriteFileData(OS, *it, *this);
494 // Write the symbol table data, if used.
496 // FIXME: Check that offsets match computed ones.
498 // FIXME: Some of these are ordered by name to help the linker.
500 // Write the symbol table entries.
501 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
502 WriteNlist32(LocalSymbolData[i]);
503 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
504 WriteNlist32(ExternalSymbolData[i]);
505 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
506 WriteNlist32(UndefinedSymbolData[i]);
508 // Write the string table.
509 OS << StringTable.str();
516 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
519 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *SD)
521 FileSize(~UINT64_C(0))
524 SD->getFragmentList().push_back(this);
527 MCFragment::~MCFragment() {
532 MCSectionData::MCSectionData() : Section(*(MCSection*)0) {}
534 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
537 FileSize(~UINT64_C(0))
540 A->getSectionList().push_back(this);
545 MCSymbolData::MCSymbolData() : Symbol(*(MCSymbol*)0) {}
547 MCSymbolData::MCSymbolData(MCSymbol &_Symbol, MCFragment *_Fragment,
548 uint64_t _Offset, MCAssembler *A)
549 : Symbol(_Symbol), Fragment(_Fragment), Offset(_Offset),
553 A->getSymbolList().push_back(this);
558 MCAssembler::MCAssembler(raw_ostream &_OS) : OS(_OS) {}
560 MCAssembler::~MCAssembler() {
563 void MCAssembler::LayoutSection(MCSectionData &SD) {
566 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
571 // Evaluate fragment size.
572 switch (F.getKind()) {
573 case MCFragment::FT_Align: {
574 MCAlignFragment &AF = cast<MCAlignFragment>(F);
576 uint64_t AlignedOffset = RoundUpToAlignment(Offset, AF.getAlignment());
577 uint64_t PaddingBytes = AlignedOffset - Offset;
579 if (PaddingBytes > AF.getMaxBytesToEmit())
582 AF.setFileSize(PaddingBytes);
586 case MCFragment::FT_Data:
587 case MCFragment::FT_Fill:
588 F.setFileSize(F.getMaxFileSize());
591 case MCFragment::FT_Org: {
592 MCOrgFragment &OF = cast<MCOrgFragment>(F);
594 if (!OF.getOffset().isAbsolute())
595 llvm_unreachable("FIXME: Not yet implemented!");
596 uint64_t OrgOffset = OF.getOffset().getConstant();
598 // FIXME: We need a way to communicate this error.
599 if (OrgOffset < Offset)
600 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
601 "' (section offset '" + Twine(Offset) + "'");
603 F.setFileSize(OrgOffset - Offset);
608 Offset += F.getFileSize();
611 // FIXME: Pad section?
612 SD.setFileSize(Offset);
615 /// WriteFileData - Write the \arg F data to the output file.
616 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
617 MachObjectWriter &MOW) {
618 uint64_t Start = OS.tell();
621 // FIXME: Embed in fragments instead?
622 switch (F.getKind()) {
623 case MCFragment::FT_Align: {
624 MCAlignFragment &AF = cast<MCAlignFragment>(F);
625 uint64_t Count = AF.getFileSize() / AF.getValueSize();
627 // FIXME: This error shouldn't actually occur (the front end should emit
628 // multiple .align directives to enforce the semantics it wants), but is
629 // severe enough that we want to report it. How to handle this?
630 if (Count * AF.getValueSize() != AF.getFileSize())
631 llvm_report_error("undefined .align directive, value size '" +
632 Twine(AF.getValueSize()) +
633 "' is not a divisor of padding size '" +
634 Twine(AF.getFileSize()) + "'");
636 for (uint64_t i = 0; i != Count; ++i) {
637 switch (AF.getValueSize()) {
639 assert(0 && "Invalid size!");
640 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
641 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
642 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
643 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
649 case MCFragment::FT_Data:
650 OS << cast<MCDataFragment>(F).getContents().str();
653 case MCFragment::FT_Fill: {
654 MCFillFragment &FF = cast<MCFillFragment>(F);
656 if (!FF.getValue().isAbsolute())
657 llvm_unreachable("FIXME: Not yet implemented!");
658 int64_t Value = FF.getValue().getConstant();
660 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
661 switch (FF.getValueSize()) {
663 assert(0 && "Invalid size!");
664 case 1: MOW.Write8 (uint8_t (Value)); break;
665 case 2: MOW.Write16(uint16_t(Value)); break;
666 case 4: MOW.Write32(uint32_t(Value)); break;
667 case 8: MOW.Write64(uint64_t(Value)); break;
673 case MCFragment::FT_Org: {
674 MCOrgFragment &OF = cast<MCOrgFragment>(F);
676 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
677 MOW.Write8(uint8_t(OF.getValue()));
683 assert(OS.tell() - Start == F.getFileSize());
686 /// WriteFileData - Write the \arg SD data to the output file.
687 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
688 MachObjectWriter &MOW) {
689 uint64_t Start = OS.tell();
692 for (MCSectionData::const_iterator it = SD.begin(),
693 ie = SD.end(); it != ie; ++it)
694 WriteFileData(OS, *it, MOW);
696 assert(OS.tell() - Start == SD.getFileSize());
699 void MCAssembler::Finish() {
700 // Layout the sections and fragments.
701 for (iterator it = begin(), ie = end(); it != ie; ++it)
704 // Write the object file.
705 MachObjectWriter MOW(OS);
706 MOW.WriteObject(*this);