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 FileOffset(~UINT64_C(0)),
206 FileSize(~UINT64_C(0))
209 SD->getFragmentList().push_back(this);
212 MCFragment::~MCFragment() {
217 MCSectionData::MCSectionData() : Section(*(MCSection*)0) {}
219 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
222 FileOffset(~UINT64_C(0)),
223 FileSize(~UINT64_C(0))
226 A->getSectionList().push_back(this);
231 MCAssembler::MCAssembler(raw_ostream &_OS) : OS(_OS) {}
233 MCAssembler::~MCAssembler() {
236 void MCAssembler::LayoutSection(MCSectionData &SD) {
237 uint64_t FileOffset = SD.getFileOffset();
238 uint64_t SectionOffset = 0;
240 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
243 F.setFileOffset(FileOffset);
245 // Evaluate fragment size.
246 switch (F.getKind()) {
247 case MCFragment::FT_Align: {
248 MCAlignFragment &AF = cast<MCAlignFragment>(F);
250 uint64_t AlignedOffset =
251 RoundUpToAlignment(SectionOffset, AF.getAlignment());
252 uint64_t PaddingBytes = AlignedOffset - SectionOffset;
254 if (PaddingBytes > AF.getMaxBytesToEmit())
257 AF.setFileSize(PaddingBytes);
261 case MCFragment::FT_Data:
262 case MCFragment::FT_Fill:
263 F.setFileSize(F.getMaxFileSize());
266 case MCFragment::FT_Org: {
267 MCOrgFragment &OF = cast<MCOrgFragment>(F);
269 if (!OF.getOffset().isAbsolute())
270 llvm_unreachable("FIXME: Not yet implemented!");
271 uint64_t OrgOffset = OF.getOffset().getConstant();
273 // FIXME: We need a way to communicate this error.
274 if (OrgOffset < SectionOffset)
275 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
276 "' (section offset '" + Twine(SectionOffset) + "'");
278 F.setFileSize(OrgOffset - SectionOffset);
283 FileOffset += F.getFileSize();
284 SectionOffset += F.getFileSize();
287 // FIXME: Pad section?
288 SD.setFileSize(FileOffset - SD.getFileOffset());
291 /// WriteFileData - Write the \arg F data to the output file.
292 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
293 MachObjectWriter &MOW) {
294 uint64_t Start = OS.tell();
297 assert(F.getFileOffset() == Start && "Invalid file offset!");
299 // FIXME: Embed in fragments instead?
300 switch (F.getKind()) {
301 case MCFragment::FT_Align: {
302 MCAlignFragment &AF = cast<MCAlignFragment>(F);
303 uint64_t Count = AF.getFileSize() / AF.getValueSize();
305 // FIXME: This error shouldn't actually occur (the front end should emit
306 // multiple .align directives to enforce the semantics it wants), but is
307 // severe enough that we want to report it. How to handle this?
308 if (Count * AF.getValueSize() != AF.getFileSize())
309 llvm_report_error("undefined .align directive, value size '" +
310 Twine(AF.getValueSize()) +
311 "' is not a divisor of padding size '" +
312 Twine(AF.getFileSize()) + "'");
314 for (uint64_t i = 0; i != Count; ++i) {
315 switch (AF.getValueSize()) {
317 assert(0 && "Invalid size!");
318 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
319 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
320 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
321 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
327 case MCFragment::FT_Data:
328 OS << cast<MCDataFragment>(F).getContents().str();
331 case MCFragment::FT_Fill: {
332 MCFillFragment &FF = cast<MCFillFragment>(F);
334 if (!FF.getValue().isAbsolute())
335 llvm_unreachable("FIXME: Not yet implemented!");
336 int64_t Value = FF.getValue().getConstant();
338 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
339 switch (FF.getValueSize()) {
341 assert(0 && "Invalid size!");
342 case 1: MOW.Write8 (uint8_t (Value)); break;
343 case 2: MOW.Write16(uint16_t(Value)); break;
344 case 4: MOW.Write32(uint32_t(Value)); break;
345 case 8: MOW.Write64(uint64_t(Value)); break;
351 case MCFragment::FT_Org: {
352 MCOrgFragment &OF = cast<MCOrgFragment>(F);
354 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
355 MOW.Write8(uint8_t(OF.getValue()));
361 assert(OS.tell() - Start == F.getFileSize());
364 /// WriteFileData - Write the \arg SD data to the output file.
365 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
366 MachObjectWriter &MOW) {
367 uint64_t Start = OS.tell();
370 for (MCSectionData::const_iterator it = SD.begin(),
371 ie = SD.end(); it != ie; ++it)
372 WriteFileData(OS, *it, MOW);
374 assert(OS.tell() - Start == SD.getFileSize());
377 void MCAssembler::Finish() {
378 unsigned NumSections = Sections.size();
380 // Layout the sections and fragments.
381 uint64_t Offset = MachObjectWriter::getPrologSize32(NumSections);
382 uint64_t SectionDataSize = 0;
383 for (iterator it = begin(), ie = end(); it != ie; ++it) {
384 it->setFileOffset(Offset);
388 Offset += it->getFileSize();
389 SectionDataSize += it->getFileSize();
392 MachObjectWriter MOW(OS);
394 // Write the prolog, starting with the header and load command...
395 MOW.WriteHeader32(NumSections);
396 MOW.WriteSegmentLoadCommand32(NumSections, SectionDataSize);
398 // ... and then the section headers.
399 for (iterator it = begin(), ie = end(); it != ie; ++it)
400 MOW.WriteSection32(*it);
402 // Finally, write the section data.
403 for (iterator it = begin(), ie = end(); it != ie; ++it)
404 WriteFileData(OS, *it, MOW);