blob: 7a67fac7efd9f4a96c9d1110a7949142d7b9ec4f [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"
Chris Lattnerbea2c952009-08-22 19:19:12 +000011#include "llvm/MC/MCSectionMachO.h"
12#include "llvm/Target/TargetMachOWriterInfo.h"
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +000013#include "llvm/ADT/DenseMap.h"
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000014#include "llvm/ADT/SmallString.h"
15#include "llvm/ADT/StringMap.h"
Daniel Dunbard6f761e2009-08-21 23:07:38 +000016#include "llvm/ADT/Twine.h"
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000017#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000018#include "llvm/Support/raw_ostream.h"
Chris Lattner23132b12009-08-24 03:52:50 +000019#include <vector>
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000020using namespace llvm;
21
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000022class MachObjectWriter;
23
24static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
25 MachObjectWriter &MOW);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000026
27class MachObjectWriter {
28 // See <mach-o/loader.h>.
29 enum {
30 Header_Magic32 = 0xFEEDFACE,
31 Header_Magic64 = 0xFEEDFACF
32 };
33
34 static const unsigned Header32Size = 28;
35 static const unsigned Header64Size = 32;
36 static const unsigned SegmentLoadCommand32Size = 56;
37 static const unsigned Section32Size = 68;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000038 static const unsigned SymtabLoadCommandSize = 24;
39 static const unsigned DysymtabLoadCommandSize = 80;
40 static const unsigned Nlist32Size = 12;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000041
42 enum HeaderFileType {
43 HFT_Object = 0x1
44 };
45
46 enum LoadCommandType {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000047 LCT_Segment = 0x1,
48 LCT_Symtab = 0x2,
49 LCT_Dysymtab = 0xb
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000050 };
51
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +000052 // See <mach-o/nlist.h>.
53 enum SymbolTypeType {
54 STT_Undefined = 0x00,
55 STT_Absolute = 0x02,
56 STT_Section = 0x0e
57 };
58
59 enum SymbolTypeFlags {
60 // If any of these bits are set, then the entry is a stab entry number (see
61 // <mach-o/stab.h>. Otherwise the other masks apply.
62 STF_StabsEntryMask = 0xe0,
63
64 STF_TypeMask = 0x0e,
65 STF_External = 0x01,
66 STF_PrivateExtern = 0x10
67 };
68
69 /// MachSymbolData - Helper struct for containing some precomputed information
70 /// on symbols.
71 struct MachSymbolData {
72 MCSymbolData *SymbolData;
73 uint64_t StringIndex;
74 uint8_t SectionIndex;
75
76 // Support lexicographic sorting.
77 bool operator<(const MachSymbolData &RHS) const {
78 const std::string &Name = SymbolData->getSymbol().getName();
79 return Name < RHS.SymbolData->getSymbol().getName();
80 }
81 };
82
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000083 raw_ostream &OS;
84 bool IsLSB;
85
86public:
87 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
88 : OS(_OS), IsLSB(_IsLSB) {
89 }
90
91 /// @name Helper Methods
92 /// @{
93
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000094 void Write8(uint8_t Value) {
95 OS << char(Value);
96 }
97
98 void Write16(uint16_t Value) {
99 if (IsLSB) {
100 Write8(uint8_t(Value >> 0));
101 Write8(uint8_t(Value >> 8));
102 } else {
103 Write8(uint8_t(Value >> 8));
104 Write8(uint8_t(Value >> 0));
105 }
106 }
107
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000108 void Write32(uint32_t Value) {
109 if (IsLSB) {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000110 Write16(uint16_t(Value >> 0));
111 Write16(uint16_t(Value >> 16));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000112 } else {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000113 Write16(uint16_t(Value >> 16));
114 Write16(uint16_t(Value >> 0));
115 }
116 }
117
118 void Write64(uint64_t Value) {
119 if (IsLSB) {
120 Write32(uint32_t(Value >> 0));
121 Write32(uint32_t(Value >> 32));
122 } else {
123 Write32(uint32_t(Value >> 32));
124 Write32(uint32_t(Value >> 0));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000125 }
126 }
127
128 void WriteZeros(unsigned N) {
129 const char Zeros[16] = { 0 };
130
131 for (unsigned i = 0, e = N / 16; i != e; ++i)
132 OS << StringRef(Zeros, 16);
133
134 OS << StringRef(Zeros, N % 16);
135 }
136
137 void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
138 OS << Str;
139 if (ZeroFillSize)
140 WriteZeros(ZeroFillSize - Str.size());
141 }
142
143 /// @}
144
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000145 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000146 // struct mach_header (28 bytes)
147
148 uint64_t Start = OS.tell();
149 (void) Start;
150
151 Write32(Header_Magic32);
152
153 // FIXME: Support cputype.
154 Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
155
156 // FIXME: Support cpusubtype.
157 Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
158
159 Write32(HFT_Object);
160
161 // Object files have a single load command, the segment.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000162 Write32(NumLoadCommands);
163 Write32(LoadCommandsSize);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000164 Write32(0); // Flags
165
166 assert(OS.tell() - Start == Header32Size);
167 }
168
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000169 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
170 ///
171 /// \arg NumSections - The number of sections in this segment.
172 /// \arg SectionDataSize - The total size of the sections.
173 void WriteSegmentLoadCommand32(unsigned NumSections,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000174 uint64_t SectionDataStartOffset,
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000175 uint64_t SectionDataSize) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000176 // struct segment_command (56 bytes)
177
178 uint64_t Start = OS.tell();
179 (void) Start;
180
181 Write32(LCT_Segment);
182 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
183
184 WriteString("", 16);
185 Write32(0); // vmaddr
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000186 Write32(SectionDataSize); // vmsize
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000187 Write32(SectionDataStartOffset); // file offset
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000188 Write32(SectionDataSize); // file size
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000189 Write32(0x7); // maxprot
190 Write32(0x7); // initprot
191 Write32(NumSections);
192 Write32(0); // flags
193
194 assert(OS.tell() - Start == SegmentLoadCommand32Size);
195 }
196
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000197 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000198 // struct section (68 bytes)
199
200 uint64_t Start = OS.tell();
201 (void) Start;
202
203 // FIXME: cast<> support!
204 const MCSectionMachO &Section =
205 static_cast<const MCSectionMachO&>(SD.getSection());
206 WriteString(Section.getSectionName(), 16);
207 WriteString(Section.getSegmentName(), 16);
208 Write32(0); // address
209 Write32(SD.getFileSize()); // size
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000210 Write32(FileOffset);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000211
212 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
213 Write32(Log2_32(SD.getAlignment()));
214 Write32(0); // file offset of relocation entries
215 Write32(0); // number of relocation entrions
216 Write32(Section.getTypeAndAttributes());
217 Write32(0); // reserved1
218 Write32(Section.getStubSize()); // reserved2
219
220 assert(OS.tell() - Start == Section32Size);
221 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000222
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000223 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
224 uint32_t StringTableOffset,
225 uint32_t StringTableSize) {
226 // struct symtab_command (24 bytes)
227
228 uint64_t Start = OS.tell();
229 (void) Start;
230
231 Write32(LCT_Symtab);
232 Write32(SymtabLoadCommandSize);
233 Write32(SymbolOffset);
234 Write32(NumSymbols);
235 Write32(StringTableOffset);
236 Write32(StringTableSize);
237
238 assert(OS.tell() - Start == SymtabLoadCommandSize);
239 }
240
241 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
242 uint32_t NumLocalSymbols,
243 uint32_t FirstExternalSymbol,
244 uint32_t NumExternalSymbols,
245 uint32_t FirstUndefinedSymbol,
246 uint32_t NumUndefinedSymbols,
247 uint32_t IndirectSymbolOffset,
248 uint32_t NumIndirectSymbols) {
249 // struct dysymtab_command (80 bytes)
250
251 uint64_t Start = OS.tell();
252 (void) Start;
253
254 Write32(LCT_Dysymtab);
255 Write32(DysymtabLoadCommandSize);
256 Write32(FirstLocalSymbol);
257 Write32(NumLocalSymbols);
258 Write32(FirstExternalSymbol);
259 Write32(NumExternalSymbols);
260 Write32(FirstUndefinedSymbol);
261 Write32(NumUndefinedSymbols);
262 Write32(0); // tocoff
263 Write32(0); // ntoc
264 Write32(0); // modtaboff
265 Write32(0); // nmodtab
266 Write32(0); // extrefsymoff
267 Write32(0); // nextrefsyms
268 Write32(IndirectSymbolOffset);
269 Write32(NumIndirectSymbols);
270 Write32(0); // extreloff
271 Write32(0); // nextrel
272 Write32(0); // locreloff
273 Write32(0); // nlocrel
274
275 assert(OS.tell() - Start == DysymtabLoadCommandSize);
276 }
277
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000278 void WriteNlist32(MachSymbolData &MSD) {
279 MCSymbol &Symbol = MSD.SymbolData->getSymbol();
280 uint8_t Type = 0;
281
282 // Set the N_TYPE bits. See <mach-o/nlist.h>.
283 //
284 // FIXME: Are the prebound or indirect fields possible here?
285 if (Symbol.isUndefined())
286 Type = STT_Undefined;
287 else if (Symbol.isAbsolute())
288 Type = STT_Absolute;
289 else
290 Type = STT_Section;
291
292 // FIXME: Set STAB bits.
293
294 // FIXME: Set private external bit.
295
296 // Set external bit.
297 if (MSD.SymbolData->isExternal())
298 Type |= STF_External;
299
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000300 // struct nlist (12 bytes)
301
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000302 Write32(MSD.StringIndex);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000303 Write8(Type);
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000304 Write8(MSD.SectionIndex);
305 Write16(0); // FIXME: Desc
306 Write32(0); // FIXME: Value
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000307 }
308
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000309 /// ComputeSymbolTable - Compute the symbol table data
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000310 ///
311 /// \param StringTable [out] - The string table data.
312 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
313 /// string table.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000314
315 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
316 std::vector<MachSymbolData> &LocalSymbolData,
317 std::vector<MachSymbolData> &ExternalSymbolData,
318 std::vector<MachSymbolData> &UndefinedSymbolData) {
319 // Build section lookup table.
320 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
321 unsigned Index = 1;
322 for (MCAssembler::iterator it = Asm.begin(),
323 ie = Asm.end(); it != ie; ++it, ++Index)
324 SectionIndexMap[&it->getSection()] = Index;
325 assert(Index <= 256 && "Too many sections!");
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000326
327 // Index 0 is always the empty string.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000328 StringMap<uint64_t> StringIndexMap;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000329 StringTable += '\x00';
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000330
331 // Build the symbol arrays and the string table, but only for non-local
332 // symbols.
333 //
334 // The particular order that we collect the symbols and create the string
335 // table, then sort the symbols is chosen to match 'as'. Even though it
336 // doesn't matter for correctness, this is important for letting us diff .o
337 // files.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000338 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
339 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000340 MCSymbol &Symbol = it->getSymbol();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000341
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000342 if (!it->isExternal())
343 continue;
344
345 uint64_t &Entry = StringIndexMap[Symbol.getName()];
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000346 if (!Entry) {
347 Entry = StringTable.size();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000348 StringTable += Symbol.getName();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000349 StringTable += '\x00';
350 }
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000351
352 MachSymbolData MSD;
353 MSD.SymbolData = it;
354 MSD.StringIndex = Entry;
355
356 if (Symbol.isUndefined()) {
357 MSD.SectionIndex = 0;
358 UndefinedSymbolData.push_back(MSD);
359 } else if (Symbol.isAbsolute()) {
360 MSD.SectionIndex = 0;
361 ExternalSymbolData.push_back(MSD);
362 } else {
363 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
364 assert(MSD.SectionIndex && "Invalid section index!");
365 ExternalSymbolData.push_back(MSD);
366 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000367 }
368
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000369 // Now add the data for local symbols.
370 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
371 ie = Asm.symbol_end(); it != ie; ++it) {
372 MCSymbol &Symbol = it->getSymbol();
373
374 if (it->isExternal())
375 continue;
376
377 uint64_t &Entry = StringIndexMap[Symbol.getName()];
378 if (!Entry) {
379 Entry = StringTable.size();
380 StringTable += Symbol.getName();
381 StringTable += '\x00';
382 }
383
384 MachSymbolData MSD;
385 MSD.SymbolData = it;
386 MSD.StringIndex = Entry;
387
388 assert(!Symbol.isUndefined() && "Local symbol can not be undefined!");
389 if (Symbol.isAbsolute()) {
390 MSD.SectionIndex = 0;
391 LocalSymbolData.push_back(MSD);
392 } else {
393 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
394 assert(MSD.SectionIndex && "Invalid section index!");
395 LocalSymbolData.push_back(MSD);
396 }
397 }
398
399 // External and undefined symbols are required to be in lexicographic order.
400 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
401 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
402
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000403 // The string table is padded to a multiple of 4.
404 //
405 // FIXME: Check to see if this varies per arch.
406 while (StringTable.size() % 4)
407 StringTable += '\x00';
408 }
409
410 void WriteObject(MCAssembler &Asm) {
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000411 unsigned NumSections = Asm.size();
412
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000413 // Compute symbol table information.
414 SmallString<256> StringTable;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000415 std::vector<MachSymbolData> LocalSymbolData;
416 std::vector<MachSymbolData> ExternalSymbolData;
417 std::vector<MachSymbolData> UndefinedSymbolData;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000418 unsigned NumSymbols = Asm.symbol_size();
419
420 // No symbol table command is written if there are no symbols.
421 if (NumSymbols)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000422 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
423 UndefinedSymbolData);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000424
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000425 // Compute the file offsets for all the sections in advance, so that we can
426 // write things out in order.
427 SmallVector<uint64_t, 16> SectionFileOffsets;
428 SectionFileOffsets.resize(NumSections);
429
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000430 // The section data starts after the header, the segment load command (and
431 // section headers) and the symbol table.
432 unsigned NumLoadCommands = 1;
433 uint64_t LoadCommandsSize =
434 SegmentLoadCommand32Size + NumSections * Section32Size;
435
436 // Add the symbol table load command sizes, if used.
437 if (NumSymbols) {
438 NumLoadCommands += 2;
439 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
440 }
441
442 uint64_t FileOffset = Header32Size + LoadCommandsSize;
443 uint64_t SectionDataStartOffset = FileOffset;
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000444 uint64_t SectionDataSize = 0;
445 unsigned Index = 0;
446 for (MCAssembler::iterator it = Asm.begin(),
447 ie = Asm.end(); it != ie; ++it, ++Index) {
448 SectionFileOffsets[Index] = FileOffset;
449 FileOffset += it->getFileSize();
450 SectionDataSize += it->getFileSize();
451 }
452
453 // Write the prolog, starting with the header and load command...
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000454 WriteHeader32(NumLoadCommands, LoadCommandsSize);
455 WriteSegmentLoadCommand32(NumSections, SectionDataStartOffset,
456 SectionDataSize);
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000457
458 // ... and then the section headers.
459 Index = 0;
460 for (MCAssembler::iterator it = Asm.begin(),
461 ie = Asm.end(); it != ie; ++it, ++Index)
462 WriteSection32(*it, SectionFileOffsets[Index]);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000463
464 // Write the symbol table load command, if used.
465 if (NumSymbols) {
466 // The string table is written after all the section data.
467 uint64_t SymbolTableOffset = SectionDataStartOffset + SectionDataSize;
468 uint64_t StringTableOffset =
469 SymbolTableOffset + NumSymbols * Nlist32Size;
470 WriteSymtabLoadCommand(SymbolTableOffset, NumSymbols,
471 StringTableOffset, StringTable.size());
472
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000473 unsigned FirstLocalSymbol = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000474 unsigned NumLocalSymbols = LocalSymbolData.size();
475 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
476 unsigned NumExternalSymbols = ExternalSymbolData.size();
477 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
478 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
479 // FIXME: Get correct symbol indices and counts for indirect symbols.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000480 unsigned IndirectSymbolOffset = 0;
481 unsigned NumIndirectSymbols = 0;
482 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
483 FirstExternalSymbol, NumExternalSymbols,
484 FirstUndefinedSymbol, NumUndefinedSymbols,
485 IndirectSymbolOffset, NumIndirectSymbols);
486 }
487
488 // Write the actual section data.
489 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
490 WriteFileData(OS, *it, *this);
491
492 // Write the symbol table data, if used.
493 if (NumSymbols) {
494 // FIXME: Check that offsets match computed ones.
495
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000496 // FIXME: Some of these are ordered by name to help the linker.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000497
498 // Write the symbol table entries.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000499 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
500 WriteNlist32(LocalSymbolData[i]);
501 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
502 WriteNlist32(ExternalSymbolData[i]);
503 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
504 WriteNlist32(UndefinedSymbolData[i]);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000505
506 // Write the string table.
507 OS << StringTable.str();
508 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000509 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000510};
511
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000512/* *** */
513
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000514MCFragment::MCFragment() : Kind(FragmentType(~0)) {
515}
516
517MCFragment::MCFragment(FragmentType _Kind, MCSectionData *SD)
518 : Kind(_Kind),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000519 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000520{
521 if (SD)
522 SD->getFragmentList().push_back(this);
523}
524
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000525MCFragment::~MCFragment() {
526}
527
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000528/* *** */
529
530MCSectionData::MCSectionData() : Section(*(MCSection*)0) {}
531
532MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
533 : Section(_Section),
534 Alignment(1),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000535 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000536{
537 if (A)
538 A->getSectionList().push_back(this);
539}
540
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000541/* *** */
542
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000543MCSymbolData::MCSymbolData() : Symbol(*(MCSymbol*)0) {}
544
545MCSymbolData::MCSymbolData(MCSymbol &_Symbol, MCFragment *_Fragment,
546 uint64_t _Offset, MCAssembler *A)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000547 : Symbol(_Symbol), Fragment(_Fragment), Offset(_Offset),
548 IsExternal(false)
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000549{
550 if (A)
551 A->getSymbolList().push_back(this);
552}
553
554/* *** */
555
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000556MCAssembler::MCAssembler(raw_ostream &_OS) : OS(_OS) {}
557
558MCAssembler::~MCAssembler() {
559}
560
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000561void MCAssembler::LayoutSection(MCSectionData &SD) {
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000562 uint64_t Offset = 0;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000563
564 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
565 MCFragment &F = *it;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000566
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000567 F.setOffset(Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000568
569 // Evaluate fragment size.
570 switch (F.getKind()) {
571 case MCFragment::FT_Align: {
572 MCAlignFragment &AF = cast<MCAlignFragment>(F);
573
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000574 uint64_t AlignedOffset = RoundUpToAlignment(Offset, AF.getAlignment());
575 uint64_t PaddingBytes = AlignedOffset - Offset;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000576
577 if (PaddingBytes > AF.getMaxBytesToEmit())
578 AF.setFileSize(0);
579 else
580 AF.setFileSize(PaddingBytes);
581 break;
582 }
583
584 case MCFragment::FT_Data:
585 case MCFragment::FT_Fill:
586 F.setFileSize(F.getMaxFileSize());
587 break;
588
589 case MCFragment::FT_Org: {
590 MCOrgFragment &OF = cast<MCOrgFragment>(F);
591
592 if (!OF.getOffset().isAbsolute())
593 llvm_unreachable("FIXME: Not yet implemented!");
594 uint64_t OrgOffset = OF.getOffset().getConstant();
595
596 // FIXME: We need a way to communicate this error.
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000597 if (OrgOffset < Offset)
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000598 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000599 "' (section offset '" + Twine(Offset) + "'");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000600
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000601 F.setFileSize(OrgOffset - Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000602 break;
603 }
604 }
605
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000606 Offset += F.getFileSize();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000607 }
608
609 // FIXME: Pad section?
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000610 SD.setFileSize(Offset);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000611}
612
613/// WriteFileData - Write the \arg F data to the output file.
614static void WriteFileData(raw_ostream &OS, const MCFragment &F,
615 MachObjectWriter &MOW) {
616 uint64_t Start = OS.tell();
617 (void) Start;
618
619 // FIXME: Embed in fragments instead?
620 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000621 case MCFragment::FT_Align: {
622 MCAlignFragment &AF = cast<MCAlignFragment>(F);
623 uint64_t Count = AF.getFileSize() / AF.getValueSize();
624
625 // FIXME: This error shouldn't actually occur (the front end should emit
626 // multiple .align directives to enforce the semantics it wants), but is
627 // severe enough that we want to report it. How to handle this?
628 if (Count * AF.getValueSize() != AF.getFileSize())
629 llvm_report_error("undefined .align directive, value size '" +
630 Twine(AF.getValueSize()) +
631 "' is not a divisor of padding size '" +
632 Twine(AF.getFileSize()) + "'");
633
634 for (uint64_t i = 0; i != Count; ++i) {
635 switch (AF.getValueSize()) {
636 default:
637 assert(0 && "Invalid size!");
638 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
639 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
640 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
641 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
642 }
643 }
644 break;
645 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000646
647 case MCFragment::FT_Data:
648 OS << cast<MCDataFragment>(F).getContents().str();
649 break;
650
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000651 case MCFragment::FT_Fill: {
652 MCFillFragment &FF = cast<MCFillFragment>(F);
653
654 if (!FF.getValue().isAbsolute())
655 llvm_unreachable("FIXME: Not yet implemented!");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000656 int64_t Value = FF.getValue().getConstant();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000657
658 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
659 switch (FF.getValueSize()) {
660 default:
661 assert(0 && "Invalid size!");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000662 case 1: MOW.Write8 (uint8_t (Value)); break;
663 case 2: MOW.Write16(uint16_t(Value)); break;
664 case 4: MOW.Write32(uint32_t(Value)); break;
665 case 8: MOW.Write64(uint64_t(Value)); break;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000666 }
667 }
668 break;
669 }
670
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000671 case MCFragment::FT_Org: {
672 MCOrgFragment &OF = cast<MCOrgFragment>(F);
673
674 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
675 MOW.Write8(uint8_t(OF.getValue()));
676
677 break;
678 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000679 }
680
681 assert(OS.tell() - Start == F.getFileSize());
682}
683
684/// WriteFileData - Write the \arg SD data to the output file.
685static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
686 MachObjectWriter &MOW) {
687 uint64_t Start = OS.tell();
688 (void) Start;
689
690 for (MCSectionData::const_iterator it = SD.begin(),
691 ie = SD.end(); it != ie; ++it)
692 WriteFileData(OS, *it, MOW);
693
694 assert(OS.tell() - Start == SD.getFileSize());
695}
696
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000697void MCAssembler::Finish() {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000698 // Layout the sections and fragments.
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000699 for (iterator it = begin(), ie = end(); it != ie; ++it)
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000700 LayoutSection(*it);
701
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000702 // Write the object file.
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000703 MachObjectWriter MOW(OS);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000704 MOW.WriteObject(*this);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000705
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000706 OS.flush();
707}