blob: a9bbfa17e101807057120178256d5f23b007912a [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
Daniel Dunbar0adcd352009-08-25 21:10:45 +000010#define DEBUG_TYPE "assembler"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000011#include "llvm/MC/MCAssembler.h"
Chris Lattnerbea2c952009-08-22 19:19:12 +000012#include "llvm/MC/MCSectionMachO.h"
13#include "llvm/Target/TargetMachOWriterInfo.h"
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +000014#include "llvm/ADT/DenseMap.h"
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000015#include "llvm/ADT/SmallString.h"
Daniel Dunbar0adcd352009-08-25 21:10:45 +000016#include "llvm/ADT/Statistic.h"
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000017#include "llvm/ADT/StringMap.h"
Daniel Dunbard6f761e2009-08-21 23:07:38 +000018#include "llvm/ADT/Twine.h"
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000019#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000020#include "llvm/Support/raw_ostream.h"
Chris Lattner23132b12009-08-24 03:52:50 +000021#include <vector>
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000022using namespace llvm;
23
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000024class MachObjectWriter;
25
Daniel Dunbar0adcd352009-08-25 21:10:45 +000026STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
27
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000028static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
29 MachObjectWriter &MOW);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000030
31class MachObjectWriter {
32 // See <mach-o/loader.h>.
33 enum {
34 Header_Magic32 = 0xFEEDFACE,
35 Header_Magic64 = 0xFEEDFACF
36 };
37
38 static const unsigned Header32Size = 28;
39 static const unsigned Header64Size = 32;
40 static const unsigned SegmentLoadCommand32Size = 56;
41 static const unsigned Section32Size = 68;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000042 static const unsigned SymtabLoadCommandSize = 24;
43 static const unsigned DysymtabLoadCommandSize = 80;
44 static const unsigned Nlist32Size = 12;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000045
46 enum HeaderFileType {
47 HFT_Object = 0x1
48 };
49
50 enum LoadCommandType {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000051 LCT_Segment = 0x1,
52 LCT_Symtab = 0x2,
53 LCT_Dysymtab = 0xb
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000054 };
55
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +000056 // See <mach-o/nlist.h>.
57 enum SymbolTypeType {
58 STT_Undefined = 0x00,
59 STT_Absolute = 0x02,
60 STT_Section = 0x0e
61 };
62
63 enum SymbolTypeFlags {
64 // If any of these bits are set, then the entry is a stab entry number (see
65 // <mach-o/stab.h>. Otherwise the other masks apply.
66 STF_StabsEntryMask = 0xe0,
67
68 STF_TypeMask = 0x0e,
69 STF_External = 0x01,
70 STF_PrivateExtern = 0x10
71 };
72
Daniel Dunbarad7c3d52009-08-26 00:18:21 +000073 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
74 /// symbol entry.
75 enum IndirectSymbolFlags {
76 ISF_Local = 0x80000000,
77 ISF_Absolute = 0x40000000
78 };
79
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +000080 /// MachSymbolData - Helper struct for containing some precomputed information
81 /// on symbols.
82 struct MachSymbolData {
83 MCSymbolData *SymbolData;
84 uint64_t StringIndex;
85 uint8_t SectionIndex;
86
87 // Support lexicographic sorting.
88 bool operator<(const MachSymbolData &RHS) const {
89 const std::string &Name = SymbolData->getSymbol().getName();
90 return Name < RHS.SymbolData->getSymbol().getName();
91 }
92 };
93
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000094 raw_ostream &OS;
95 bool IsLSB;
96
97public:
98 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
99 : OS(_OS), IsLSB(_IsLSB) {
100 }
101
102 /// @name Helper Methods
103 /// @{
104
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000105 void Write8(uint8_t Value) {
106 OS << char(Value);
107 }
108
109 void Write16(uint16_t Value) {
110 if (IsLSB) {
111 Write8(uint8_t(Value >> 0));
112 Write8(uint8_t(Value >> 8));
113 } else {
114 Write8(uint8_t(Value >> 8));
115 Write8(uint8_t(Value >> 0));
116 }
117 }
118
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000119 void Write32(uint32_t Value) {
120 if (IsLSB) {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000121 Write16(uint16_t(Value >> 0));
122 Write16(uint16_t(Value >> 16));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000123 } else {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000124 Write16(uint16_t(Value >> 16));
125 Write16(uint16_t(Value >> 0));
126 }
127 }
128
129 void Write64(uint64_t Value) {
130 if (IsLSB) {
131 Write32(uint32_t(Value >> 0));
132 Write32(uint32_t(Value >> 32));
133 } else {
134 Write32(uint32_t(Value >> 32));
135 Write32(uint32_t(Value >> 0));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000136 }
137 }
138
139 void WriteZeros(unsigned N) {
140 const char Zeros[16] = { 0 };
141
142 for (unsigned i = 0, e = N / 16; i != e; ++i)
143 OS << StringRef(Zeros, 16);
144
145 OS << StringRef(Zeros, N % 16);
146 }
147
148 void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
149 OS << Str;
150 if (ZeroFillSize)
151 WriteZeros(ZeroFillSize - Str.size());
152 }
153
154 /// @}
155
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000156 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000157 // struct mach_header (28 bytes)
158
159 uint64_t Start = OS.tell();
160 (void) Start;
161
162 Write32(Header_Magic32);
163
164 // FIXME: Support cputype.
165 Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
166
167 // FIXME: Support cpusubtype.
168 Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
169
170 Write32(HFT_Object);
171
172 // Object files have a single load command, the segment.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000173 Write32(NumLoadCommands);
174 Write32(LoadCommandsSize);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000175 Write32(0); // Flags
176
177 assert(OS.tell() - Start == Header32Size);
178 }
179
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000180 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
181 ///
182 /// \arg NumSections - The number of sections in this segment.
183 /// \arg SectionDataSize - The total size of the sections.
184 void WriteSegmentLoadCommand32(unsigned NumSections,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000185 uint64_t SectionDataStartOffset,
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000186 uint64_t SectionDataSize) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000187 // struct segment_command (56 bytes)
188
189 uint64_t Start = OS.tell();
190 (void) Start;
191
192 Write32(LCT_Segment);
193 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
194
195 WriteString("", 16);
196 Write32(0); // vmaddr
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000197 Write32(SectionDataSize); // vmsize
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000198 Write32(SectionDataStartOffset); // file offset
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000199 Write32(SectionDataSize); // file size
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000200 Write32(0x7); // maxprot
201 Write32(0x7); // initprot
202 Write32(NumSections);
203 Write32(0); // flags
204
205 assert(OS.tell() - Start == SegmentLoadCommand32Size);
206 }
207
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000208 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000209 // struct section (68 bytes)
210
211 uint64_t Start = OS.tell();
212 (void) Start;
213
214 // FIXME: cast<> support!
215 const MCSectionMachO &Section =
216 static_cast<const MCSectionMachO&>(SD.getSection());
217 WriteString(Section.getSectionName(), 16);
218 WriteString(Section.getSegmentName(), 16);
Daniel Dunbar5e835962009-08-26 02:48:04 +0000219 Write32(SD.getAddress()); // address
Daniel Dunbar6742e342009-08-26 04:13:32 +0000220 Write32(SD.getSize()); // size
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000221 Write32(FileOffset);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000222
223 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
224 Write32(Log2_32(SD.getAlignment()));
225 Write32(0); // file offset of relocation entries
226 Write32(0); // number of relocation entrions
227 Write32(Section.getTypeAndAttributes());
228 Write32(0); // reserved1
229 Write32(Section.getStubSize()); // reserved2
230
231 assert(OS.tell() - Start == Section32Size);
232 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000233
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000234 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
235 uint32_t StringTableOffset,
236 uint32_t StringTableSize) {
237 // struct symtab_command (24 bytes)
238
239 uint64_t Start = OS.tell();
240 (void) Start;
241
242 Write32(LCT_Symtab);
243 Write32(SymtabLoadCommandSize);
244 Write32(SymbolOffset);
245 Write32(NumSymbols);
246 Write32(StringTableOffset);
247 Write32(StringTableSize);
248
249 assert(OS.tell() - Start == SymtabLoadCommandSize);
250 }
251
252 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
253 uint32_t NumLocalSymbols,
254 uint32_t FirstExternalSymbol,
255 uint32_t NumExternalSymbols,
256 uint32_t FirstUndefinedSymbol,
257 uint32_t NumUndefinedSymbols,
258 uint32_t IndirectSymbolOffset,
259 uint32_t NumIndirectSymbols) {
260 // struct dysymtab_command (80 bytes)
261
262 uint64_t Start = OS.tell();
263 (void) Start;
264
265 Write32(LCT_Dysymtab);
266 Write32(DysymtabLoadCommandSize);
267 Write32(FirstLocalSymbol);
268 Write32(NumLocalSymbols);
269 Write32(FirstExternalSymbol);
270 Write32(NumExternalSymbols);
271 Write32(FirstUndefinedSymbol);
272 Write32(NumUndefinedSymbols);
273 Write32(0); // tocoff
274 Write32(0); // ntoc
275 Write32(0); // modtaboff
276 Write32(0); // nmodtab
277 Write32(0); // extrefsymoff
278 Write32(0); // nextrefsyms
279 Write32(IndirectSymbolOffset);
280 Write32(NumIndirectSymbols);
281 Write32(0); // extreloff
282 Write32(0); // nextrel
283 Write32(0); // locreloff
284 Write32(0); // nlocrel
285
286 assert(OS.tell() - Start == DysymtabLoadCommandSize);
287 }
288
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000289 void WriteNlist32(MachSymbolData &MSD) {
Daniel Dunbar5e835962009-08-26 02:48:04 +0000290 MCSymbolData &Data = *MSD.SymbolData;
291 MCSymbol &Symbol = Data.getSymbol();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000292 uint8_t Type = 0;
293
294 // Set the N_TYPE bits. See <mach-o/nlist.h>.
295 //
296 // FIXME: Are the prebound or indirect fields possible here?
297 if (Symbol.isUndefined())
298 Type = STT_Undefined;
299 else if (Symbol.isAbsolute())
300 Type = STT_Absolute;
301 else
302 Type = STT_Section;
303
304 // FIXME: Set STAB bits.
305
Daniel Dunbar5e835962009-08-26 02:48:04 +0000306 if (Data.isPrivateExtern())
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000307 Type |= STF_PrivateExtern;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000308
309 // Set external bit.
Daniel Dunbar5e835962009-08-26 02:48:04 +0000310 if (Data.isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000311 Type |= STF_External;
312
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000313 // struct nlist (12 bytes)
314
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000315 Write32(MSD.StringIndex);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000316 Write8(Type);
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000317 Write8(MSD.SectionIndex);
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000318
319 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
320 // value.
Daniel Dunbar5e835962009-08-26 02:48:04 +0000321 Write16(Data.getFlags() & 0xFFFF);
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000322
Daniel Dunbar5e835962009-08-26 02:48:04 +0000323 // Write the symbol address.
324 uint32_t Address = 0;
325 if (Symbol.isDefined()) {
326 if (Symbol.isAbsolute()) {
327 llvm_unreachable("FIXME: Not yet implemented!");
328 } else {
329 Address = Data.getFragment()->getAddress() + Data.getOffset();
330 }
331 }
332 Write32(Address);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000333 }
334
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000335 void BindIndirectSymbols(MCAssembler &Asm,
Daniel Dunbarbe963552009-08-26 13:57:54 +0000336 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000337 // This is the point where 'as' creates actual symbols for indirect symbols
338 // (in the following two passes). It would be easier for us to do this
339 // sooner when we see the attribute, but that makes getting the order in the
340 // symbol table much more complicated than it is worth.
341 //
342 // FIXME: Revisit this when the dust settles.
343
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000344 // Bind non lazy symbol pointers first.
345 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
346 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
347 // FIXME: cast<> support!
348 const MCSectionMachO &Section =
349 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
350
351 unsigned Type =
352 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
353 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
354 continue;
355
356 MCSymbolData *&Entry = SymbolMap[it->Symbol];
357 if (!Entry)
358 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
359 }
360
361 // Then lazy symbol pointers and symbol stubs.
362 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
363 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
364 // FIXME: cast<> support!
365 const MCSectionMachO &Section =
366 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
367
368 unsigned Type =
369 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
370 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
371 Type != MCSectionMachO::S_SYMBOL_STUBS)
372 continue;
373
374 MCSymbolData *&Entry = SymbolMap[it->Symbol];
375 if (!Entry) {
376 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
377
378 // Set the symbol type to undefined lazy, but only on construction.
379 //
380 // FIXME: Do not hardcode.
381 Entry->setFlags(Entry->getFlags() | 0x0001);
382 }
383 }
384 }
385
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000386 /// ComputeSymbolTable - Compute the symbol table data
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000387 ///
388 /// \param StringTable [out] - The string table data.
389 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
390 /// string table.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000391 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
392 std::vector<MachSymbolData> &LocalSymbolData,
393 std::vector<MachSymbolData> &ExternalSymbolData,
394 std::vector<MachSymbolData> &UndefinedSymbolData) {
395 // Build section lookup table.
396 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
397 unsigned Index = 1;
398 for (MCAssembler::iterator it = Asm.begin(),
399 ie = Asm.end(); it != ie; ++it, ++Index)
400 SectionIndexMap[&it->getSection()] = Index;
401 assert(Index <= 256 && "Too many sections!");
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000402
403 // Index 0 is always the empty string.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000404 StringMap<uint64_t> StringIndexMap;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000405 StringTable += '\x00';
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000406
407 // Build the symbol arrays and the string table, but only for non-local
408 // symbols.
409 //
410 // The particular order that we collect the symbols and create the string
411 // table, then sort the symbols is chosen to match 'as'. Even though it
412 // doesn't matter for correctness, this is important for letting us diff .o
413 // files.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000414 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
415 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000416 MCSymbol &Symbol = it->getSymbol();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000417
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000418 if (!it->isExternal() && !Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000419 continue;
420
421 uint64_t &Entry = StringIndexMap[Symbol.getName()];
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000422 if (!Entry) {
423 Entry = StringTable.size();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000424 StringTable += Symbol.getName();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000425 StringTable += '\x00';
426 }
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000427
428 MachSymbolData MSD;
429 MSD.SymbolData = it;
430 MSD.StringIndex = Entry;
431
432 if (Symbol.isUndefined()) {
433 MSD.SectionIndex = 0;
434 UndefinedSymbolData.push_back(MSD);
435 } else if (Symbol.isAbsolute()) {
436 MSD.SectionIndex = 0;
437 ExternalSymbolData.push_back(MSD);
438 } else {
439 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
440 assert(MSD.SectionIndex && "Invalid section index!");
441 ExternalSymbolData.push_back(MSD);
442 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000443 }
444
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000445 // Now add the data for local symbols.
446 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
447 ie = Asm.symbol_end(); it != ie; ++it) {
448 MCSymbol &Symbol = it->getSymbol();
449
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000450 if (it->isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000451 continue;
452
453 uint64_t &Entry = StringIndexMap[Symbol.getName()];
454 if (!Entry) {
455 Entry = StringTable.size();
456 StringTable += Symbol.getName();
457 StringTable += '\x00';
458 }
459
460 MachSymbolData MSD;
461 MSD.SymbolData = it;
462 MSD.StringIndex = Entry;
463
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000464 if (Symbol.isAbsolute()) {
465 MSD.SectionIndex = 0;
466 LocalSymbolData.push_back(MSD);
467 } else {
468 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
469 assert(MSD.SectionIndex && "Invalid section index!");
470 LocalSymbolData.push_back(MSD);
471 }
472 }
473
474 // External and undefined symbols are required to be in lexicographic order.
475 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
476 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
477
Daniel Dunbarbe963552009-08-26 13:57:54 +0000478 // Set the symbol indices.
479 Index = 0;
480 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
481 LocalSymbolData[i].SymbolData->setIndex(Index++);
482 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
483 ExternalSymbolData[i].SymbolData->setIndex(Index++);
484 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
485 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
486
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000487 // The string table is padded to a multiple of 4.
488 //
489 // FIXME: Check to see if this varies per arch.
490 while (StringTable.size() % 4)
491 StringTable += '\x00';
492 }
493
494 void WriteObject(MCAssembler &Asm) {
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000495 unsigned NumSections = Asm.size();
496
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000497 // Compute the symbol -> symbol data map.
498 //
499 // FIXME: This should not be here.
Daniel Dunbarbe963552009-08-26 13:57:54 +0000500 DenseMap<const MCSymbol*, MCSymbolData *> SymbolMap;
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000501 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
502 ie = Asm.symbol_end(); it != ie; ++it)
503 SymbolMap[&it->getSymbol()] = it;
504
505 // Create symbol data for any indirect symbols.
506 BindIndirectSymbols(Asm, SymbolMap);
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000507
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000508 // Compute symbol table information.
509 SmallString<256> StringTable;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000510 std::vector<MachSymbolData> LocalSymbolData;
511 std::vector<MachSymbolData> ExternalSymbolData;
512 std::vector<MachSymbolData> UndefinedSymbolData;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000513 unsigned NumSymbols = Asm.symbol_size();
514
515 // No symbol table command is written if there are no symbols.
516 if (NumSymbols)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000517 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
518 UndefinedSymbolData);
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000519
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000520 // The section data starts after the header, the segment load command (and
521 // section headers) and the symbol table.
522 unsigned NumLoadCommands = 1;
523 uint64_t LoadCommandsSize =
524 SegmentLoadCommand32Size + NumSections * Section32Size;
525
526 // Add the symbol table load command sizes, if used.
527 if (NumSymbols) {
528 NumLoadCommands += 2;
529 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
530 }
531
Daniel Dunbar6742e342009-08-26 04:13:32 +0000532 uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
533 uint64_t SectionDataEnd = SectionDataStart;
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000534 uint64_t SectionDataSize = 0;
Daniel Dunbar6742e342009-08-26 04:13:32 +0000535 if (!Asm.getSectionList().empty()) {
536 MCSectionData &SD = Asm.getSectionList().back();
537 SectionDataSize = SD.getAddress() + SD.getSize();
538 SectionDataEnd = SectionDataStart + SD.getAddress() + SD.getFileSize();
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000539 }
540
541 // Write the prolog, starting with the header and load command...
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000542 WriteHeader32(NumLoadCommands, LoadCommandsSize);
Daniel Dunbar6742e342009-08-26 04:13:32 +0000543 WriteSegmentLoadCommand32(NumSections, SectionDataStart, SectionDataSize);
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000544
545 // ... and then the section headers.
Daniel Dunbar6742e342009-08-26 04:13:32 +0000546 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
547 WriteSection32(*it, SectionDataStart + it->getAddress());
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000548
549 // Write the symbol table load command, if used.
550 if (NumSymbols) {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000551 unsigned FirstLocalSymbol = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000552 unsigned NumLocalSymbols = LocalSymbolData.size();
553 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
554 unsigned NumExternalSymbols = ExternalSymbolData.size();
555 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
556 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000557 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
558 unsigned NumSymTabSymbols =
559 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
560 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
561 uint64_t IndirectSymbolOffset = 0;
562
563 // If used, the indirect symbols are written after the section data.
564 if (NumIndirectSymbols)
Daniel Dunbar6742e342009-08-26 04:13:32 +0000565 IndirectSymbolOffset = SectionDataEnd;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000566
567 // The symbol table is written after the indirect symbol data.
Daniel Dunbar6742e342009-08-26 04:13:32 +0000568 uint64_t SymbolTableOffset = SectionDataEnd + IndirectSymbolSize;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000569
570 // The string table is written after symbol table.
571 uint64_t StringTableOffset =
572 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
573 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
574 StringTableOffset, StringTable.size());
575
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000576 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
577 FirstExternalSymbol, NumExternalSymbols,
578 FirstUndefinedSymbol, NumUndefinedSymbols,
579 IndirectSymbolOffset, NumIndirectSymbols);
580 }
581
582 // Write the actual section data.
583 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
584 WriteFileData(OS, *it, *this);
585
586 // Write the symbol table data, if used.
587 if (NumSymbols) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000588 // Write the indirect symbol entries.
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000589 for (MCAssembler::indirect_symbol_iterator
590 it = Asm.indirect_symbol_begin(),
591 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
592 // Indirect symbols in the non lazy symbol pointer section have some
593 // special handling.
594 const MCSectionMachO &Section =
595 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
596 unsigned Type =
597 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
598 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
599 // If this symbol is defined and internal, mark it as such.
600 if (it->Symbol->isDefined() &&
601 !SymbolMap.lookup(it->Symbol)->isExternal()) {
602 uint32_t Flags = ISF_Local;
603 if (it->Symbol->isAbsolute())
604 Flags |= ISF_Absolute;
605 Write32(Flags);
606 continue;
607 }
608 }
609
Daniel Dunbarbe963552009-08-26 13:57:54 +0000610 Write32(SymbolMap[it->Symbol]->getIndex());
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000611 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000612
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000613 // FIXME: Check that offsets match computed ones.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000614
615 // Write the symbol table entries.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000616 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
617 WriteNlist32(LocalSymbolData[i]);
618 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
619 WriteNlist32(ExternalSymbolData[i]);
620 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
621 WriteNlist32(UndefinedSymbolData[i]);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000622
623 // Write the string table.
624 OS << StringTable.str();
625 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000626 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000627};
628
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000629/* *** */
630
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000631MCFragment::MCFragment() : Kind(FragmentType(~0)) {
632}
633
Daniel Dunbar5e835962009-08-26 02:48:04 +0000634MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000635 : Kind(_Kind),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000636 Parent(_Parent),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000637 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000638{
Daniel Dunbar5e835962009-08-26 02:48:04 +0000639 if (Parent)
640 Parent->getFragmentList().push_back(this);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000641}
642
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000643MCFragment::~MCFragment() {
644}
645
Daniel Dunbar5e835962009-08-26 02:48:04 +0000646uint64_t MCFragment::getAddress() const {
647 assert(getParent() && "Missing Section!");
648 return getParent()->getAddress() + Offset;
649}
650
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000651/* *** */
652
653MCSectionData::MCSectionData() : Section(*(MCSection*)0) {}
654
655MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
656 : Section(_Section),
657 Alignment(1),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000658 Address(~UINT64_C(0)),
Daniel Dunbar6742e342009-08-26 04:13:32 +0000659 Size(~UINT64_C(0)),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000660 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000661{
662 if (A)
663 A->getSectionList().push_back(this);
664}
665
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000666/* *** */
667
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000668MCSymbolData::MCSymbolData() : Symbol(*(MCSymbol*)0) {}
669
670MCSymbolData::MCSymbolData(MCSymbol &_Symbol, MCFragment *_Fragment,
671 uint64_t _Offset, MCAssembler *A)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000672 : Symbol(_Symbol), Fragment(_Fragment), Offset(_Offset),
Daniel Dunbarbe963552009-08-26 13:57:54 +0000673 IsExternal(false), IsPrivateExtern(false), Flags(0), Index(0)
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000674{
675 if (A)
676 A->getSymbolList().push_back(this);
677}
678
679/* *** */
680
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000681MCAssembler::MCAssembler(raw_ostream &_OS) : OS(_OS) {}
682
683MCAssembler::~MCAssembler() {
684}
685
Daniel Dunbar6742e342009-08-26 04:13:32 +0000686void MCAssembler::LayoutSection(MCSectionData &SD, unsigned NextAlign) {
687 uint64_t Address = SD.getAddress();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000688
689 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
690 MCFragment &F = *it;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000691
Daniel Dunbar6742e342009-08-26 04:13:32 +0000692 F.setOffset(Address - SD.getAddress());
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000693
694 // Evaluate fragment size.
695 switch (F.getKind()) {
696 case MCFragment::FT_Align: {
697 MCAlignFragment &AF = cast<MCAlignFragment>(F);
698
Daniel Dunbar6742e342009-08-26 04:13:32 +0000699 uint64_t Size = RoundUpToAlignment(Address, AF.getAlignment()) - Address;
700 if (Size > AF.getMaxBytesToEmit())
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000701 AF.setFileSize(0);
702 else
Daniel Dunbar6742e342009-08-26 04:13:32 +0000703 AF.setFileSize(Size);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000704 break;
705 }
706
707 case MCFragment::FT_Data:
708 case MCFragment::FT_Fill:
709 F.setFileSize(F.getMaxFileSize());
710 break;
711
712 case MCFragment::FT_Org: {
713 MCOrgFragment &OF = cast<MCOrgFragment>(F);
714
715 if (!OF.getOffset().isAbsolute())
716 llvm_unreachable("FIXME: Not yet implemented!");
717 uint64_t OrgOffset = OF.getOffset().getConstant();
Daniel Dunbar6742e342009-08-26 04:13:32 +0000718 uint64_t Offset = Address - SD.getAddress();
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000719
720 // FIXME: We need a way to communicate this error.
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000721 if (OrgOffset < Offset)
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000722 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
Daniel Dunbar6742e342009-08-26 04:13:32 +0000723 "' (at offset '" + Twine(Offset) + "'");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000724
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000725 F.setFileSize(OrgOffset - Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000726 break;
727 }
728 }
729
Daniel Dunbar6742e342009-08-26 04:13:32 +0000730 Address += F.getFileSize();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000731 }
732
Daniel Dunbar6742e342009-08-26 04:13:32 +0000733 // Set the section sizes.
734 SD.setSize(Address - SD.getAddress());
735 SD.setFileSize(RoundUpToAlignment(Address, NextAlign) - SD.getAddress());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000736}
737
738/// WriteFileData - Write the \arg F data to the output file.
739static void WriteFileData(raw_ostream &OS, const MCFragment &F,
740 MachObjectWriter &MOW) {
741 uint64_t Start = OS.tell();
742 (void) Start;
743
Daniel Dunbar0adcd352009-08-25 21:10:45 +0000744 ++EmittedFragments;
745
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000746 // FIXME: Embed in fragments instead?
747 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000748 case MCFragment::FT_Align: {
749 MCAlignFragment &AF = cast<MCAlignFragment>(F);
750 uint64_t Count = AF.getFileSize() / AF.getValueSize();
751
752 // FIXME: This error shouldn't actually occur (the front end should emit
753 // multiple .align directives to enforce the semantics it wants), but is
754 // severe enough that we want to report it. How to handle this?
755 if (Count * AF.getValueSize() != AF.getFileSize())
756 llvm_report_error("undefined .align directive, value size '" +
757 Twine(AF.getValueSize()) +
758 "' is not a divisor of padding size '" +
759 Twine(AF.getFileSize()) + "'");
760
761 for (uint64_t i = 0; i != Count; ++i) {
762 switch (AF.getValueSize()) {
763 default:
764 assert(0 && "Invalid size!");
765 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
766 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
767 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
768 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
769 }
770 }
771 break;
772 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000773
774 case MCFragment::FT_Data:
775 OS << cast<MCDataFragment>(F).getContents().str();
776 break;
777
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000778 case MCFragment::FT_Fill: {
779 MCFillFragment &FF = cast<MCFillFragment>(F);
780
781 if (!FF.getValue().isAbsolute())
782 llvm_unreachable("FIXME: Not yet implemented!");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000783 int64_t Value = FF.getValue().getConstant();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000784
785 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
786 switch (FF.getValueSize()) {
787 default:
788 assert(0 && "Invalid size!");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000789 case 1: MOW.Write8 (uint8_t (Value)); break;
790 case 2: MOW.Write16(uint16_t(Value)); break;
791 case 4: MOW.Write32(uint32_t(Value)); break;
792 case 8: MOW.Write64(uint64_t(Value)); break;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000793 }
794 }
795 break;
796 }
797
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000798 case MCFragment::FT_Org: {
799 MCOrgFragment &OF = cast<MCOrgFragment>(F);
800
801 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
802 MOW.Write8(uint8_t(OF.getValue()));
803
804 break;
805 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000806 }
807
808 assert(OS.tell() - Start == F.getFileSize());
809}
810
811/// WriteFileData - Write the \arg SD data to the output file.
812static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
813 MachObjectWriter &MOW) {
814 uint64_t Start = OS.tell();
815 (void) Start;
816
817 for (MCSectionData::const_iterator it = SD.begin(),
818 ie = SD.end(); it != ie; ++it)
819 WriteFileData(OS, *it, MOW);
820
Daniel Dunbar6742e342009-08-26 04:13:32 +0000821 // Add section padding.
822 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
823 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
824
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000825 assert(OS.tell() - Start == SD.getFileSize());
826}
827
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000828void MCAssembler::Finish() {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000829 // Layout the sections and fragments.
Daniel Dunbar5e835962009-08-26 02:48:04 +0000830 uint64_t Address = 0;
Daniel Dunbar6742e342009-08-26 04:13:32 +0000831 for (iterator it = begin(), ie = end(); it != ie;) {
832 MCSectionData &SD = *it;
833
834 // Select the amount of padding alignment we need, based on either the next
835 // sections alignment or the default alignment.
836 //
837 // FIXME: This should probably match the native word size.
838 unsigned NextAlign = 4;
839 ++it;
840 if (it != ie)
841 NextAlign = it->getAlignment();
842
843 // Layout the section fragments and its size.
844 SD.setAddress(Address);
845 LayoutSection(SD, NextAlign);
846 Address += SD.getFileSize();
Daniel Dunbar5e835962009-08-26 02:48:04 +0000847 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000848
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000849 // Write the object file.
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000850 MachObjectWriter MOW(OS);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000851 MOW.WriteObject(*this);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000852
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000853 OS.flush();
854}