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"
11 #include "llvm/MC/MCSectionMachO.h"
12 #include "llvm/Target/TargetMachOWriterInfo.h"
13 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/StringMap.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/raw_ostream.h"
21 class MachObjectWriter;
23 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
24 MachObjectWriter &MOW);
26 class MachObjectWriter {
27 // See <mach-o/loader.h>.
29 Header_Magic32 = 0xFEEDFACE,
30 Header_Magic64 = 0xFEEDFACF
33 static const unsigned Header32Size = 28;
34 static const unsigned Header64Size = 32;
35 static const unsigned SegmentLoadCommand32Size = 56;
36 static const unsigned Section32Size = 68;
37 static const unsigned SymtabLoadCommandSize = 24;
38 static const unsigned DysymtabLoadCommandSize = 80;
39 static const unsigned Nlist32Size = 12;
45 enum LoadCommandType {
51 // See <mach-o/nlist.h>.
58 enum SymbolTypeFlags {
59 // If any of these bits are set, then the entry is a stab entry number (see
60 // <mach-o/stab.h>. Otherwise the other masks apply.
61 STF_StabsEntryMask = 0xe0,
65 STF_PrivateExtern = 0x10
68 /// MachSymbolData - Helper struct for containing some precomputed information
70 struct MachSymbolData {
71 MCSymbolData *SymbolData;
75 // Support lexicographic sorting.
76 bool operator<(const MachSymbolData &RHS) const {
77 const std::string &Name = SymbolData->getSymbol().getName();
78 return Name < RHS.SymbolData->getSymbol().getName();
86 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
87 : OS(_OS), IsLSB(_IsLSB) {
90 /// @name Helper Methods
93 void Write8(uint8_t Value) {
97 void Write16(uint16_t Value) {
99 Write8(uint8_t(Value >> 0));
100 Write8(uint8_t(Value >> 8));
102 Write8(uint8_t(Value >> 8));
103 Write8(uint8_t(Value >> 0));
107 void Write32(uint32_t Value) {
109 Write16(uint16_t(Value >> 0));
110 Write16(uint16_t(Value >> 16));
112 Write16(uint16_t(Value >> 16));
113 Write16(uint16_t(Value >> 0));
117 void Write64(uint64_t Value) {
119 Write32(uint32_t(Value >> 0));
120 Write32(uint32_t(Value >> 32));
122 Write32(uint32_t(Value >> 32));
123 Write32(uint32_t(Value >> 0));
127 void WriteZeros(unsigned N) {
128 const char Zeros[16] = { 0 };
130 for (unsigned i = 0, e = N / 16; i != e; ++i)
131 OS << StringRef(Zeros, 16);
133 OS << StringRef(Zeros, N % 16);
136 void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
139 WriteZeros(ZeroFillSize - Str.size());
144 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize) {
145 // struct mach_header (28 bytes)
147 uint64_t Start = OS.tell();
150 Write32(Header_Magic32);
152 // FIXME: Support cputype.
153 Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
155 // FIXME: Support cpusubtype.
156 Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
160 // Object files have a single load command, the segment.
161 Write32(NumLoadCommands);
162 Write32(LoadCommandsSize);
165 assert(OS.tell() - Start == Header32Size);
168 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
170 /// \arg NumSections - The number of sections in this segment.
171 /// \arg SectionDataSize - The total size of the sections.
172 void WriteSegmentLoadCommand32(unsigned NumSections,
173 uint64_t SectionDataStartOffset,
174 uint64_t SectionDataSize) {
175 // struct segment_command (56 bytes)
177 uint64_t Start = OS.tell();
180 Write32(LCT_Segment);
181 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
184 Write32(0); // vmaddr
185 Write32(SectionDataSize); // vmsize
186 Write32(SectionDataStartOffset); // file offset
187 Write32(SectionDataSize); // file size
188 Write32(0x7); // maxprot
189 Write32(0x7); // initprot
190 Write32(NumSections);
193 assert(OS.tell() - Start == SegmentLoadCommand32Size);
196 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset) {
197 // struct section (68 bytes)
199 uint64_t Start = OS.tell();
202 // FIXME: cast<> support!
203 const MCSectionMachO &Section =
204 static_cast<const MCSectionMachO&>(SD.getSection());
205 WriteString(Section.getSectionName(), 16);
206 WriteString(Section.getSegmentName(), 16);
207 Write32(0); // address
208 Write32(SD.getFileSize()); // size
211 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
212 Write32(Log2_32(SD.getAlignment()));
213 Write32(0); // file offset of relocation entries
214 Write32(0); // number of relocation entrions
215 Write32(Section.getTypeAndAttributes());
216 Write32(0); // reserved1
217 Write32(Section.getStubSize()); // reserved2
219 assert(OS.tell() - Start == Section32Size);
222 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
223 uint32_t StringTableOffset,
224 uint32_t StringTableSize) {
225 // struct symtab_command (24 bytes)
227 uint64_t Start = OS.tell();
231 Write32(SymtabLoadCommandSize);
232 Write32(SymbolOffset);
234 Write32(StringTableOffset);
235 Write32(StringTableSize);
237 assert(OS.tell() - Start == SymtabLoadCommandSize);
240 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
241 uint32_t NumLocalSymbols,
242 uint32_t FirstExternalSymbol,
243 uint32_t NumExternalSymbols,
244 uint32_t FirstUndefinedSymbol,
245 uint32_t NumUndefinedSymbols,
246 uint32_t IndirectSymbolOffset,
247 uint32_t NumIndirectSymbols) {
248 // struct dysymtab_command (80 bytes)
250 uint64_t Start = OS.tell();
253 Write32(LCT_Dysymtab);
254 Write32(DysymtabLoadCommandSize);
255 Write32(FirstLocalSymbol);
256 Write32(NumLocalSymbols);
257 Write32(FirstExternalSymbol);
258 Write32(NumExternalSymbols);
259 Write32(FirstUndefinedSymbol);
260 Write32(NumUndefinedSymbols);
261 Write32(0); // tocoff
263 Write32(0); // modtaboff
264 Write32(0); // nmodtab
265 Write32(0); // extrefsymoff
266 Write32(0); // nextrefsyms
267 Write32(IndirectSymbolOffset);
268 Write32(NumIndirectSymbols);
269 Write32(0); // extreloff
270 Write32(0); // nextrel
271 Write32(0); // locreloff
272 Write32(0); // nlocrel
274 assert(OS.tell() - Start == DysymtabLoadCommandSize);
277 void WriteNlist32(MachSymbolData &MSD) {
278 MCSymbol &Symbol = MSD.SymbolData->getSymbol();
281 // Set the N_TYPE bits. See <mach-o/nlist.h>.
283 // FIXME: Are the prebound or indirect fields possible here?
284 if (Symbol.isUndefined())
285 Type = STT_Undefined;
286 else if (Symbol.isAbsolute())
291 // FIXME: Set STAB bits.
293 // FIXME: Set private external bit.
296 if (MSD.SymbolData->isExternal())
297 Type |= STF_External;
299 // struct nlist (12 bytes)
301 Write32(MSD.StringIndex);
303 Write8(MSD.SectionIndex);
304 Write16(0); // FIXME: Desc
305 Write32(0); // FIXME: Value
308 /// ComputeSymbolTable - Compute the symbol table data
310 /// \param StringTable [out] - The string table data.
311 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
314 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
315 std::vector<MachSymbolData> &LocalSymbolData,
316 std::vector<MachSymbolData> &ExternalSymbolData,
317 std::vector<MachSymbolData> &UndefinedSymbolData) {
318 // Build section lookup table.
319 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
321 for (MCAssembler::iterator it = Asm.begin(),
322 ie = Asm.end(); it != ie; ++it, ++Index)
323 SectionIndexMap[&it->getSection()] = Index;
324 assert(Index <= 256 && "Too many sections!");
326 // Index 0 is always the empty string.
327 StringMap<uint64_t> StringIndexMap;
328 StringTable += '\x00';
330 // Build the symbol arrays and the string table, but only for non-local
333 // The particular order that we collect the symbols and create the string
334 // table, then sort the symbols is chosen to match 'as'. Even though it
335 // doesn't matter for correctness, this is important for letting us diff .o
337 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
338 ie = Asm.symbol_end(); it != ie; ++it) {
339 MCSymbol &Symbol = it->getSymbol();
341 if (!it->isExternal())
344 uint64_t &Entry = StringIndexMap[Symbol.getName()];
346 Entry = StringTable.size();
347 StringTable += Symbol.getName();
348 StringTable += '\x00';
353 MSD.StringIndex = Entry;
355 if (Symbol.isUndefined()) {
356 MSD.SectionIndex = 0;
357 UndefinedSymbolData.push_back(MSD);
358 } else if (Symbol.isAbsolute()) {
359 MSD.SectionIndex = 0;
360 ExternalSymbolData.push_back(MSD);
362 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
363 assert(MSD.SectionIndex && "Invalid section index!");
364 ExternalSymbolData.push_back(MSD);
368 // Now add the data for local symbols.
369 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
370 ie = Asm.symbol_end(); it != ie; ++it) {
371 MCSymbol &Symbol = it->getSymbol();
373 if (it->isExternal())
376 uint64_t &Entry = StringIndexMap[Symbol.getName()];
378 Entry = StringTable.size();
379 StringTable += Symbol.getName();
380 StringTable += '\x00';
385 MSD.StringIndex = Entry;
387 assert(!Symbol.isUndefined() && "Local symbol can not be undefined!");
388 if (Symbol.isAbsolute()) {
389 MSD.SectionIndex = 0;
390 LocalSymbolData.push_back(MSD);
392 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
393 assert(MSD.SectionIndex && "Invalid section index!");
394 LocalSymbolData.push_back(MSD);
398 // External and undefined symbols are required to be in lexicographic order.
399 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
400 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
402 // The string table is padded to a multiple of 4.
404 // FIXME: Check to see if this varies per arch.
405 while (StringTable.size() % 4)
406 StringTable += '\x00';
409 void WriteObject(MCAssembler &Asm) {
410 unsigned NumSections = Asm.size();
412 // Compute symbol table information.
413 SmallString<256> StringTable;
414 std::vector<MachSymbolData> LocalSymbolData;
415 std::vector<MachSymbolData> ExternalSymbolData;
416 std::vector<MachSymbolData> UndefinedSymbolData;
417 unsigned NumSymbols = Asm.symbol_size();
419 // No symbol table command is written if there are no symbols.
421 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
422 UndefinedSymbolData);
424 // Compute the file offsets for all the sections in advance, so that we can
425 // write things out in order.
426 SmallVector<uint64_t, 16> SectionFileOffsets;
427 SectionFileOffsets.resize(NumSections);
429 // The section data starts after the header, the segment load command (and
430 // section headers) and the symbol table.
431 unsigned NumLoadCommands = 1;
432 uint64_t LoadCommandsSize =
433 SegmentLoadCommand32Size + NumSections * Section32Size;
435 // Add the symbol table load command sizes, if used.
437 NumLoadCommands += 2;
438 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
441 uint64_t FileOffset = Header32Size + LoadCommandsSize;
442 uint64_t SectionDataStartOffset = FileOffset;
443 uint64_t SectionDataSize = 0;
445 for (MCAssembler::iterator it = Asm.begin(),
446 ie = Asm.end(); it != ie; ++it, ++Index) {
447 SectionFileOffsets[Index] = FileOffset;
448 FileOffset += it->getFileSize();
449 SectionDataSize += it->getFileSize();
452 // Write the prolog, starting with the header and load command...
453 WriteHeader32(NumLoadCommands, LoadCommandsSize);
454 WriteSegmentLoadCommand32(NumSections, SectionDataStartOffset,
457 // ... and then the section headers.
459 for (MCAssembler::iterator it = Asm.begin(),
460 ie = Asm.end(); it != ie; ++it, ++Index)
461 WriteSection32(*it, SectionFileOffsets[Index]);
463 // Write the symbol table load command, if used.
465 // The string table is written after all the section data.
466 uint64_t SymbolTableOffset = SectionDataStartOffset + SectionDataSize;
467 uint64_t StringTableOffset =
468 SymbolTableOffset + NumSymbols * Nlist32Size;
469 WriteSymtabLoadCommand(SymbolTableOffset, NumSymbols,
470 StringTableOffset, StringTable.size());
472 unsigned FirstLocalSymbol = 0;
473 unsigned NumLocalSymbols = LocalSymbolData.size();
474 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
475 unsigned NumExternalSymbols = ExternalSymbolData.size();
476 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
477 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
478 // FIXME: Get correct symbol indices and counts for indirect symbols.
479 unsigned IndirectSymbolOffset = 0;
480 unsigned NumIndirectSymbols = 0;
481 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
482 FirstExternalSymbol, NumExternalSymbols,
483 FirstUndefinedSymbol, NumUndefinedSymbols,
484 IndirectSymbolOffset, NumIndirectSymbols);
487 // Write the actual section data.
488 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
489 WriteFileData(OS, *it, *this);
491 // Write the symbol table data, if used.
493 // FIXME: Check that offsets match computed ones.
495 // FIXME: Some of these are ordered by name to help the linker.
497 // Write the symbol table entries.
498 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
499 WriteNlist32(LocalSymbolData[i]);
500 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
501 WriteNlist32(ExternalSymbolData[i]);
502 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
503 WriteNlist32(UndefinedSymbolData[i]);
505 // Write the string table.
506 OS << StringTable.str();
513 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
516 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *SD)
518 FileSize(~UINT64_C(0))
521 SD->getFragmentList().push_back(this);
524 MCFragment::~MCFragment() {
529 MCSectionData::MCSectionData() : Section(*(MCSection*)0) {}
531 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
534 FileSize(~UINT64_C(0))
537 A->getSectionList().push_back(this);
542 MCSymbolData::MCSymbolData() : Symbol(*(MCSymbol*)0) {}
544 MCSymbolData::MCSymbolData(MCSymbol &_Symbol, MCFragment *_Fragment,
545 uint64_t _Offset, MCAssembler *A)
546 : Symbol(_Symbol), Fragment(_Fragment), Offset(_Offset),
550 A->getSymbolList().push_back(this);
555 MCAssembler::MCAssembler(raw_ostream &_OS) : OS(_OS) {}
557 MCAssembler::~MCAssembler() {
560 void MCAssembler::LayoutSection(MCSectionData &SD) {
563 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
568 // Evaluate fragment size.
569 switch (F.getKind()) {
570 case MCFragment::FT_Align: {
571 MCAlignFragment &AF = cast<MCAlignFragment>(F);
573 uint64_t AlignedOffset = RoundUpToAlignment(Offset, AF.getAlignment());
574 uint64_t PaddingBytes = AlignedOffset - Offset;
576 if (PaddingBytes > AF.getMaxBytesToEmit())
579 AF.setFileSize(PaddingBytes);
583 case MCFragment::FT_Data:
584 case MCFragment::FT_Fill:
585 F.setFileSize(F.getMaxFileSize());
588 case MCFragment::FT_Org: {
589 MCOrgFragment &OF = cast<MCOrgFragment>(F);
591 if (!OF.getOffset().isAbsolute())
592 llvm_unreachable("FIXME: Not yet implemented!");
593 uint64_t OrgOffset = OF.getOffset().getConstant();
595 // FIXME: We need a way to communicate this error.
596 if (OrgOffset < Offset)
597 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
598 "' (section offset '" + Twine(Offset) + "'");
600 F.setFileSize(OrgOffset - Offset);
605 Offset += F.getFileSize();
608 // FIXME: Pad section?
609 SD.setFileSize(Offset);
612 /// WriteFileData - Write the \arg F data to the output file.
613 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
614 MachObjectWriter &MOW) {
615 uint64_t Start = OS.tell();
618 // FIXME: Embed in fragments instead?
619 switch (F.getKind()) {
620 case MCFragment::FT_Align: {
621 MCAlignFragment &AF = cast<MCAlignFragment>(F);
622 uint64_t Count = AF.getFileSize() / AF.getValueSize();
624 // FIXME: This error shouldn't actually occur (the front end should emit
625 // multiple .align directives to enforce the semantics it wants), but is
626 // severe enough that we want to report it. How to handle this?
627 if (Count * AF.getValueSize() != AF.getFileSize())
628 llvm_report_error("undefined .align directive, value size '" +
629 Twine(AF.getValueSize()) +
630 "' is not a divisor of padding size '" +
631 Twine(AF.getFileSize()) + "'");
633 for (uint64_t i = 0; i != Count; ++i) {
634 switch (AF.getValueSize()) {
636 assert(0 && "Invalid size!");
637 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
638 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
639 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
640 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
646 case MCFragment::FT_Data:
647 OS << cast<MCDataFragment>(F).getContents().str();
650 case MCFragment::FT_Fill: {
651 MCFillFragment &FF = cast<MCFillFragment>(F);
653 if (!FF.getValue().isAbsolute())
654 llvm_unreachable("FIXME: Not yet implemented!");
655 int64_t Value = FF.getValue().getConstant();
657 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
658 switch (FF.getValueSize()) {
660 assert(0 && "Invalid size!");
661 case 1: MOW.Write8 (uint8_t (Value)); break;
662 case 2: MOW.Write16(uint16_t(Value)); break;
663 case 4: MOW.Write32(uint32_t(Value)); break;
664 case 8: MOW.Write64(uint64_t(Value)); break;
670 case MCFragment::FT_Org: {
671 MCOrgFragment &OF = cast<MCOrgFragment>(F);
673 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
674 MOW.Write8(uint8_t(OF.getValue()));
680 assert(OS.tell() - Start == F.getFileSize());
683 /// WriteFileData - Write the \arg SD data to the output file.
684 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
685 MachObjectWriter &MOW) {
686 uint64_t Start = OS.tell();
689 for (MCSectionData::const_iterator it = SD.begin(),
690 ie = SD.end(); it != ie; ++it)
691 WriteFileData(OS, *it, MOW);
693 assert(OS.tell() - Start == SD.getFileSize());
696 void MCAssembler::Finish() {
697 // Layout the sections and fragments.
698 for (iterator it = begin(), ie = end(); it != ie; ++it)
701 // Write the object file.
702 MachObjectWriter MOW(OS);
703 MOW.WriteObject(*this);