blob: f822711d4a2249f5e6c65535c506950fc48036e5 [file] [log] [blame]
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001//===- 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"
Daniel Dunbard6f761e2009-08-21 23:07:38 +000011
12#include "llvm/ADT/Twine.h"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000013#include "llvm/MC/MCSectionMachO.h"
14#include "llvm/Support/DataTypes.h"
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000015#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000016#include "llvm/Support/raw_ostream.h"
17#include "llvm/Target/TargetMachOWriterInfo.h"
18
19using namespace llvm;
20
21namespace {
22
23class 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
46public:
47 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
48 : OS(_OS), IsLSB(_IsLSB) {
49 }
50
51 /// @name Helper Methods
52 /// @{
53
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000054 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
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000068 void Write32(uint32_t Value) {
69 if (IsLSB) {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000070 Write16(uint16_t(Value >> 0));
71 Write16(uint16_t(Value >> 16));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000072 } else {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000073 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));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000085 }
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
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000105 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
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000136 /// 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) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000142 // 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
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000152 Write32(SectionDataSize); // vmsize
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000153 Write32(Header32Size + SegmentLoadCommand32Size +
154 NumSections * Section32Size); // file offset
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000155 Write32(SectionDataSize); // file size
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000156 Write32(0x7); // maxprot
157 Write32(0x7); // initprot
158 Write32(NumSections);
159 Write32(0); // flags
160
161 assert(OS.tell() - Start == SegmentLoadCommand32Size);
162 }
163
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000164 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000165 // 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
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000177 Write32(FileOffset);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000178
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 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000189
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
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000222};
223
224}
225
226/* *** */
227
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000228MCFragment::MCFragment() : Kind(FragmentType(~0)) {
229}
230
231MCFragment::MCFragment(FragmentType _Kind, MCSectionData *SD)
232 : Kind(_Kind),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000233 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000234{
235 if (SD)
236 SD->getFragmentList().push_back(this);
237}
238
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000239MCFragment::~MCFragment() {
240}
241
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000242/* *** */
243
244MCSectionData::MCSectionData() : Section(*(MCSection*)0) {}
245
246MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
247 : Section(_Section),
248 Alignment(1),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000249 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000250{
251 if (A)
252 A->getSectionList().push_back(this);
253}
254
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000255/* *** */
256
257MCAssembler::MCAssembler(raw_ostream &_OS) : OS(_OS) {}
258
259MCAssembler::~MCAssembler() {
260}
261
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000262void MCAssembler::LayoutSection(MCSectionData &SD) {
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000263 uint64_t Offset = 0;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000264
265 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
266 MCFragment &F = *it;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000267
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000268 F.setOffset(Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000269
270 // Evaluate fragment size.
271 switch (F.getKind()) {
272 case MCFragment::FT_Align: {
273 MCAlignFragment &AF = cast<MCAlignFragment>(F);
274
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000275 uint64_t AlignedOffset = RoundUpToAlignment(Offset, AF.getAlignment());
276 uint64_t PaddingBytes = AlignedOffset - Offset;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000277
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.
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000298 if (OrgOffset < Offset)
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000299 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000300 "' (section offset '" + Twine(Offset) + "'");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000301
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000302 F.setFileSize(OrgOffset - Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000303 break;
304 }
305 }
306
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000307 Offset += F.getFileSize();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000308 }
309
310 // FIXME: Pad section?
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000311 SD.setFileSize(Offset);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000312}
313
314/// WriteFileData - Write the \arg F data to the output file.
315static 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()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000322 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 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000347
348 case MCFragment::FT_Data:
349 OS << cast<MCDataFragment>(F).getContents().str();
350 break;
351
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000352 case MCFragment::FT_Fill: {
353 MCFillFragment &FF = cast<MCFillFragment>(F);
354
355 if (!FF.getValue().isAbsolute())
356 llvm_unreachable("FIXME: Not yet implemented!");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000357 int64_t Value = FF.getValue().getConstant();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000358
359 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
360 switch (FF.getValueSize()) {
361 default:
362 assert(0 && "Invalid size!");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000363 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;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000367 }
368 }
369 break;
370 }
371
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000372 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 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000380 }
381
382 assert(OS.tell() - Start == F.getFileSize());
383}
384
385/// WriteFileData - Write the \arg SD data to the output file.
386static 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
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000398void MCAssembler::Finish() {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000399 // Layout the sections and fragments.
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000400 for (iterator it = begin(), ie = end(); it != ie; ++it)
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000401 LayoutSection(*it);
402
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000403 MachObjectWriter MOW(OS);
404
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000405 // Write the prolog, followed by the data for all the sections & fragments.
406 MOW.WriteProlog(*this);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000407
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000408 // FIXME: This should move into the Mach-O writer, it should have control over
409 // what goes where.
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000410 for (iterator it = begin(), ie = end(); it != ie; ++it)
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000411 WriteFileData(OS, *it, MOW);
412
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000413 OS.flush();
414}