blob: 9bd704a0e2cce23f0531d8dcc69bc73da4c4a2d2 [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
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +000012#include "llvm/ADT/DenseMap.h"
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000013#include "llvm/ADT/SmallString.h"
14#include "llvm/ADT/StringMap.h"
Daniel Dunbard6f761e2009-08-21 23:07:38 +000015#include "llvm/ADT/Twine.h"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000016#include "llvm/MC/MCSectionMachO.h"
17#include "llvm/Support/DataTypes.h"
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000018#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000019#include "llvm/Support/raw_ostream.h"
20#include "llvm/Target/TargetMachOWriterInfo.h"
21
22using namespace llvm;
23
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000024class MachObjectWriter;
25
26static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
27 MachObjectWriter &MOW);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000028
29class MachObjectWriter {
30 // See <mach-o/loader.h>.
31 enum {
32 Header_Magic32 = 0xFEEDFACE,
33 Header_Magic64 = 0xFEEDFACF
34 };
35
36 static const unsigned Header32Size = 28;
37 static const unsigned Header64Size = 32;
38 static const unsigned SegmentLoadCommand32Size = 56;
39 static const unsigned Section32Size = 68;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000040 static const unsigned SymtabLoadCommandSize = 24;
41 static const unsigned DysymtabLoadCommandSize = 80;
42 static const unsigned Nlist32Size = 12;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000043
44 enum HeaderFileType {
45 HFT_Object = 0x1
46 };
47
48 enum LoadCommandType {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000049 LCT_Segment = 0x1,
50 LCT_Symtab = 0x2,
51 LCT_Dysymtab = 0xb
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000052 };
53
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +000054 // See <mach-o/nlist.h>.
55 enum SymbolTypeType {
56 STT_Undefined = 0x00,
57 STT_Absolute = 0x02,
58 STT_Section = 0x0e
59 };
60
61 enum SymbolTypeFlags {
62 // If any of these bits are set, then the entry is a stab entry number (see
63 // <mach-o/stab.h>. Otherwise the other masks apply.
64 STF_StabsEntryMask = 0xe0,
65
66 STF_TypeMask = 0x0e,
67 STF_External = 0x01,
68 STF_PrivateExtern = 0x10
69 };
70
71 /// MachSymbolData - Helper struct for containing some precomputed information
72 /// on symbols.
73 struct MachSymbolData {
74 MCSymbolData *SymbolData;
75 uint64_t StringIndex;
76 uint8_t SectionIndex;
77
78 // Support lexicographic sorting.
79 bool operator<(const MachSymbolData &RHS) const {
80 const std::string &Name = SymbolData->getSymbol().getName();
81 return Name < RHS.SymbolData->getSymbol().getName();
82 }
83 };
84
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000085 raw_ostream &OS;
86 bool IsLSB;
87
88public:
89 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
90 : OS(_OS), IsLSB(_IsLSB) {
91 }
92
93 /// @name Helper Methods
94 /// @{
95
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000096 void Write8(uint8_t Value) {
97 OS << char(Value);
98 }
99
100 void Write16(uint16_t Value) {
101 if (IsLSB) {
102 Write8(uint8_t(Value >> 0));
103 Write8(uint8_t(Value >> 8));
104 } else {
105 Write8(uint8_t(Value >> 8));
106 Write8(uint8_t(Value >> 0));
107 }
108 }
109
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000110 void Write32(uint32_t Value) {
111 if (IsLSB) {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000112 Write16(uint16_t(Value >> 0));
113 Write16(uint16_t(Value >> 16));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000114 } else {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000115 Write16(uint16_t(Value >> 16));
116 Write16(uint16_t(Value >> 0));
117 }
118 }
119
120 void Write64(uint64_t Value) {
121 if (IsLSB) {
122 Write32(uint32_t(Value >> 0));
123 Write32(uint32_t(Value >> 32));
124 } else {
125 Write32(uint32_t(Value >> 32));
126 Write32(uint32_t(Value >> 0));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000127 }
128 }
129
130 void WriteZeros(unsigned N) {
131 const char Zeros[16] = { 0 };
132
133 for (unsigned i = 0, e = N / 16; i != e; ++i)
134 OS << StringRef(Zeros, 16);
135
136 OS << StringRef(Zeros, N % 16);
137 }
138
139 void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
140 OS << Str;
141 if (ZeroFillSize)
142 WriteZeros(ZeroFillSize - Str.size());
143 }
144
145 /// @}
146
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000147 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000148 // struct mach_header (28 bytes)
149
150 uint64_t Start = OS.tell();
151 (void) Start;
152
153 Write32(Header_Magic32);
154
155 // FIXME: Support cputype.
156 Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
157
158 // FIXME: Support cpusubtype.
159 Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
160
161 Write32(HFT_Object);
162
163 // Object files have a single load command, the segment.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000164 Write32(NumLoadCommands);
165 Write32(LoadCommandsSize);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000166 Write32(0); // Flags
167
168 assert(OS.tell() - Start == Header32Size);
169 }
170
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000171 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
172 ///
173 /// \arg NumSections - The number of sections in this segment.
174 /// \arg SectionDataSize - The total size of the sections.
175 void WriteSegmentLoadCommand32(unsigned NumSections,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000176 uint64_t SectionDataStartOffset,
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000177 uint64_t SectionDataSize) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000178 // struct segment_command (56 bytes)
179
180 uint64_t Start = OS.tell();
181 (void) Start;
182
183 Write32(LCT_Segment);
184 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
185
186 WriteString("", 16);
187 Write32(0); // vmaddr
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000188 Write32(SectionDataSize); // vmsize
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000189 Write32(SectionDataStartOffset); // file offset
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000190 Write32(SectionDataSize); // file size
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000191 Write32(0x7); // maxprot
192 Write32(0x7); // initprot
193 Write32(NumSections);
194 Write32(0); // flags
195
196 assert(OS.tell() - Start == SegmentLoadCommand32Size);
197 }
198
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000199 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000200 // struct section (68 bytes)
201
202 uint64_t Start = OS.tell();
203 (void) Start;
204
205 // FIXME: cast<> support!
206 const MCSectionMachO &Section =
207 static_cast<const MCSectionMachO&>(SD.getSection());
208 WriteString(Section.getSectionName(), 16);
209 WriteString(Section.getSegmentName(), 16);
210 Write32(0); // address
211 Write32(SD.getFileSize()); // size
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000212 Write32(FileOffset);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000213
214 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
215 Write32(Log2_32(SD.getAlignment()));
216 Write32(0); // file offset of relocation entries
217 Write32(0); // number of relocation entrions
218 Write32(Section.getTypeAndAttributes());
219 Write32(0); // reserved1
220 Write32(Section.getStubSize()); // reserved2
221
222 assert(OS.tell() - Start == Section32Size);
223 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000224
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000225 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
226 uint32_t StringTableOffset,
227 uint32_t StringTableSize) {
228 // struct symtab_command (24 bytes)
229
230 uint64_t Start = OS.tell();
231 (void) Start;
232
233 Write32(LCT_Symtab);
234 Write32(SymtabLoadCommandSize);
235 Write32(SymbolOffset);
236 Write32(NumSymbols);
237 Write32(StringTableOffset);
238 Write32(StringTableSize);
239
240 assert(OS.tell() - Start == SymtabLoadCommandSize);
241 }
242
243 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
244 uint32_t NumLocalSymbols,
245 uint32_t FirstExternalSymbol,
246 uint32_t NumExternalSymbols,
247 uint32_t FirstUndefinedSymbol,
248 uint32_t NumUndefinedSymbols,
249 uint32_t IndirectSymbolOffset,
250 uint32_t NumIndirectSymbols) {
251 // struct dysymtab_command (80 bytes)
252
253 uint64_t Start = OS.tell();
254 (void) Start;
255
256 Write32(LCT_Dysymtab);
257 Write32(DysymtabLoadCommandSize);
258 Write32(FirstLocalSymbol);
259 Write32(NumLocalSymbols);
260 Write32(FirstExternalSymbol);
261 Write32(NumExternalSymbols);
262 Write32(FirstUndefinedSymbol);
263 Write32(NumUndefinedSymbols);
264 Write32(0); // tocoff
265 Write32(0); // ntoc
266 Write32(0); // modtaboff
267 Write32(0); // nmodtab
268 Write32(0); // extrefsymoff
269 Write32(0); // nextrefsyms
270 Write32(IndirectSymbolOffset);
271 Write32(NumIndirectSymbols);
272 Write32(0); // extreloff
273 Write32(0); // nextrel
274 Write32(0); // locreloff
275 Write32(0); // nlocrel
276
277 assert(OS.tell() - Start == DysymtabLoadCommandSize);
278 }
279
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000280 void WriteNlist32(MachSymbolData &MSD) {
281 MCSymbol &Symbol = MSD.SymbolData->getSymbol();
282 uint8_t Type = 0;
283
284 // Set the N_TYPE bits. See <mach-o/nlist.h>.
285 //
286 // FIXME: Are the prebound or indirect fields possible here?
287 if (Symbol.isUndefined())
288 Type = STT_Undefined;
289 else if (Symbol.isAbsolute())
290 Type = STT_Absolute;
291 else
292 Type = STT_Section;
293
294 // FIXME: Set STAB bits.
295
296 // FIXME: Set private external bit.
297
298 // Set external bit.
299 if (MSD.SymbolData->isExternal())
300 Type |= STF_External;
301
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000302 // struct nlist (12 bytes)
303
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000304 Write32(MSD.StringIndex);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000305 Write8(Type);
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000306 Write8(MSD.SectionIndex);
307 Write16(0); // FIXME: Desc
308 Write32(0); // FIXME: Value
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000309 }
310
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000311 /// ComputeSymbolTable - Compute the symbol table data
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000312 ///
313 /// \param StringTable [out] - The string table data.
314 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
315 /// string table.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000316
317 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
318 std::vector<MachSymbolData> &LocalSymbolData,
319 std::vector<MachSymbolData> &ExternalSymbolData,
320 std::vector<MachSymbolData> &UndefinedSymbolData) {
321 // Build section lookup table.
322 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
323 unsigned Index = 1;
324 for (MCAssembler::iterator it = Asm.begin(),
325 ie = Asm.end(); it != ie; ++it, ++Index)
326 SectionIndexMap[&it->getSection()] = Index;
327 assert(Index <= 256 && "Too many sections!");
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000328
329 // Index 0 is always the empty string.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000330 StringMap<uint64_t> StringIndexMap;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000331 StringTable += '\x00';
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000332
333 // Build the symbol arrays and the string table, but only for non-local
334 // symbols.
335 //
336 // The particular order that we collect the symbols and create the string
337 // table, then sort the symbols is chosen to match 'as'. Even though it
338 // doesn't matter for correctness, this is important for letting us diff .o
339 // files.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000340 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
341 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000342 MCSymbol &Symbol = it->getSymbol();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000343
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000344 if (!it->isExternal())
345 continue;
346
347 uint64_t &Entry = StringIndexMap[Symbol.getName()];
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000348 if (!Entry) {
349 Entry = StringTable.size();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000350 StringTable += Symbol.getName();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000351 StringTable += '\x00';
352 }
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000353
354 MachSymbolData MSD;
355 MSD.SymbolData = it;
356 MSD.StringIndex = Entry;
357
358 if (Symbol.isUndefined()) {
359 MSD.SectionIndex = 0;
360 UndefinedSymbolData.push_back(MSD);
361 } else if (Symbol.isAbsolute()) {
362 MSD.SectionIndex = 0;
363 ExternalSymbolData.push_back(MSD);
364 } else {
365 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
366 assert(MSD.SectionIndex && "Invalid section index!");
367 ExternalSymbolData.push_back(MSD);
368 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000369 }
370
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000371 // Now add the data for local symbols.
372 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
373 ie = Asm.symbol_end(); it != ie; ++it) {
374 MCSymbol &Symbol = it->getSymbol();
375
376 if (it->isExternal())
377 continue;
378
379 uint64_t &Entry = StringIndexMap[Symbol.getName()];
380 if (!Entry) {
381 Entry = StringTable.size();
382 StringTable += Symbol.getName();
383 StringTable += '\x00';
384 }
385
386 MachSymbolData MSD;
387 MSD.SymbolData = it;
388 MSD.StringIndex = Entry;
389
390 assert(!Symbol.isUndefined() && "Local symbol can not be undefined!");
391 if (Symbol.isAbsolute()) {
392 MSD.SectionIndex = 0;
393 LocalSymbolData.push_back(MSD);
394 } else {
395 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
396 assert(MSD.SectionIndex && "Invalid section index!");
397 LocalSymbolData.push_back(MSD);
398 }
399 }
400
401 // External and undefined symbols are required to be in lexicographic order.
402 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
403 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
404
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000405 // The string table is padded to a multiple of 4.
406 //
407 // FIXME: Check to see if this varies per arch.
408 while (StringTable.size() % 4)
409 StringTable += '\x00';
410 }
411
412 void WriteObject(MCAssembler &Asm) {
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000413 unsigned NumSections = Asm.size();
414
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000415 // Compute symbol table information.
416 SmallString<256> StringTable;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000417 std::vector<MachSymbolData> LocalSymbolData;
418 std::vector<MachSymbolData> ExternalSymbolData;
419 std::vector<MachSymbolData> UndefinedSymbolData;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000420 unsigned NumSymbols = Asm.symbol_size();
421
422 // No symbol table command is written if there are no symbols.
423 if (NumSymbols)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000424 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
425 UndefinedSymbolData);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000426
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000427 // Compute the file offsets for all the sections in advance, so that we can
428 // write things out in order.
429 SmallVector<uint64_t, 16> SectionFileOffsets;
430 SectionFileOffsets.resize(NumSections);
431
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000432 // The section data starts after the header, the segment load command (and
433 // section headers) and the symbol table.
434 unsigned NumLoadCommands = 1;
435 uint64_t LoadCommandsSize =
436 SegmentLoadCommand32Size + NumSections * Section32Size;
437
438 // Add the symbol table load command sizes, if used.
439 if (NumSymbols) {
440 NumLoadCommands += 2;
441 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
442 }
443
444 uint64_t FileOffset = Header32Size + LoadCommandsSize;
445 uint64_t SectionDataStartOffset = FileOffset;
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000446 uint64_t SectionDataSize = 0;
447 unsigned Index = 0;
448 for (MCAssembler::iterator it = Asm.begin(),
449 ie = Asm.end(); it != ie; ++it, ++Index) {
450 SectionFileOffsets[Index] = FileOffset;
451 FileOffset += it->getFileSize();
452 SectionDataSize += it->getFileSize();
453 }
454
455 // Write the prolog, starting with the header and load command...
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000456 WriteHeader32(NumLoadCommands, LoadCommandsSize);
457 WriteSegmentLoadCommand32(NumSections, SectionDataStartOffset,
458 SectionDataSize);
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000459
460 // ... and then the section headers.
461 Index = 0;
462 for (MCAssembler::iterator it = Asm.begin(),
463 ie = Asm.end(); it != ie; ++it, ++Index)
464 WriteSection32(*it, SectionFileOffsets[Index]);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000465
466 // Write the symbol table load command, if used.
467 if (NumSymbols) {
468 // The string table is written after all the section data.
469 uint64_t SymbolTableOffset = SectionDataStartOffset + SectionDataSize;
470 uint64_t StringTableOffset =
471 SymbolTableOffset + NumSymbols * Nlist32Size;
472 WriteSymtabLoadCommand(SymbolTableOffset, NumSymbols,
473 StringTableOffset, StringTable.size());
474
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000475 unsigned FirstLocalSymbol = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000476 unsigned NumLocalSymbols = LocalSymbolData.size();
477 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
478 unsigned NumExternalSymbols = ExternalSymbolData.size();
479 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
480 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
481 // FIXME: Get correct symbol indices and counts for indirect symbols.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000482 unsigned IndirectSymbolOffset = 0;
483 unsigned NumIndirectSymbols = 0;
484 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
485 FirstExternalSymbol, NumExternalSymbols,
486 FirstUndefinedSymbol, NumUndefinedSymbols,
487 IndirectSymbolOffset, NumIndirectSymbols);
488 }
489
490 // Write the actual section data.
491 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
492 WriteFileData(OS, *it, *this);
493
494 // Write the symbol table data, if used.
495 if (NumSymbols) {
496 // FIXME: Check that offsets match computed ones.
497
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000498 // FIXME: Some of these are ordered by name to help the linker.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000499
500 // Write the symbol table entries.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000501 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
502 WriteNlist32(LocalSymbolData[i]);
503 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
504 WriteNlist32(ExternalSymbolData[i]);
505 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
506 WriteNlist32(UndefinedSymbolData[i]);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000507
508 // Write the string table.
509 OS << StringTable.str();
510 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000511 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000512};
513
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000514/* *** */
515
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000516MCFragment::MCFragment() : Kind(FragmentType(~0)) {
517}
518
519MCFragment::MCFragment(FragmentType _Kind, MCSectionData *SD)
520 : Kind(_Kind),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000521 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000522{
523 if (SD)
524 SD->getFragmentList().push_back(this);
525}
526
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000527MCFragment::~MCFragment() {
528}
529
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000530/* *** */
531
532MCSectionData::MCSectionData() : Section(*(MCSection*)0) {}
533
534MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
535 : Section(_Section),
536 Alignment(1),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000537 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000538{
539 if (A)
540 A->getSectionList().push_back(this);
541}
542
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000543/* *** */
544
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000545MCSymbolData::MCSymbolData() : Symbol(*(MCSymbol*)0) {}
546
547MCSymbolData::MCSymbolData(MCSymbol &_Symbol, MCFragment *_Fragment,
548 uint64_t _Offset, MCAssembler *A)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000549 : Symbol(_Symbol), Fragment(_Fragment), Offset(_Offset),
550 IsExternal(false)
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000551{
552 if (A)
553 A->getSymbolList().push_back(this);
554}
555
556/* *** */
557
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000558MCAssembler::MCAssembler(raw_ostream &_OS) : OS(_OS) {}
559
560MCAssembler::~MCAssembler() {
561}
562
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000563void MCAssembler::LayoutSection(MCSectionData &SD) {
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000564 uint64_t Offset = 0;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000565
566 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
567 MCFragment &F = *it;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000568
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000569 F.setOffset(Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000570
571 // Evaluate fragment size.
572 switch (F.getKind()) {
573 case MCFragment::FT_Align: {
574 MCAlignFragment &AF = cast<MCAlignFragment>(F);
575
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000576 uint64_t AlignedOffset = RoundUpToAlignment(Offset, AF.getAlignment());
577 uint64_t PaddingBytes = AlignedOffset - Offset;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000578
579 if (PaddingBytes > AF.getMaxBytesToEmit())
580 AF.setFileSize(0);
581 else
582 AF.setFileSize(PaddingBytes);
583 break;
584 }
585
586 case MCFragment::FT_Data:
587 case MCFragment::FT_Fill:
588 F.setFileSize(F.getMaxFileSize());
589 break;
590
591 case MCFragment::FT_Org: {
592 MCOrgFragment &OF = cast<MCOrgFragment>(F);
593
594 if (!OF.getOffset().isAbsolute())
595 llvm_unreachable("FIXME: Not yet implemented!");
596 uint64_t OrgOffset = OF.getOffset().getConstant();
597
598 // FIXME: We need a way to communicate this error.
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000599 if (OrgOffset < Offset)
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000600 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000601 "' (section offset '" + Twine(Offset) + "'");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000602
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000603 F.setFileSize(OrgOffset - Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000604 break;
605 }
606 }
607
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000608 Offset += F.getFileSize();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000609 }
610
611 // FIXME: Pad section?
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000612 SD.setFileSize(Offset);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000613}
614
615/// WriteFileData - Write the \arg F data to the output file.
616static void WriteFileData(raw_ostream &OS, const MCFragment &F,
617 MachObjectWriter &MOW) {
618 uint64_t Start = OS.tell();
619 (void) Start;
620
621 // FIXME: Embed in fragments instead?
622 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000623 case MCFragment::FT_Align: {
624 MCAlignFragment &AF = cast<MCAlignFragment>(F);
625 uint64_t Count = AF.getFileSize() / AF.getValueSize();
626
627 // FIXME: This error shouldn't actually occur (the front end should emit
628 // multiple .align directives to enforce the semantics it wants), but is
629 // severe enough that we want to report it. How to handle this?
630 if (Count * AF.getValueSize() != AF.getFileSize())
631 llvm_report_error("undefined .align directive, value size '" +
632 Twine(AF.getValueSize()) +
633 "' is not a divisor of padding size '" +
634 Twine(AF.getFileSize()) + "'");
635
636 for (uint64_t i = 0; i != Count; ++i) {
637 switch (AF.getValueSize()) {
638 default:
639 assert(0 && "Invalid size!");
640 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
641 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
642 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
643 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
644 }
645 }
646 break;
647 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000648
649 case MCFragment::FT_Data:
650 OS << cast<MCDataFragment>(F).getContents().str();
651 break;
652
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000653 case MCFragment::FT_Fill: {
654 MCFillFragment &FF = cast<MCFillFragment>(F);
655
656 if (!FF.getValue().isAbsolute())
657 llvm_unreachable("FIXME: Not yet implemented!");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000658 int64_t Value = FF.getValue().getConstant();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000659
660 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
661 switch (FF.getValueSize()) {
662 default:
663 assert(0 && "Invalid size!");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000664 case 1: MOW.Write8 (uint8_t (Value)); break;
665 case 2: MOW.Write16(uint16_t(Value)); break;
666 case 4: MOW.Write32(uint32_t(Value)); break;
667 case 8: MOW.Write64(uint64_t(Value)); break;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000668 }
669 }
670 break;
671 }
672
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000673 case MCFragment::FT_Org: {
674 MCOrgFragment &OF = cast<MCOrgFragment>(F);
675
676 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
677 MOW.Write8(uint8_t(OF.getValue()));
678
679 break;
680 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000681 }
682
683 assert(OS.tell() - Start == F.getFileSize());
684}
685
686/// WriteFileData - Write the \arg SD data to the output file.
687static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
688 MachObjectWriter &MOW) {
689 uint64_t Start = OS.tell();
690 (void) Start;
691
692 for (MCSectionData::const_iterator it = SD.begin(),
693 ie = SD.end(); it != ie; ++it)
694 WriteFileData(OS, *it, MOW);
695
696 assert(OS.tell() - Start == SD.getFileSize());
697}
698
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000699void MCAssembler::Finish() {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000700 // Layout the sections and fragments.
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000701 for (iterator it = begin(), ie = end(); it != ie; ++it)
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000702 LayoutSection(*it);
703
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000704 // Write the object file.
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000705 MachObjectWriter MOW(OS);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000706 MOW.WriteObject(*this);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000707
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000708 OS.flush();
709}