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"
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"
23 class MachObjectWriter {
24 // See <mach-o/loader.h>.
26 Header_Magic32 = 0xFEEDFACE,
27 Header_Magic64 = 0xFEEDFACF
30 static const unsigned Header32Size = 28;
31 static const unsigned Header64Size = 32;
32 static const unsigned SegmentLoadCommand32Size = 56;
33 static const unsigned Section32Size = 68;
39 enum LoadCommandType {
47 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
48 : OS(_OS), IsLSB(_IsLSB) {
51 /// @name Helper Methods
54 void Write8(uint8_t Value) {
58 void Write16(uint16_t Value) {
60 Write8(uint8_t(Value >> 0));
61 Write8(uint8_t(Value >> 8));
63 Write8(uint8_t(Value >> 8));
64 Write8(uint8_t(Value >> 0));
68 void Write32(uint32_t Value) {
70 Write16(uint16_t(Value >> 0));
71 Write16(uint16_t(Value >> 16));
73 Write16(uint16_t(Value >> 16));
74 Write16(uint16_t(Value >> 0));
78 void Write64(uint64_t Value) {
80 Write32(uint32_t(Value >> 0));
81 Write32(uint32_t(Value >> 32));
83 Write32(uint32_t(Value >> 32));
84 Write32(uint32_t(Value >> 0));
88 void WriteZeros(unsigned N) {
89 const char Zeros[16] = { 0 };
91 for (unsigned i = 0, e = N / 16; i != e; ++i)
92 OS << StringRef(Zeros, 16);
94 OS << StringRef(Zeros, N % 16);
97 void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
100 WriteZeros(ZeroFillSize - Str.size());
105 static unsigned getPrologSize32(unsigned NumSections) {
106 return Header32Size + SegmentLoadCommand32Size +
107 NumSections * Section32Size;
110 void WriteHeader32(unsigned NumSections) {
111 // struct mach_header (28 bytes)
113 uint64_t Start = OS.tell();
116 Write32(Header_Magic32);
118 // FIXME: Support cputype.
119 Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
121 // FIXME: Support cpusubtype.
122 Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
126 // Object files have a single load command, the segment.
128 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
131 assert(OS.tell() - Start == Header32Size);
134 void WriteLoadCommandHeader(uint32_t Cmd, uint32_t CmdSize) {
135 assert((CmdSize & 0x3) == 0 && "Invalid size!");
141 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
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)
149 uint64_t Start = OS.tell();
152 Write32(LCT_Segment);
153 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
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);
166 assert(OS.tell() - Start == SegmentLoadCommand32Size);
169 void WriteSection32(const MCSectionData &SD) {
170 // struct section (68 bytes)
172 uint64_t Start = OS.tell();
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());
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
192 assert(OS.tell() - Start == Section32Size);
200 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
203 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *SD)
205 FileSize(~UINT64_C(0))
208 SD->getFragmentList().push_back(this);
211 MCFragment::~MCFragment() {
216 MCSectionData::MCSectionData() : Section(*(MCSection*)0) {}
218 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
221 FileOffset(~UINT64_C(0)),
222 FileSize(~UINT64_C(0))
225 A->getSectionList().push_back(this);
230 MCAssembler::MCAssembler(raw_ostream &_OS) : OS(_OS) {}
232 MCAssembler::~MCAssembler() {
235 void MCAssembler::LayoutSection(MCSectionData &SD) {
238 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
243 // Evaluate fragment size.
244 switch (F.getKind()) {
245 case MCFragment::FT_Align: {
246 MCAlignFragment &AF = cast<MCAlignFragment>(F);
248 uint64_t AlignedOffset = RoundUpToAlignment(Offset, AF.getAlignment());
249 uint64_t PaddingBytes = AlignedOffset - Offset;
251 if (PaddingBytes > AF.getMaxBytesToEmit())
254 AF.setFileSize(PaddingBytes);
258 case MCFragment::FT_Data:
259 case MCFragment::FT_Fill:
260 F.setFileSize(F.getMaxFileSize());
263 case MCFragment::FT_Org: {
264 MCOrgFragment &OF = cast<MCOrgFragment>(F);
266 if (!OF.getOffset().isAbsolute())
267 llvm_unreachable("FIXME: Not yet implemented!");
268 uint64_t OrgOffset = OF.getOffset().getConstant();
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) + "'");
275 F.setFileSize(OrgOffset - Offset);
280 Offset += F.getFileSize();
283 // FIXME: Pad section?
284 SD.setFileSize(Offset);
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();
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();
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()) + "'");
308 for (uint64_t i = 0; i != Count; ++i) {
309 switch (AF.getValueSize()) {
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;
321 case MCFragment::FT_Data:
322 OS << cast<MCDataFragment>(F).getContents().str();
325 case MCFragment::FT_Fill: {
326 MCFillFragment &FF = cast<MCFillFragment>(F);
328 if (!FF.getValue().isAbsolute())
329 llvm_unreachable("FIXME: Not yet implemented!");
330 int64_t Value = FF.getValue().getConstant();
332 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
333 switch (FF.getValueSize()) {
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;
345 case MCFragment::FT_Org: {
346 MCOrgFragment &OF = cast<MCOrgFragment>(F);
348 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
349 MOW.Write8(uint8_t(OF.getValue()));
355 assert(OS.tell() - Start == F.getFileSize());
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();
364 for (MCSectionData::const_iterator it = SD.begin(),
365 ie = SD.end(); it != ie; ++it)
366 WriteFileData(OS, *it, MOW);
368 assert(OS.tell() - Start == SD.getFileSize());
371 void MCAssembler::Finish() {
372 unsigned NumSections = Sections.size();
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);
382 Offset += it->getFileSize();
383 SectionDataSize += it->getFileSize();
386 MachObjectWriter MOW(OS);
388 // Write the prolog, starting with the header and load command...
389 MOW.WriteHeader32(NumSections);
390 MOW.WriteSegmentLoadCommand32(NumSections, SectionDataSize);
392 // ... and then the section headers.
393 for (iterator it = begin(), ie = end(); it != ie; ++it)
394 MOW.WriteSection32(*it);
396 // Finally, write the section data.
397 for (iterator it = begin(), ie = end(); it != ie; ++it)
398 WriteFileData(OS, *it, MOW);