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 void WriteHeader32(unsigned NumSections) {
106 // struct mach_header (28 bytes)
108 uint64_t Start = OS.tell();
111 Write32(Header_Magic32);
113 // FIXME: Support cputype.
114 Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
116 // FIXME: Support cpusubtype.
117 Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
121 // Object files have a single load command, the segment.
123 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
126 assert(OS.tell() - Start == Header32Size);
129 void WriteLoadCommandHeader(uint32_t Cmd, uint32_t CmdSize) {
130 assert((CmdSize & 0x3) == 0 && "Invalid size!");
136 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
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)
144 uint64_t Start = OS.tell();
147 Write32(LCT_Segment);
148 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
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);
161 assert(OS.tell() - Start == SegmentLoadCommand32Size);
164 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset) {
165 // struct section (68 bytes)
167 uint64_t Start = OS.tell();
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
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
187 assert(OS.tell() - Start == Section32Size);
190 void WriteProlog(MCAssembler &Asm) {
191 unsigned NumSections = Asm.size();
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);
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;
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();
211 // Write the prolog, starting with the header and load command...
212 WriteHeader32(NumSections);
213 WriteSegmentLoadCommand32(NumSections, SectionDataSize);
215 // ... and then the section headers.
217 for (MCAssembler::iterator it = Asm.begin(),
218 ie = Asm.end(); it != ie; ++it, ++Index)
219 WriteSection32(*it, SectionFileOffsets[Index]);
228 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
231 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *SD)
233 FileSize(~UINT64_C(0))
236 SD->getFragmentList().push_back(this);
239 MCFragment::~MCFragment() {
244 MCSectionData::MCSectionData() : Section(*(MCSection*)0) {}
246 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
249 FileSize(~UINT64_C(0))
252 A->getSectionList().push_back(this);
257 MCAssembler::MCAssembler(raw_ostream &_OS) : OS(_OS) {}
259 MCAssembler::~MCAssembler() {
262 void MCAssembler::LayoutSection(MCSectionData &SD) {
265 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
270 // Evaluate fragment size.
271 switch (F.getKind()) {
272 case MCFragment::FT_Align: {
273 MCAlignFragment &AF = cast<MCAlignFragment>(F);
275 uint64_t AlignedOffset = RoundUpToAlignment(Offset, AF.getAlignment());
276 uint64_t PaddingBytes = AlignedOffset - Offset;
278 if (PaddingBytes > AF.getMaxBytesToEmit())
281 AF.setFileSize(PaddingBytes);
285 case MCFragment::FT_Data:
286 case MCFragment::FT_Fill:
287 F.setFileSize(F.getMaxFileSize());
290 case MCFragment::FT_Org: {
291 MCOrgFragment &OF = cast<MCOrgFragment>(F);
293 if (!OF.getOffset().isAbsolute())
294 llvm_unreachable("FIXME: Not yet implemented!");
295 uint64_t OrgOffset = OF.getOffset().getConstant();
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) + "'");
302 F.setFileSize(OrgOffset - Offset);
307 Offset += F.getFileSize();
310 // FIXME: Pad section?
311 SD.setFileSize(Offset);
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();
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();
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()) + "'");
335 for (uint64_t i = 0; i != Count; ++i) {
336 switch (AF.getValueSize()) {
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;
348 case MCFragment::FT_Data:
349 OS << cast<MCDataFragment>(F).getContents().str();
352 case MCFragment::FT_Fill: {
353 MCFillFragment &FF = cast<MCFillFragment>(F);
355 if (!FF.getValue().isAbsolute())
356 llvm_unreachable("FIXME: Not yet implemented!");
357 int64_t Value = FF.getValue().getConstant();
359 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
360 switch (FF.getValueSize()) {
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;
372 case MCFragment::FT_Org: {
373 MCOrgFragment &OF = cast<MCOrgFragment>(F);
375 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
376 MOW.Write8(uint8_t(OF.getValue()));
382 assert(OS.tell() - Start == F.getFileSize());
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();
391 for (MCSectionData::const_iterator it = SD.begin(),
392 ie = SD.end(); it != ie; ++it)
393 WriteFileData(OS, *it, MOW);
395 assert(OS.tell() - Start == SD.getFileSize());
398 void MCAssembler::Finish() {
399 // Layout the sections and fragments.
400 for (iterator it = begin(), ie = end(); it != ie; ++it)
403 MachObjectWriter MOW(OS);
405 // Write the prolog, followed by the data for all the sections & fragments.
406 MOW.WriteProlog(*this);
408 // FIXME: This should move into the Mach-O writer, it should have control over
410 for (iterator it = begin(), ie = end(); it != ie; ++it)
411 WriteFileData(OS, *it, MOW);