blob: 99d2988dc8ec94e71ff903d8bf43b01053f5ed2e [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"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000019using namespace llvm;
20
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000021class MachObjectWriter;
22
23static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
24 MachObjectWriter &MOW);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000025
26class MachObjectWriter {
27 // See <mach-o/loader.h>.
28 enum {
29 Header_Magic32 = 0xFEEDFACE,
30 Header_Magic64 = 0xFEEDFACF
31 };
32
33 static const unsigned Header32Size = 28;
34 static const unsigned Header64Size = 32;
35 static const unsigned SegmentLoadCommand32Size = 56;
36 static const unsigned Section32Size = 68;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000037 static const unsigned SymtabLoadCommandSize = 24;
38 static const unsigned DysymtabLoadCommandSize = 80;
39 static const unsigned Nlist32Size = 12;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000040
41 enum HeaderFileType {
42 HFT_Object = 0x1
43 };
44
45 enum LoadCommandType {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000046 LCT_Segment = 0x1,
47 LCT_Symtab = 0x2,
48 LCT_Dysymtab = 0xb
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000049 };
50
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +000051 // See <mach-o/nlist.h>.
52 enum SymbolTypeType {
53 STT_Undefined = 0x00,
54 STT_Absolute = 0x02,
55 STT_Section = 0x0e
56 };
57
58 enum SymbolTypeFlags {
59 // If any of these bits are set, then the entry is a stab entry number (see
60 // <mach-o/stab.h>. Otherwise the other masks apply.
61 STF_StabsEntryMask = 0xe0,
62
63 STF_TypeMask = 0x0e,
64 STF_External = 0x01,
65 STF_PrivateExtern = 0x10
66 };
67
68 /// MachSymbolData - Helper struct for containing some precomputed information
69 /// on symbols.
70 struct MachSymbolData {
71 MCSymbolData *SymbolData;
72 uint64_t StringIndex;
73 uint8_t SectionIndex;
74
75 // Support lexicographic sorting.
76 bool operator<(const MachSymbolData &RHS) const {
77 const std::string &Name = SymbolData->getSymbol().getName();
78 return Name < RHS.SymbolData->getSymbol().getName();
79 }
80 };
81
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000082 raw_ostream &OS;
83 bool IsLSB;
84
85public:
86 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
87 : OS(_OS), IsLSB(_IsLSB) {
88 }
89
90 /// @name Helper Methods
91 /// @{
92
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000093 void Write8(uint8_t Value) {
94 OS << char(Value);
95 }
96
97 void Write16(uint16_t Value) {
98 if (IsLSB) {
99 Write8(uint8_t(Value >> 0));
100 Write8(uint8_t(Value >> 8));
101 } else {
102 Write8(uint8_t(Value >> 8));
103 Write8(uint8_t(Value >> 0));
104 }
105 }
106
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000107 void Write32(uint32_t Value) {
108 if (IsLSB) {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000109 Write16(uint16_t(Value >> 0));
110 Write16(uint16_t(Value >> 16));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000111 } else {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000112 Write16(uint16_t(Value >> 16));
113 Write16(uint16_t(Value >> 0));
114 }
115 }
116
117 void Write64(uint64_t Value) {
118 if (IsLSB) {
119 Write32(uint32_t(Value >> 0));
120 Write32(uint32_t(Value >> 32));
121 } else {
122 Write32(uint32_t(Value >> 32));
123 Write32(uint32_t(Value >> 0));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000124 }
125 }
126
127 void WriteZeros(unsigned N) {
128 const char Zeros[16] = { 0 };
129
130 for (unsigned i = 0, e = N / 16; i != e; ++i)
131 OS << StringRef(Zeros, 16);
132
133 OS << StringRef(Zeros, N % 16);
134 }
135
136 void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
137 OS << Str;
138 if (ZeroFillSize)
139 WriteZeros(ZeroFillSize - Str.size());
140 }
141
142 /// @}
143
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000144 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000145 // struct mach_header (28 bytes)
146
147 uint64_t Start = OS.tell();
148 (void) Start;
149
150 Write32(Header_Magic32);
151
152 // FIXME: Support cputype.
153 Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
154
155 // FIXME: Support cpusubtype.
156 Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
157
158 Write32(HFT_Object);
159
160 // Object files have a single load command, the segment.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000161 Write32(NumLoadCommands);
162 Write32(LoadCommandsSize);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000163 Write32(0); // Flags
164
165 assert(OS.tell() - Start == Header32Size);
166 }
167
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000168 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
169 ///
170 /// \arg NumSections - The number of sections in this segment.
171 /// \arg SectionDataSize - The total size of the sections.
172 void WriteSegmentLoadCommand32(unsigned NumSections,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000173 uint64_t SectionDataStartOffset,
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000174 uint64_t SectionDataSize) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000175 // struct segment_command (56 bytes)
176
177 uint64_t Start = OS.tell();
178 (void) Start;
179
180 Write32(LCT_Segment);
181 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
182
183 WriteString("", 16);
184 Write32(0); // vmaddr
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000185 Write32(SectionDataSize); // vmsize
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000186 Write32(SectionDataStartOffset); // file offset
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000187 Write32(SectionDataSize); // file size
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000188 Write32(0x7); // maxprot
189 Write32(0x7); // initprot
190 Write32(NumSections);
191 Write32(0); // flags
192
193 assert(OS.tell() - Start == SegmentLoadCommand32Size);
194 }
195
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000196 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000197 // struct section (68 bytes)
198
199 uint64_t Start = OS.tell();
200 (void) Start;
201
202 // FIXME: cast<> support!
203 const MCSectionMachO &Section =
204 static_cast<const MCSectionMachO&>(SD.getSection());
205 WriteString(Section.getSectionName(), 16);
206 WriteString(Section.getSegmentName(), 16);
207 Write32(0); // address
208 Write32(SD.getFileSize()); // size
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000209 Write32(FileOffset);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000210
211 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
212 Write32(Log2_32(SD.getAlignment()));
213 Write32(0); // file offset of relocation entries
214 Write32(0); // number of relocation entrions
215 Write32(Section.getTypeAndAttributes());
216 Write32(0); // reserved1
217 Write32(Section.getStubSize()); // reserved2
218
219 assert(OS.tell() - Start == Section32Size);
220 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000221
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000222 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
223 uint32_t StringTableOffset,
224 uint32_t StringTableSize) {
225 // struct symtab_command (24 bytes)
226
227 uint64_t Start = OS.tell();
228 (void) Start;
229
230 Write32(LCT_Symtab);
231 Write32(SymtabLoadCommandSize);
232 Write32(SymbolOffset);
233 Write32(NumSymbols);
234 Write32(StringTableOffset);
235 Write32(StringTableSize);
236
237 assert(OS.tell() - Start == SymtabLoadCommandSize);
238 }
239
240 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
241 uint32_t NumLocalSymbols,
242 uint32_t FirstExternalSymbol,
243 uint32_t NumExternalSymbols,
244 uint32_t FirstUndefinedSymbol,
245 uint32_t NumUndefinedSymbols,
246 uint32_t IndirectSymbolOffset,
247 uint32_t NumIndirectSymbols) {
248 // struct dysymtab_command (80 bytes)
249
250 uint64_t Start = OS.tell();
251 (void) Start;
252
253 Write32(LCT_Dysymtab);
254 Write32(DysymtabLoadCommandSize);
255 Write32(FirstLocalSymbol);
256 Write32(NumLocalSymbols);
257 Write32(FirstExternalSymbol);
258 Write32(NumExternalSymbols);
259 Write32(FirstUndefinedSymbol);
260 Write32(NumUndefinedSymbols);
261 Write32(0); // tocoff
262 Write32(0); // ntoc
263 Write32(0); // modtaboff
264 Write32(0); // nmodtab
265 Write32(0); // extrefsymoff
266 Write32(0); // nextrefsyms
267 Write32(IndirectSymbolOffset);
268 Write32(NumIndirectSymbols);
269 Write32(0); // extreloff
270 Write32(0); // nextrel
271 Write32(0); // locreloff
272 Write32(0); // nlocrel
273
274 assert(OS.tell() - Start == DysymtabLoadCommandSize);
275 }
276
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000277 void WriteNlist32(MachSymbolData &MSD) {
278 MCSymbol &Symbol = MSD.SymbolData->getSymbol();
279 uint8_t Type = 0;
280
281 // Set the N_TYPE bits. See <mach-o/nlist.h>.
282 //
283 // FIXME: Are the prebound or indirect fields possible here?
284 if (Symbol.isUndefined())
285 Type = STT_Undefined;
286 else if (Symbol.isAbsolute())
287 Type = STT_Absolute;
288 else
289 Type = STT_Section;
290
291 // FIXME: Set STAB bits.
292
293 // FIXME: Set private external bit.
294
295 // Set external bit.
296 if (MSD.SymbolData->isExternal())
297 Type |= STF_External;
298
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000299 // struct nlist (12 bytes)
300
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000301 Write32(MSD.StringIndex);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000302 Write8(Type);
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000303 Write8(MSD.SectionIndex);
304 Write16(0); // FIXME: Desc
305 Write32(0); // FIXME: Value
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000306 }
307
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000308 /// ComputeSymbolTable - Compute the symbol table data
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000309 ///
310 /// \param StringTable [out] - The string table data.
311 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
312 /// string table.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000313
314 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
315 std::vector<MachSymbolData> &LocalSymbolData,
316 std::vector<MachSymbolData> &ExternalSymbolData,
317 std::vector<MachSymbolData> &UndefinedSymbolData) {
318 // Build section lookup table.
319 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
320 unsigned Index = 1;
321 for (MCAssembler::iterator it = Asm.begin(),
322 ie = Asm.end(); it != ie; ++it, ++Index)
323 SectionIndexMap[&it->getSection()] = Index;
324 assert(Index <= 256 && "Too many sections!");
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000325
326 // Index 0 is always the empty string.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000327 StringMap<uint64_t> StringIndexMap;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000328 StringTable += '\x00';
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000329
330 // Build the symbol arrays and the string table, but only for non-local
331 // symbols.
332 //
333 // The particular order that we collect the symbols and create the string
334 // table, then sort the symbols is chosen to match 'as'. Even though it
335 // doesn't matter for correctness, this is important for letting us diff .o
336 // files.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000337 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
338 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000339 MCSymbol &Symbol = it->getSymbol();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000340
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000341 if (!it->isExternal())
342 continue;
343
344 uint64_t &Entry = StringIndexMap[Symbol.getName()];
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000345 if (!Entry) {
346 Entry = StringTable.size();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000347 StringTable += Symbol.getName();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000348 StringTable += '\x00';
349 }
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000350
351 MachSymbolData MSD;
352 MSD.SymbolData = it;
353 MSD.StringIndex = Entry;
354
355 if (Symbol.isUndefined()) {
356 MSD.SectionIndex = 0;
357 UndefinedSymbolData.push_back(MSD);
358 } else if (Symbol.isAbsolute()) {
359 MSD.SectionIndex = 0;
360 ExternalSymbolData.push_back(MSD);
361 } else {
362 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
363 assert(MSD.SectionIndex && "Invalid section index!");
364 ExternalSymbolData.push_back(MSD);
365 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000366 }
367
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000368 // Now add the data for local symbols.
369 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
370 ie = Asm.symbol_end(); it != ie; ++it) {
371 MCSymbol &Symbol = it->getSymbol();
372
373 if (it->isExternal())
374 continue;
375
376 uint64_t &Entry = StringIndexMap[Symbol.getName()];
377 if (!Entry) {
378 Entry = StringTable.size();
379 StringTable += Symbol.getName();
380 StringTable += '\x00';
381 }
382
383 MachSymbolData MSD;
384 MSD.SymbolData = it;
385 MSD.StringIndex = Entry;
386
387 assert(!Symbol.isUndefined() && "Local symbol can not be undefined!");
388 if (Symbol.isAbsolute()) {
389 MSD.SectionIndex = 0;
390 LocalSymbolData.push_back(MSD);
391 } else {
392 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
393 assert(MSD.SectionIndex && "Invalid section index!");
394 LocalSymbolData.push_back(MSD);
395 }
396 }
397
398 // External and undefined symbols are required to be in lexicographic order.
399 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
400 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
401
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000402 // The string table is padded to a multiple of 4.
403 //
404 // FIXME: Check to see if this varies per arch.
405 while (StringTable.size() % 4)
406 StringTable += '\x00';
407 }
408
409 void WriteObject(MCAssembler &Asm) {
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000410 unsigned NumSections = Asm.size();
411
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000412 // Compute symbol table information.
413 SmallString<256> StringTable;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000414 std::vector<MachSymbolData> LocalSymbolData;
415 std::vector<MachSymbolData> ExternalSymbolData;
416 std::vector<MachSymbolData> UndefinedSymbolData;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000417 unsigned NumSymbols = Asm.symbol_size();
418
419 // No symbol table command is written if there are no symbols.
420 if (NumSymbols)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000421 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
422 UndefinedSymbolData);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000423
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000424 // Compute the file offsets for all the sections in advance, so that we can
425 // write things out in order.
426 SmallVector<uint64_t, 16> SectionFileOffsets;
427 SectionFileOffsets.resize(NumSections);
428
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000429 // The section data starts after the header, the segment load command (and
430 // section headers) and the symbol table.
431 unsigned NumLoadCommands = 1;
432 uint64_t LoadCommandsSize =
433 SegmentLoadCommand32Size + NumSections * Section32Size;
434
435 // Add the symbol table load command sizes, if used.
436 if (NumSymbols) {
437 NumLoadCommands += 2;
438 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
439 }
440
441 uint64_t FileOffset = Header32Size + LoadCommandsSize;
442 uint64_t SectionDataStartOffset = FileOffset;
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000443 uint64_t SectionDataSize = 0;
444 unsigned Index = 0;
445 for (MCAssembler::iterator it = Asm.begin(),
446 ie = Asm.end(); it != ie; ++it, ++Index) {
447 SectionFileOffsets[Index] = FileOffset;
448 FileOffset += it->getFileSize();
449 SectionDataSize += it->getFileSize();
450 }
451
452 // Write the prolog, starting with the header and load command...
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000453 WriteHeader32(NumLoadCommands, LoadCommandsSize);
454 WriteSegmentLoadCommand32(NumSections, SectionDataStartOffset,
455 SectionDataSize);
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000456
457 // ... and then the section headers.
458 Index = 0;
459 for (MCAssembler::iterator it = Asm.begin(),
460 ie = Asm.end(); it != ie; ++it, ++Index)
461 WriteSection32(*it, SectionFileOffsets[Index]);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000462
463 // Write the symbol table load command, if used.
464 if (NumSymbols) {
465 // The string table is written after all the section data.
466 uint64_t SymbolTableOffset = SectionDataStartOffset + SectionDataSize;
467 uint64_t StringTableOffset =
468 SymbolTableOffset + NumSymbols * Nlist32Size;
469 WriteSymtabLoadCommand(SymbolTableOffset, NumSymbols,
470 StringTableOffset, StringTable.size());
471
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000472 unsigned FirstLocalSymbol = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000473 unsigned NumLocalSymbols = LocalSymbolData.size();
474 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
475 unsigned NumExternalSymbols = ExternalSymbolData.size();
476 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
477 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
478 // FIXME: Get correct symbol indices and counts for indirect symbols.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000479 unsigned IndirectSymbolOffset = 0;
480 unsigned NumIndirectSymbols = 0;
481 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
482 FirstExternalSymbol, NumExternalSymbols,
483 FirstUndefinedSymbol, NumUndefinedSymbols,
484 IndirectSymbolOffset, NumIndirectSymbols);
485 }
486
487 // Write the actual section data.
488 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
489 WriteFileData(OS, *it, *this);
490
491 // Write the symbol table data, if used.
492 if (NumSymbols) {
493 // FIXME: Check that offsets match computed ones.
494
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000495 // FIXME: Some of these are ordered by name to help the linker.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000496
497 // Write the symbol table entries.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000498 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
499 WriteNlist32(LocalSymbolData[i]);
500 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
501 WriteNlist32(ExternalSymbolData[i]);
502 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
503 WriteNlist32(UndefinedSymbolData[i]);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000504
505 // Write the string table.
506 OS << StringTable.str();
507 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000508 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000509};
510
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000511/* *** */
512
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000513MCFragment::MCFragment() : Kind(FragmentType(~0)) {
514}
515
516MCFragment::MCFragment(FragmentType _Kind, MCSectionData *SD)
517 : Kind(_Kind),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000518 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000519{
520 if (SD)
521 SD->getFragmentList().push_back(this);
522}
523
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000524MCFragment::~MCFragment() {
525}
526
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000527/* *** */
528
529MCSectionData::MCSectionData() : Section(*(MCSection*)0) {}
530
531MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
532 : Section(_Section),
533 Alignment(1),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000534 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000535{
536 if (A)
537 A->getSectionList().push_back(this);
538}
539
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000540/* *** */
541
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000542MCSymbolData::MCSymbolData() : Symbol(*(MCSymbol*)0) {}
543
544MCSymbolData::MCSymbolData(MCSymbol &_Symbol, MCFragment *_Fragment,
545 uint64_t _Offset, MCAssembler *A)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000546 : Symbol(_Symbol), Fragment(_Fragment), Offset(_Offset),
547 IsExternal(false)
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000548{
549 if (A)
550 A->getSymbolList().push_back(this);
551}
552
553/* *** */
554
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000555MCAssembler::MCAssembler(raw_ostream &_OS) : OS(_OS) {}
556
557MCAssembler::~MCAssembler() {
558}
559
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000560void MCAssembler::LayoutSection(MCSectionData &SD) {
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000561 uint64_t Offset = 0;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000562
563 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
564 MCFragment &F = *it;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000565
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000566 F.setOffset(Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000567
568 // Evaluate fragment size.
569 switch (F.getKind()) {
570 case MCFragment::FT_Align: {
571 MCAlignFragment &AF = cast<MCAlignFragment>(F);
572
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000573 uint64_t AlignedOffset = RoundUpToAlignment(Offset, AF.getAlignment());
574 uint64_t PaddingBytes = AlignedOffset - Offset;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000575
576 if (PaddingBytes > AF.getMaxBytesToEmit())
577 AF.setFileSize(0);
578 else
579 AF.setFileSize(PaddingBytes);
580 break;
581 }
582
583 case MCFragment::FT_Data:
584 case MCFragment::FT_Fill:
585 F.setFileSize(F.getMaxFileSize());
586 break;
587
588 case MCFragment::FT_Org: {
589 MCOrgFragment &OF = cast<MCOrgFragment>(F);
590
591 if (!OF.getOffset().isAbsolute())
592 llvm_unreachable("FIXME: Not yet implemented!");
593 uint64_t OrgOffset = OF.getOffset().getConstant();
594
595 // FIXME: We need a way to communicate this error.
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000596 if (OrgOffset < Offset)
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000597 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000598 "' (section offset '" + Twine(Offset) + "'");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000599
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000600 F.setFileSize(OrgOffset - Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000601 break;
602 }
603 }
604
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000605 Offset += F.getFileSize();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000606 }
607
608 // FIXME: Pad section?
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000609 SD.setFileSize(Offset);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000610}
611
612/// WriteFileData - Write the \arg F data to the output file.
613static void WriteFileData(raw_ostream &OS, const MCFragment &F,
614 MachObjectWriter &MOW) {
615 uint64_t Start = OS.tell();
616 (void) Start;
617
618 // FIXME: Embed in fragments instead?
619 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000620 case MCFragment::FT_Align: {
621 MCAlignFragment &AF = cast<MCAlignFragment>(F);
622 uint64_t Count = AF.getFileSize() / AF.getValueSize();
623
624 // FIXME: This error shouldn't actually occur (the front end should emit
625 // multiple .align directives to enforce the semantics it wants), but is
626 // severe enough that we want to report it. How to handle this?
627 if (Count * AF.getValueSize() != AF.getFileSize())
628 llvm_report_error("undefined .align directive, value size '" +
629 Twine(AF.getValueSize()) +
630 "' is not a divisor of padding size '" +
631 Twine(AF.getFileSize()) + "'");
632
633 for (uint64_t i = 0; i != Count; ++i) {
634 switch (AF.getValueSize()) {
635 default:
636 assert(0 && "Invalid size!");
637 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
638 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
639 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
640 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
641 }
642 }
643 break;
644 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000645
646 case MCFragment::FT_Data:
647 OS << cast<MCDataFragment>(F).getContents().str();
648 break;
649
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000650 case MCFragment::FT_Fill: {
651 MCFillFragment &FF = cast<MCFillFragment>(F);
652
653 if (!FF.getValue().isAbsolute())
654 llvm_unreachable("FIXME: Not yet implemented!");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000655 int64_t Value = FF.getValue().getConstant();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000656
657 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
658 switch (FF.getValueSize()) {
659 default:
660 assert(0 && "Invalid size!");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000661 case 1: MOW.Write8 (uint8_t (Value)); break;
662 case 2: MOW.Write16(uint16_t(Value)); break;
663 case 4: MOW.Write32(uint32_t(Value)); break;
664 case 8: MOW.Write64(uint64_t(Value)); break;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000665 }
666 }
667 break;
668 }
669
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000670 case MCFragment::FT_Org: {
671 MCOrgFragment &OF = cast<MCOrgFragment>(F);
672
673 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
674 MOW.Write8(uint8_t(OF.getValue()));
675
676 break;
677 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000678 }
679
680 assert(OS.tell() - Start == F.getFileSize());
681}
682
683/// WriteFileData - Write the \arg SD data to the output file.
684static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
685 MachObjectWriter &MOW) {
686 uint64_t Start = OS.tell();
687 (void) Start;
688
689 for (MCSectionData::const_iterator it = SD.begin(),
690 ie = SD.end(); it != ie; ++it)
691 WriteFileData(OS, *it, MOW);
692
693 assert(OS.tell() - Start == SD.getFileSize());
694}
695
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000696void MCAssembler::Finish() {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000697 // Layout the sections and fragments.
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000698 for (iterator it = begin(), ie = end(); it != ie; ++it)
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000699 LayoutSection(*it);
700
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000701 // Write the object file.
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000702 MachObjectWriter MOW(OS);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000703 MOW.WriteObject(*this);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000704
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000705 OS.flush();
706}