llvm-mc: Rename / redefine MCFragment::FileOffset to MCFragment::Offset (the
[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   static unsigned getPrologSize32(unsigned NumSections) {
106     return Header32Size + SegmentLoadCommand32Size + 
107       NumSections * Section32Size;
108   }
109
110   void WriteHeader32(unsigned NumSections) {
111     // struct mach_header (28 bytes)
112
113     uint64_t Start = OS.tell();
114     (void) Start;
115
116     Write32(Header_Magic32);
117
118     // FIXME: Support cputype.
119     Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
120
121     // FIXME: Support cpusubtype.
122     Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
123
124     Write32(HFT_Object);
125
126     // Object files have a single load command, the segment.
127     Write32(1);
128     Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
129     Write32(0); // Flags
130
131     assert(OS.tell() - Start == Header32Size);
132   }
133
134   void WriteLoadCommandHeader(uint32_t Cmd, uint32_t CmdSize) {
135     assert((CmdSize & 0x3) == 0 && "Invalid size!");
136
137     Write32(Cmd);
138     Write32(CmdSize);
139   }
140
141   /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
142   ///
143   /// \arg NumSections - The number of sections in this segment.
144   /// \arg SectionDataSize - The total size of the sections.
145   void WriteSegmentLoadCommand32(unsigned NumSections,
146                                  uint64_t SectionDataSize) {
147     // struct segment_command (56 bytes)
148
149     uint64_t Start = OS.tell();
150     (void) Start;
151
152     Write32(LCT_Segment);
153     Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
154
155     WriteString("", 16);
156     Write32(0); // vmaddr
157     Write32(SectionDataSize); // vmsize
158     Write32(Header32Size + SegmentLoadCommand32Size + 
159             NumSections * Section32Size); // file offset
160     Write32(SectionDataSize); // file size
161     Write32(0x7); // maxprot
162     Write32(0x7); // initprot
163     Write32(NumSections);
164     Write32(0); // flags
165
166     assert(OS.tell() - Start == SegmentLoadCommand32Size);
167   }
168
169   void WriteSection32(const MCSectionData &SD) {
170     // struct section (68 bytes)
171
172     uint64_t Start = OS.tell();
173     (void) Start;
174
175     // FIXME: cast<> support!
176     const MCSectionMachO &Section =
177       static_cast<const MCSectionMachO&>(SD.getSection());
178     WriteString(Section.getSectionName(), 16);
179     WriteString(Section.getSegmentName(), 16);
180     Write32(0); // address
181     Write32(SD.getFileSize()); // size
182     Write32(SD.getFileOffset());
183
184     assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
185     Write32(Log2_32(SD.getAlignment()));
186     Write32(0); // file offset of relocation entries
187     Write32(0); // number of relocation entrions
188     Write32(Section.getTypeAndAttributes());
189     Write32(0); // reserved1
190     Write32(Section.getStubSize()); // reserved2
191
192     assert(OS.tell() - Start == Section32Size);
193   }
194 };
195
196 }
197
198 /* *** */
199
200 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
201 }
202
203 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *SD)
204   : Kind(_Kind),
205     FileSize(~UINT64_C(0))
206 {
207   if (SD)
208     SD->getFragmentList().push_back(this);
209 }
210
211 MCFragment::~MCFragment() {
212 }
213
214 /* *** */
215
216 MCSectionData::MCSectionData() : Section(*(MCSection*)0) {}
217
218 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
219   : Section(_Section),
220     Alignment(1),
221     FileOffset(~UINT64_C(0)),
222     FileSize(~UINT64_C(0))
223 {
224   if (A)
225     A->getSectionList().push_back(this);
226 }
227
228 /* *** */
229
230 MCAssembler::MCAssembler(raw_ostream &_OS) : OS(_OS) {}
231
232 MCAssembler::~MCAssembler() {
233 }
234
235 void MCAssembler::LayoutSection(MCSectionData &SD) {
236   uint64_t Offset = 0;
237
238   for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
239     MCFragment &F = *it;
240
241     F.setOffset(Offset);
242
243     // Evaluate fragment size.
244     switch (F.getKind()) {
245     case MCFragment::FT_Align: {
246       MCAlignFragment &AF = cast<MCAlignFragment>(F);
247       
248       uint64_t AlignedOffset = RoundUpToAlignment(Offset, AF.getAlignment());
249       uint64_t PaddingBytes = AlignedOffset - Offset;
250
251       if (PaddingBytes > AF.getMaxBytesToEmit())
252         AF.setFileSize(0);
253       else
254         AF.setFileSize(PaddingBytes);
255       break;
256     }
257
258     case MCFragment::FT_Data:
259     case MCFragment::FT_Fill:
260       F.setFileSize(F.getMaxFileSize());
261       break;
262
263     case MCFragment::FT_Org: {
264       MCOrgFragment &OF = cast<MCOrgFragment>(F);
265
266       if (!OF.getOffset().isAbsolute())
267         llvm_unreachable("FIXME: Not yet implemented!");
268       uint64_t OrgOffset = OF.getOffset().getConstant();
269
270       // FIXME: We need a way to communicate this error.
271       if (OrgOffset < Offset)
272         llvm_report_error("invalid .org offset '" + Twine(OrgOffset) + 
273                           "' (section offset '" + Twine(Offset) + "'");
274         
275       F.setFileSize(OrgOffset - Offset);
276       break;
277     }      
278     }
279
280     Offset += F.getFileSize();
281   }
282
283   // FIXME: Pad section?
284   SD.setFileSize(Offset);
285 }
286
287 /// WriteFileData - Write the \arg F data to the output file.
288 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
289                           MachObjectWriter &MOW) {
290   uint64_t Start = OS.tell();
291   (void) Start;
292     
293   // FIXME: Embed in fragments instead?
294   switch (F.getKind()) {
295   case MCFragment::FT_Align: {
296     MCAlignFragment &AF = cast<MCAlignFragment>(F);
297     uint64_t Count = AF.getFileSize() / AF.getValueSize();
298
299     // FIXME: This error shouldn't actually occur (the front end should emit
300     // multiple .align directives to enforce the semantics it wants), but is
301     // severe enough that we want to report it. How to handle this?
302     if (Count * AF.getValueSize() != AF.getFileSize())
303       llvm_report_error("undefined .align directive, value size '" + 
304                         Twine(AF.getValueSize()) + 
305                         "' is not a divisor of padding size '" +
306                         Twine(AF.getFileSize()) + "'");
307
308     for (uint64_t i = 0; i != Count; ++i) {
309       switch (AF.getValueSize()) {
310       default:
311         assert(0 && "Invalid size!");
312       case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
313       case 2: MOW.Write16(uint16_t(AF.getValue())); break;
314       case 4: MOW.Write32(uint32_t(AF.getValue())); break;
315       case 8: MOW.Write64(uint64_t(AF.getValue())); break;
316       }
317     }
318     break;
319   }
320
321   case MCFragment::FT_Data:
322     OS << cast<MCDataFragment>(F).getContents().str();
323     break;
324
325   case MCFragment::FT_Fill: {
326     MCFillFragment &FF = cast<MCFillFragment>(F);
327
328     if (!FF.getValue().isAbsolute())
329       llvm_unreachable("FIXME: Not yet implemented!");
330     int64_t Value = FF.getValue().getConstant();
331
332     for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
333       switch (FF.getValueSize()) {
334       default:
335         assert(0 && "Invalid size!");
336       case 1: MOW.Write8 (uint8_t (Value)); break;
337       case 2: MOW.Write16(uint16_t(Value)); break;
338       case 4: MOW.Write32(uint32_t(Value)); break;
339       case 8: MOW.Write64(uint64_t(Value)); break;
340       }
341     }
342     break;
343   }
344     
345   case MCFragment::FT_Org: {
346     MCOrgFragment &OF = cast<MCOrgFragment>(F);
347
348     for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
349       MOW.Write8(uint8_t(OF.getValue()));
350
351     break;
352   }
353   }
354
355   assert(OS.tell() - Start == F.getFileSize());
356 }
357
358 /// WriteFileData - Write the \arg SD data to the output file.
359 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
360                           MachObjectWriter &MOW) {
361   uint64_t Start = OS.tell();
362   (void) Start;
363       
364   for (MCSectionData::const_iterator it = SD.begin(),
365          ie = SD.end(); it != ie; ++it)
366     WriteFileData(OS, *it, MOW);
367
368   assert(OS.tell() - Start == SD.getFileSize());
369 }
370
371 void MCAssembler::Finish() {
372   unsigned NumSections = Sections.size();
373
374   // Layout the sections and fragments.
375   uint64_t Offset = MachObjectWriter::getPrologSize32(NumSections);
376   uint64_t SectionDataSize = 0;
377   for (iterator it = begin(), ie = end(); it != ie; ++it) {
378     it->setFileOffset(Offset);
379
380     LayoutSection(*it);
381
382     Offset += it->getFileSize();
383     SectionDataSize += it->getFileSize();
384   }
385
386   MachObjectWriter MOW(OS);
387
388   // Write the prolog, starting with the header and load command...
389   MOW.WriteHeader32(NumSections);
390   MOW.WriteSegmentLoadCommand32(NumSections, SectionDataSize);
391   
392   // ... and then the section headers.
393   for (iterator it = begin(), ie = end(); it != ie; ++it)
394     MOW.WriteSection32(*it);
395
396   // Finally, write the section data.
397   for (iterator it = begin(), ie = end(); it != ie; ++it)
398     WriteFileData(OS, *it, MOW);
399
400   OS.flush();
401 }