llvm-mc/Mach-O: Improve symbol table support:
[oota-llvm.git] / lib / MC / MCAssembler.cpp
1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/MC/MCAssembler.h"
11
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"
21
22 using namespace llvm;
23
24 class MachObjectWriter;
25
26 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
27                           MachObjectWriter &MOW);
28
29 class MachObjectWriter {
30   // See <mach-o/loader.h>.
31   enum {
32     Header_Magic32 = 0xFEEDFACE,
33     Header_Magic64 = 0xFEEDFACF
34   };
35   
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;
43
44   enum HeaderFileType {
45     HFT_Object = 0x1
46   };
47
48   enum LoadCommandType {
49     LCT_Segment = 0x1,
50     LCT_Symtab = 0x2,
51     LCT_Dysymtab = 0xb
52   };
53
54   // See <mach-o/nlist.h>.
55   enum SymbolTypeType {
56     STT_Undefined = 0x00,
57     STT_Absolute  = 0x02,
58     STT_Section   = 0x0e
59   };
60
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,
65
66     STF_TypeMask       = 0x0e,
67     STF_External       = 0x01,
68     STF_PrivateExtern  = 0x10
69   };
70
71   /// MachSymbolData - Helper struct for containing some precomputed information
72   /// on symbols.
73   struct MachSymbolData {
74     MCSymbolData *SymbolData;
75     uint64_t StringIndex;
76     uint8_t SectionIndex;
77
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();
82     }
83   };
84
85   raw_ostream &OS;
86   bool IsLSB;
87
88 public:
89   MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true) 
90     : OS(_OS), IsLSB(_IsLSB) {
91   }
92
93   /// @name Helper Methods
94   /// @{
95
96   void Write8(uint8_t Value) {
97     OS << char(Value);
98   }
99
100   void Write16(uint16_t Value) {
101     if (IsLSB) {
102       Write8(uint8_t(Value >> 0));
103       Write8(uint8_t(Value >> 8));
104     } else {
105       Write8(uint8_t(Value >> 8));
106       Write8(uint8_t(Value >> 0));
107     }
108   }
109
110   void Write32(uint32_t Value) {
111     if (IsLSB) {
112       Write16(uint16_t(Value >> 0));
113       Write16(uint16_t(Value >> 16));
114     } else {
115       Write16(uint16_t(Value >> 16));
116       Write16(uint16_t(Value >> 0));
117     }
118   }
119
120   void Write64(uint64_t Value) {
121     if (IsLSB) {
122       Write32(uint32_t(Value >> 0));
123       Write32(uint32_t(Value >> 32));
124     } else {
125       Write32(uint32_t(Value >> 32));
126       Write32(uint32_t(Value >> 0));
127     }
128   }
129
130   void WriteZeros(unsigned N) {
131     const char Zeros[16] = { 0 };
132     
133     for (unsigned i = 0, e = N / 16; i != e; ++i)
134       OS << StringRef(Zeros, 16);
135     
136     OS << StringRef(Zeros, N % 16);
137   }
138
139   void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
140     OS << Str;
141     if (ZeroFillSize)
142       WriteZeros(ZeroFillSize - Str.size());
143   }
144
145   /// @}
146   
147   void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize) {
148     // struct mach_header (28 bytes)
149
150     uint64_t Start = OS.tell();
151     (void) Start;
152
153     Write32(Header_Magic32);
154
155     // FIXME: Support cputype.
156     Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
157
158     // FIXME: Support cpusubtype.
159     Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
160
161     Write32(HFT_Object);
162
163     // Object files have a single load command, the segment.
164     Write32(NumLoadCommands);
165     Write32(LoadCommandsSize);
166     Write32(0); // Flags
167
168     assert(OS.tell() - Start == Header32Size);
169   }
170
171   /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
172   ///
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)
179
180     uint64_t Start = OS.tell();
181     (void) Start;
182
183     Write32(LCT_Segment);
184     Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
185
186     WriteString("", 16);
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);
194     Write32(0); // flags
195
196     assert(OS.tell() - Start == SegmentLoadCommand32Size);
197   }
198
199   void WriteSection32(const MCSectionData &SD, uint64_t FileOffset) {
200     // struct section (68 bytes)
201
202     uint64_t Start = OS.tell();
203     (void) Start;
204
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
212     Write32(FileOffset);
213
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
221
222     assert(OS.tell() - Start == Section32Size);
223   }
224
225   void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
226                               uint32_t StringTableOffset,
227                               uint32_t StringTableSize) {
228     // struct symtab_command (24 bytes)
229
230     uint64_t Start = OS.tell();
231     (void) Start;
232
233     Write32(LCT_Symtab);
234     Write32(SymtabLoadCommandSize);
235     Write32(SymbolOffset);
236     Write32(NumSymbols);
237     Write32(StringTableOffset);
238     Write32(StringTableSize);
239
240     assert(OS.tell() - Start == SymtabLoadCommandSize);
241   }
242
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)
252
253     uint64_t Start = OS.tell();
254     (void) Start;
255
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
265     Write32(0); // ntoc
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
276
277     assert(OS.tell() - Start == DysymtabLoadCommandSize);
278   }
279
280   void WriteNlist32(MachSymbolData &MSD) {
281     MCSymbol &Symbol = MSD.SymbolData->getSymbol();
282     uint8_t Type = 0;
283
284     // Set the N_TYPE bits. See <mach-o/nlist.h>.
285     //
286     // FIXME: Are the prebound or indirect fields possible here?
287     if (Symbol.isUndefined())
288       Type = STT_Undefined;
289     else if (Symbol.isAbsolute())
290       Type = STT_Absolute;
291     else
292       Type = STT_Section;
293
294     // FIXME: Set STAB bits.
295
296     // FIXME: Set private external bit.
297
298     // Set external bit.
299     if (MSD.SymbolData->isExternal())
300       Type |= STF_External;
301
302     // struct nlist (12 bytes)
303
304     Write32(MSD.StringIndex);
305     Write8(Type);
306     Write8(MSD.SectionIndex);
307     Write16(0); // FIXME: Desc
308     Write32(0); // FIXME: Value
309   }
310
311   /// ComputeSymbolTable - Compute the symbol table data
312   ///
313   /// \param StringTable [out] - The string table data.
314   /// \param StringIndexMap [out] - Map from symbol names to offsets in the
315   /// string table.
316
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;
323     unsigned Index = 1;
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!");
328
329     // Index 0 is always the empty string.
330     StringMap<uint64_t> StringIndexMap;
331     StringTable += '\x00';
332
333     // Build the symbol arrays and the string table, but only for non-local
334     // symbols.
335     //
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
339     // files.
340     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
341            ie = Asm.symbol_end(); it != ie; ++it) {
342       MCSymbol &Symbol = it->getSymbol();
343
344       if (!it->isExternal())
345         continue;
346
347       uint64_t &Entry = StringIndexMap[Symbol.getName()];
348       if (!Entry) {
349         Entry = StringTable.size();
350         StringTable += Symbol.getName();
351         StringTable += '\x00';
352       }
353
354       MachSymbolData MSD;
355       MSD.SymbolData = it;
356       MSD.StringIndex = Entry;
357
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);
364       } else {
365         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
366         assert(MSD.SectionIndex && "Invalid section index!");
367         ExternalSymbolData.push_back(MSD);
368       }
369     }
370
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();
375
376       if (it->isExternal())
377         continue;
378
379       uint64_t &Entry = StringIndexMap[Symbol.getName()];
380       if (!Entry) {
381         Entry = StringTable.size();
382         StringTable += Symbol.getName();
383         StringTable += '\x00';
384       }
385
386       MachSymbolData MSD;
387       MSD.SymbolData = it;
388       MSD.StringIndex = Entry;
389
390       assert(!Symbol.isUndefined() && "Local symbol can not be undefined!");
391       if (Symbol.isAbsolute()) {
392         MSD.SectionIndex = 0;
393         LocalSymbolData.push_back(MSD);
394       } else {
395         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
396         assert(MSD.SectionIndex && "Invalid section index!");
397         LocalSymbolData.push_back(MSD);
398       }
399     }
400
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());
404
405     // The string table is padded to a multiple of 4.
406     //
407     // FIXME: Check to see if this varies per arch.
408     while (StringTable.size() % 4)
409       StringTable += '\x00';
410   }
411
412   void WriteObject(MCAssembler &Asm) {
413     unsigned NumSections = Asm.size();
414
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();
421
422     // No symbol table command is written if there are no symbols.
423     if (NumSymbols)
424       ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
425                          UndefinedSymbolData);
426
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);
431   
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;
437
438     // Add the symbol table load command sizes, if used.
439     if (NumSymbols) {
440       NumLoadCommands += 2;
441       LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
442     }
443
444     uint64_t FileOffset = Header32Size + LoadCommandsSize;
445     uint64_t SectionDataStartOffset = FileOffset;
446     uint64_t SectionDataSize = 0;
447     unsigned Index = 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();
453     }
454
455     // Write the prolog, starting with the header and load command...
456     WriteHeader32(NumLoadCommands, LoadCommandsSize);
457     WriteSegmentLoadCommand32(NumSections, SectionDataStartOffset,
458                               SectionDataSize);
459   
460     // ... and then the section headers.
461     Index = 0;
462     for (MCAssembler::iterator it = Asm.begin(),
463            ie = Asm.end(); it != ie; ++it, ++Index)
464       WriteSection32(*it, SectionFileOffsets[Index]);
465
466     // Write the symbol table load command, if used.
467     if (NumSymbols) {
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());
474
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);
488     }
489
490     // Write the actual section data.
491     for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
492       WriteFileData(OS, *it, *this);
493
494     // Write the symbol table data, if used.
495     if (NumSymbols) {
496       // FIXME: Check that offsets match computed ones.
497
498       // FIXME: Some of these are ordered by name to help the linker.
499
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]);
507
508       // Write the string table.
509       OS << StringTable.str();
510     }
511   }
512 };
513
514 /* *** */
515
516 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
517 }
518
519 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *SD)
520   : Kind(_Kind),
521     FileSize(~UINT64_C(0))
522 {
523   if (SD)
524     SD->getFragmentList().push_back(this);
525 }
526
527 MCFragment::~MCFragment() {
528 }
529
530 /* *** */
531
532 MCSectionData::MCSectionData() : Section(*(MCSection*)0) {}
533
534 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
535   : Section(_Section),
536     Alignment(1),
537     FileSize(~UINT64_C(0))
538 {
539   if (A)
540     A->getSectionList().push_back(this);
541 }
542
543 /* *** */
544
545 MCSymbolData::MCSymbolData() : Symbol(*(MCSymbol*)0) {}
546
547 MCSymbolData::MCSymbolData(MCSymbol &_Symbol, MCFragment *_Fragment,
548                            uint64_t _Offset, MCAssembler *A)
549   : Symbol(_Symbol), Fragment(_Fragment), Offset(_Offset),
550     IsExternal(false)
551 {
552   if (A)
553     A->getSymbolList().push_back(this);
554 }
555
556 /* *** */
557
558 MCAssembler::MCAssembler(raw_ostream &_OS) : OS(_OS) {}
559
560 MCAssembler::~MCAssembler() {
561 }
562
563 void MCAssembler::LayoutSection(MCSectionData &SD) {
564   uint64_t Offset = 0;
565
566   for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
567     MCFragment &F = *it;
568
569     F.setOffset(Offset);
570
571     // Evaluate fragment size.
572     switch (F.getKind()) {
573     case MCFragment::FT_Align: {
574       MCAlignFragment &AF = cast<MCAlignFragment>(F);
575       
576       uint64_t AlignedOffset = RoundUpToAlignment(Offset, AF.getAlignment());
577       uint64_t PaddingBytes = AlignedOffset - Offset;
578
579       if (PaddingBytes > AF.getMaxBytesToEmit())
580         AF.setFileSize(0);
581       else
582         AF.setFileSize(PaddingBytes);
583       break;
584     }
585
586     case MCFragment::FT_Data:
587     case MCFragment::FT_Fill:
588       F.setFileSize(F.getMaxFileSize());
589       break;
590
591     case MCFragment::FT_Org: {
592       MCOrgFragment &OF = cast<MCOrgFragment>(F);
593
594       if (!OF.getOffset().isAbsolute())
595         llvm_unreachable("FIXME: Not yet implemented!");
596       uint64_t OrgOffset = OF.getOffset().getConstant();
597
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) + "'");
602         
603       F.setFileSize(OrgOffset - Offset);
604       break;
605     }      
606     }
607
608     Offset += F.getFileSize();
609   }
610
611   // FIXME: Pad section?
612   SD.setFileSize(Offset);
613 }
614
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();
619   (void) Start;
620     
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();
626
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()) + "'");
635
636     for (uint64_t i = 0; i != Count; ++i) {
637       switch (AF.getValueSize()) {
638       default:
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;
644       }
645     }
646     break;
647   }
648
649   case MCFragment::FT_Data:
650     OS << cast<MCDataFragment>(F).getContents().str();
651     break;
652
653   case MCFragment::FT_Fill: {
654     MCFillFragment &FF = cast<MCFillFragment>(F);
655
656     if (!FF.getValue().isAbsolute())
657       llvm_unreachable("FIXME: Not yet implemented!");
658     int64_t Value = FF.getValue().getConstant();
659
660     for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
661       switch (FF.getValueSize()) {
662       default:
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;
668       }
669     }
670     break;
671   }
672     
673   case MCFragment::FT_Org: {
674     MCOrgFragment &OF = cast<MCOrgFragment>(F);
675
676     for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
677       MOW.Write8(uint8_t(OF.getValue()));
678
679     break;
680   }
681   }
682
683   assert(OS.tell() - Start == F.getFileSize());
684 }
685
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();
690   (void) Start;
691       
692   for (MCSectionData::const_iterator it = SD.begin(),
693          ie = SD.end(); it != ie; ++it)
694     WriteFileData(OS, *it, MOW);
695
696   assert(OS.tell() - Start == SD.getFileSize());
697 }
698
699 void MCAssembler::Finish() {
700   // Layout the sections and fragments.
701   for (iterator it = begin(), ie = end(); it != ie; ++it)
702     LayoutSection(*it);
703
704   // Write the object file.
705   MachObjectWriter MOW(OS);
706   MOW.WriteObject(*this);
707
708   OS.flush();
709 }