llvm-mc/Mach-O: Move more logic for writing the Mach-O file into the writer
[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/Twine.h"
13 #include "llvm/MC/MCSectionMachO.h"
14 #include "llvm/Support/DataTypes.h"
15 #include "llvm/Support/ErrorHandling.h"
16 #include "llvm/Support/raw_ostream.h"
17 #include "llvm/Target/TargetMachOWriterInfo.h"
18
19 using namespace llvm;
20
21 namespace {
22
23 class MachObjectWriter {
24   // See <mach-o/loader.h>.
25   enum {
26     Header_Magic32 = 0xFEEDFACE,
27     Header_Magic64 = 0xFEEDFACF
28   };
29   
30   static const unsigned Header32Size = 28;
31   static const unsigned Header64Size = 32;
32   static const unsigned SegmentLoadCommand32Size = 56;
33   static const unsigned Section32Size = 68;
34
35   enum HeaderFileType {
36     HFT_Object = 0x1
37   };
38
39   enum LoadCommandType {
40     LCT_Segment = 0x1
41   };
42
43   raw_ostream &OS;
44   bool IsLSB;
45
46 public:
47   MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true) 
48     : OS(_OS), IsLSB(_IsLSB) {
49   }
50
51   /// @name Helper Methods
52   /// @{
53
54   void Write8(uint8_t Value) {
55     OS << char(Value);
56   }
57
58   void Write16(uint16_t Value) {
59     if (IsLSB) {
60       Write8(uint8_t(Value >> 0));
61       Write8(uint8_t(Value >> 8));
62     } else {
63       Write8(uint8_t(Value >> 8));
64       Write8(uint8_t(Value >> 0));
65     }
66   }
67
68   void Write32(uint32_t Value) {
69     if (IsLSB) {
70       Write16(uint16_t(Value >> 0));
71       Write16(uint16_t(Value >> 16));
72     } else {
73       Write16(uint16_t(Value >> 16));
74       Write16(uint16_t(Value >> 0));
75     }
76   }
77
78   void Write64(uint64_t Value) {
79     if (IsLSB) {
80       Write32(uint32_t(Value >> 0));
81       Write32(uint32_t(Value >> 32));
82     } else {
83       Write32(uint32_t(Value >> 32));
84       Write32(uint32_t(Value >> 0));
85     }
86   }
87
88   void WriteZeros(unsigned N) {
89     const char Zeros[16] = { 0 };
90     
91     for (unsigned i = 0, e = N / 16; i != e; ++i)
92       OS << StringRef(Zeros, 16);
93     
94     OS << StringRef(Zeros, N % 16);
95   }
96
97   void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
98     OS << Str;
99     if (ZeroFillSize)
100       WriteZeros(ZeroFillSize - Str.size());
101   }
102
103   /// @}
104   
105   void WriteHeader32(unsigned NumSections) {
106     // struct mach_header (28 bytes)
107
108     uint64_t Start = OS.tell();
109     (void) Start;
110
111     Write32(Header_Magic32);
112
113     // FIXME: Support cputype.
114     Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
115
116     // FIXME: Support cpusubtype.
117     Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
118
119     Write32(HFT_Object);
120
121     // Object files have a single load command, the segment.
122     Write32(1);
123     Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
124     Write32(0); // Flags
125
126     assert(OS.tell() - Start == Header32Size);
127   }
128
129   void WriteLoadCommandHeader(uint32_t Cmd, uint32_t CmdSize) {
130     assert((CmdSize & 0x3) == 0 && "Invalid size!");
131
132     Write32(Cmd);
133     Write32(CmdSize);
134   }
135
136   /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
137   ///
138   /// \arg NumSections - The number of sections in this segment.
139   /// \arg SectionDataSize - The total size of the sections.
140   void WriteSegmentLoadCommand32(unsigned NumSections,
141                                  uint64_t SectionDataSize) {
142     // struct segment_command (56 bytes)
143
144     uint64_t Start = OS.tell();
145     (void) Start;
146
147     Write32(LCT_Segment);
148     Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
149
150     WriteString("", 16);
151     Write32(0); // vmaddr
152     Write32(SectionDataSize); // vmsize
153     Write32(Header32Size + SegmentLoadCommand32Size + 
154             NumSections * Section32Size); // file offset
155     Write32(SectionDataSize); // file size
156     Write32(0x7); // maxprot
157     Write32(0x7); // initprot
158     Write32(NumSections);
159     Write32(0); // flags
160
161     assert(OS.tell() - Start == SegmentLoadCommand32Size);
162   }
163
164   void WriteSection32(const MCSectionData &SD, uint64_t FileOffset) {
165     // struct section (68 bytes)
166
167     uint64_t Start = OS.tell();
168     (void) Start;
169
170     // FIXME: cast<> support!
171     const MCSectionMachO &Section =
172       static_cast<const MCSectionMachO&>(SD.getSection());
173     WriteString(Section.getSectionName(), 16);
174     WriteString(Section.getSegmentName(), 16);
175     Write32(0); // address
176     Write32(SD.getFileSize()); // size
177     Write32(FileOffset);
178
179     assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
180     Write32(Log2_32(SD.getAlignment()));
181     Write32(0); // file offset of relocation entries
182     Write32(0); // number of relocation entrions
183     Write32(Section.getTypeAndAttributes());
184     Write32(0); // reserved1
185     Write32(Section.getStubSize()); // reserved2
186
187     assert(OS.tell() - Start == Section32Size);
188   }
189
190   void WriteProlog(MCAssembler &Asm) {
191     unsigned NumSections = Asm.size();
192
193     // Compute the file offsets for all the sections in advance, so that we can
194     // write things out in order.
195     SmallVector<uint64_t, 16> SectionFileOffsets;
196     SectionFileOffsets.resize(NumSections);
197   
198     // The section data starts after the header, the segment load command, and
199     // the section headers.
200     uint64_t FileOffset = Header32Size + SegmentLoadCommand32Size + 
201       NumSections * Section32Size;
202     uint64_t SectionDataSize = 0;
203     unsigned Index = 0;
204     for (MCAssembler::iterator it = Asm.begin(),
205            ie = Asm.end(); it != ie; ++it, ++Index) {
206       SectionFileOffsets[Index] = FileOffset;
207       FileOffset += it->getFileSize();
208       SectionDataSize += it->getFileSize();
209     }
210
211     // Write the prolog, starting with the header and load command...
212     WriteHeader32(NumSections);
213     WriteSegmentLoadCommand32(NumSections, SectionDataSize);
214   
215     // ... and then the section headers.
216     Index = 0;
217     for (MCAssembler::iterator it = Asm.begin(),
218            ie = Asm.end(); it != ie; ++it, ++Index)
219       WriteSection32(*it, SectionFileOffsets[Index]);
220   }
221
222 };
223
224 }
225
226 /* *** */
227
228 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
229 }
230
231 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *SD)
232   : Kind(_Kind),
233     FileSize(~UINT64_C(0))
234 {
235   if (SD)
236     SD->getFragmentList().push_back(this);
237 }
238
239 MCFragment::~MCFragment() {
240 }
241
242 /* *** */
243
244 MCSectionData::MCSectionData() : Section(*(MCSection*)0) {}
245
246 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
247   : Section(_Section),
248     Alignment(1),
249     FileSize(~UINT64_C(0))
250 {
251   if (A)
252     A->getSectionList().push_back(this);
253 }
254
255 /* *** */
256
257 MCAssembler::MCAssembler(raw_ostream &_OS) : OS(_OS) {}
258
259 MCAssembler::~MCAssembler() {
260 }
261
262 void MCAssembler::LayoutSection(MCSectionData &SD) {
263   uint64_t Offset = 0;
264
265   for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
266     MCFragment &F = *it;
267
268     F.setOffset(Offset);
269
270     // Evaluate fragment size.
271     switch (F.getKind()) {
272     case MCFragment::FT_Align: {
273       MCAlignFragment &AF = cast<MCAlignFragment>(F);
274       
275       uint64_t AlignedOffset = RoundUpToAlignment(Offset, AF.getAlignment());
276       uint64_t PaddingBytes = AlignedOffset - Offset;
277
278       if (PaddingBytes > AF.getMaxBytesToEmit())
279         AF.setFileSize(0);
280       else
281         AF.setFileSize(PaddingBytes);
282       break;
283     }
284
285     case MCFragment::FT_Data:
286     case MCFragment::FT_Fill:
287       F.setFileSize(F.getMaxFileSize());
288       break;
289
290     case MCFragment::FT_Org: {
291       MCOrgFragment &OF = cast<MCOrgFragment>(F);
292
293       if (!OF.getOffset().isAbsolute())
294         llvm_unreachable("FIXME: Not yet implemented!");
295       uint64_t OrgOffset = OF.getOffset().getConstant();
296
297       // FIXME: We need a way to communicate this error.
298       if (OrgOffset < Offset)
299         llvm_report_error("invalid .org offset '" + Twine(OrgOffset) + 
300                           "' (section offset '" + Twine(Offset) + "'");
301         
302       F.setFileSize(OrgOffset - Offset);
303       break;
304     }      
305     }
306
307     Offset += F.getFileSize();
308   }
309
310   // FIXME: Pad section?
311   SD.setFileSize(Offset);
312 }
313
314 /// WriteFileData - Write the \arg F data to the output file.
315 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
316                           MachObjectWriter &MOW) {
317   uint64_t Start = OS.tell();
318   (void) Start;
319     
320   // FIXME: Embed in fragments instead?
321   switch (F.getKind()) {
322   case MCFragment::FT_Align: {
323     MCAlignFragment &AF = cast<MCAlignFragment>(F);
324     uint64_t Count = AF.getFileSize() / AF.getValueSize();
325
326     // FIXME: This error shouldn't actually occur (the front end should emit
327     // multiple .align directives to enforce the semantics it wants), but is
328     // severe enough that we want to report it. How to handle this?
329     if (Count * AF.getValueSize() != AF.getFileSize())
330       llvm_report_error("undefined .align directive, value size '" + 
331                         Twine(AF.getValueSize()) + 
332                         "' is not a divisor of padding size '" +
333                         Twine(AF.getFileSize()) + "'");
334
335     for (uint64_t i = 0; i != Count; ++i) {
336       switch (AF.getValueSize()) {
337       default:
338         assert(0 && "Invalid size!");
339       case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
340       case 2: MOW.Write16(uint16_t(AF.getValue())); break;
341       case 4: MOW.Write32(uint32_t(AF.getValue())); break;
342       case 8: MOW.Write64(uint64_t(AF.getValue())); break;
343       }
344     }
345     break;
346   }
347
348   case MCFragment::FT_Data:
349     OS << cast<MCDataFragment>(F).getContents().str();
350     break;
351
352   case MCFragment::FT_Fill: {
353     MCFillFragment &FF = cast<MCFillFragment>(F);
354
355     if (!FF.getValue().isAbsolute())
356       llvm_unreachable("FIXME: Not yet implemented!");
357     int64_t Value = FF.getValue().getConstant();
358
359     for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
360       switch (FF.getValueSize()) {
361       default:
362         assert(0 && "Invalid size!");
363       case 1: MOW.Write8 (uint8_t (Value)); break;
364       case 2: MOW.Write16(uint16_t(Value)); break;
365       case 4: MOW.Write32(uint32_t(Value)); break;
366       case 8: MOW.Write64(uint64_t(Value)); break;
367       }
368     }
369     break;
370   }
371     
372   case MCFragment::FT_Org: {
373     MCOrgFragment &OF = cast<MCOrgFragment>(F);
374
375     for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
376       MOW.Write8(uint8_t(OF.getValue()));
377
378     break;
379   }
380   }
381
382   assert(OS.tell() - Start == F.getFileSize());
383 }
384
385 /// WriteFileData - Write the \arg SD data to the output file.
386 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
387                           MachObjectWriter &MOW) {
388   uint64_t Start = OS.tell();
389   (void) Start;
390       
391   for (MCSectionData::const_iterator it = SD.begin(),
392          ie = SD.end(); it != ie; ++it)
393     WriteFileData(OS, *it, MOW);
394
395   assert(OS.tell() - Start == SD.getFileSize());
396 }
397
398 void MCAssembler::Finish() {
399   // Layout the sections and fragments.
400   for (iterator it = begin(), ie = end(); it != ie; ++it)
401     LayoutSection(*it);
402
403   MachObjectWriter MOW(OS);
404
405   // Write the prolog, followed by the data for all the sections & fragments.
406   MOW.WriteProlog(*this);
407
408   // FIXME: This should move into the Mach-O writer, it should have control over
409   // what goes where.
410   for (iterator it = begin(), ie = end(); it != ie; ++it)
411     WriteFileData(OS, *it, MOW);
412
413   OS.flush();
414 }