blob: 4b265745785955204317f3024c80bb8d66efe7a2 [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
73 /// MachSymbolData - Helper struct for containing some precomputed information
74 /// on symbols.
75 struct MachSymbolData {
76 MCSymbolData *SymbolData;
77 uint64_t StringIndex;
78 uint8_t SectionIndex;
79
80 // Support lexicographic sorting.
81 bool operator<(const MachSymbolData &RHS) const {
82 const std::string &Name = SymbolData->getSymbol().getName();
83 return Name < RHS.SymbolData->getSymbol().getName();
84 }
85 };
86
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000087 raw_ostream &OS;
88 bool IsLSB;
89
90public:
91 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
92 : OS(_OS), IsLSB(_IsLSB) {
93 }
94
95 /// @name Helper Methods
96 /// @{
97
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000098 void Write8(uint8_t Value) {
99 OS << char(Value);
100 }
101
102 void Write16(uint16_t Value) {
103 if (IsLSB) {
104 Write8(uint8_t(Value >> 0));
105 Write8(uint8_t(Value >> 8));
106 } else {
107 Write8(uint8_t(Value >> 8));
108 Write8(uint8_t(Value >> 0));
109 }
110 }
111
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000112 void Write32(uint32_t Value) {
113 if (IsLSB) {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000114 Write16(uint16_t(Value >> 0));
115 Write16(uint16_t(Value >> 16));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000116 } else {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000117 Write16(uint16_t(Value >> 16));
118 Write16(uint16_t(Value >> 0));
119 }
120 }
121
122 void Write64(uint64_t Value) {
123 if (IsLSB) {
124 Write32(uint32_t(Value >> 0));
125 Write32(uint32_t(Value >> 32));
126 } else {
127 Write32(uint32_t(Value >> 32));
128 Write32(uint32_t(Value >> 0));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000129 }
130 }
131
132 void WriteZeros(unsigned N) {
133 const char Zeros[16] = { 0 };
134
135 for (unsigned i = 0, e = N / 16; i != e; ++i)
136 OS << StringRef(Zeros, 16);
137
138 OS << StringRef(Zeros, N % 16);
139 }
140
141 void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
142 OS << Str;
143 if (ZeroFillSize)
144 WriteZeros(ZeroFillSize - Str.size());
145 }
146
147 /// @}
148
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000149 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000150 // struct mach_header (28 bytes)
151
152 uint64_t Start = OS.tell();
153 (void) Start;
154
155 Write32(Header_Magic32);
156
157 // FIXME: Support cputype.
158 Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
159
160 // FIXME: Support cpusubtype.
161 Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
162
163 Write32(HFT_Object);
164
165 // Object files have a single load command, the segment.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000166 Write32(NumLoadCommands);
167 Write32(LoadCommandsSize);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000168 Write32(0); // Flags
169
170 assert(OS.tell() - Start == Header32Size);
171 }
172
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000173 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
174 ///
175 /// \arg NumSections - The number of sections in this segment.
176 /// \arg SectionDataSize - The total size of the sections.
177 void WriteSegmentLoadCommand32(unsigned NumSections,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000178 uint64_t SectionDataStartOffset,
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000179 uint64_t SectionDataSize) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000180 // struct segment_command (56 bytes)
181
182 uint64_t Start = OS.tell();
183 (void) Start;
184
185 Write32(LCT_Segment);
186 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
187
188 WriteString("", 16);
189 Write32(0); // vmaddr
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000190 Write32(SectionDataSize); // vmsize
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000191 Write32(SectionDataStartOffset); // file offset
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000192 Write32(SectionDataSize); // file size
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000193 Write32(0x7); // maxprot
194 Write32(0x7); // initprot
195 Write32(NumSections);
196 Write32(0); // flags
197
198 assert(OS.tell() - Start == SegmentLoadCommand32Size);
199 }
200
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000201 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000202 // struct section (68 bytes)
203
204 uint64_t Start = OS.tell();
205 (void) Start;
206
207 // FIXME: cast<> support!
208 const MCSectionMachO &Section =
209 static_cast<const MCSectionMachO&>(SD.getSection());
210 WriteString(Section.getSectionName(), 16);
211 WriteString(Section.getSegmentName(), 16);
212 Write32(0); // address
213 Write32(SD.getFileSize()); // size
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000214 Write32(FileOffset);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000215
216 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
217 Write32(Log2_32(SD.getAlignment()));
218 Write32(0); // file offset of relocation entries
219 Write32(0); // number of relocation entrions
220 Write32(Section.getTypeAndAttributes());
221 Write32(0); // reserved1
222 Write32(Section.getStubSize()); // reserved2
223
224 assert(OS.tell() - Start == Section32Size);
225 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000226
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000227 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
228 uint32_t StringTableOffset,
229 uint32_t StringTableSize) {
230 // struct symtab_command (24 bytes)
231
232 uint64_t Start = OS.tell();
233 (void) Start;
234
235 Write32(LCT_Symtab);
236 Write32(SymtabLoadCommandSize);
237 Write32(SymbolOffset);
238 Write32(NumSymbols);
239 Write32(StringTableOffset);
240 Write32(StringTableSize);
241
242 assert(OS.tell() - Start == SymtabLoadCommandSize);
243 }
244
245 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
246 uint32_t NumLocalSymbols,
247 uint32_t FirstExternalSymbol,
248 uint32_t NumExternalSymbols,
249 uint32_t FirstUndefinedSymbol,
250 uint32_t NumUndefinedSymbols,
251 uint32_t IndirectSymbolOffset,
252 uint32_t NumIndirectSymbols) {
253 // struct dysymtab_command (80 bytes)
254
255 uint64_t Start = OS.tell();
256 (void) Start;
257
258 Write32(LCT_Dysymtab);
259 Write32(DysymtabLoadCommandSize);
260 Write32(FirstLocalSymbol);
261 Write32(NumLocalSymbols);
262 Write32(FirstExternalSymbol);
263 Write32(NumExternalSymbols);
264 Write32(FirstUndefinedSymbol);
265 Write32(NumUndefinedSymbols);
266 Write32(0); // tocoff
267 Write32(0); // ntoc
268 Write32(0); // modtaboff
269 Write32(0); // nmodtab
270 Write32(0); // extrefsymoff
271 Write32(0); // nextrefsyms
272 Write32(IndirectSymbolOffset);
273 Write32(NumIndirectSymbols);
274 Write32(0); // extreloff
275 Write32(0); // nextrel
276 Write32(0); // locreloff
277 Write32(0); // nlocrel
278
279 assert(OS.tell() - Start == DysymtabLoadCommandSize);
280 }
281
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000282 void WriteNlist32(MachSymbolData &MSD) {
283 MCSymbol &Symbol = MSD.SymbolData->getSymbol();
284 uint8_t Type = 0;
285
286 // Set the N_TYPE bits. See <mach-o/nlist.h>.
287 //
288 // FIXME: Are the prebound or indirect fields possible here?
289 if (Symbol.isUndefined())
290 Type = STT_Undefined;
291 else if (Symbol.isAbsolute())
292 Type = STT_Absolute;
293 else
294 Type = STT_Section;
295
296 // FIXME: Set STAB bits.
297
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000298 if (MSD.SymbolData->isPrivateExtern())
299 Type |= STF_PrivateExtern;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000300
301 // Set external bit.
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000302 if (MSD.SymbolData->isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000303 Type |= STF_External;
304
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000305 // struct nlist (12 bytes)
306
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000307 Write32(MSD.StringIndex);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000308 Write8(Type);
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000309 Write8(MSD.SectionIndex);
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000310
311 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
312 // value.
313 Write16(MSD.SymbolData->getFlags() & 0xFFFF);
314
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000315 Write32(0); // FIXME: Value
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000316 }
317
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000318 void BindIndirectSymbols(MCAssembler &Asm) {
319 // This is the point where 'as' creates actual symbols for indirect symbols
320 // (in the following two passes). It would be easier for us to do this
321 // sooner when we see the attribute, but that makes getting the order in the
322 // symbol table much more complicated than it is worth.
323 //
324 // FIXME: Revisit this when the dust settles.
325
326 // FIXME: This should not be needed.
327 DenseMap<MCSymbol*, MCSymbolData *> SymbolMap;
328
329 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
330 ie = Asm.symbol_end(); it != ie; ++it)
331 SymbolMap[&it->getSymbol()] = it;
332
333 // Bind non lazy symbol pointers first.
334 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
335 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
336 // FIXME: cast<> support!
337 const MCSectionMachO &Section =
338 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
339
340 unsigned Type =
341 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
342 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
343 continue;
344
345 MCSymbolData *&Entry = SymbolMap[it->Symbol];
346 if (!Entry)
347 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
348 }
349
350 // Then lazy symbol pointers and symbol stubs.
351 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
352 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
353 // FIXME: cast<> support!
354 const MCSectionMachO &Section =
355 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
356
357 unsigned Type =
358 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
359 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
360 Type != MCSectionMachO::S_SYMBOL_STUBS)
361 continue;
362
363 MCSymbolData *&Entry = SymbolMap[it->Symbol];
364 if (!Entry) {
365 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
366
367 // Set the symbol type to undefined lazy, but only on construction.
368 //
369 // FIXME: Do not hardcode.
370 Entry->setFlags(Entry->getFlags() | 0x0001);
371 }
372 }
373 }
374
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000375 /// ComputeSymbolTable - Compute the symbol table data
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000376 ///
377 /// \param StringTable [out] - The string table data.
378 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
379 /// string table.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000380 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
381 std::vector<MachSymbolData> &LocalSymbolData,
382 std::vector<MachSymbolData> &ExternalSymbolData,
383 std::vector<MachSymbolData> &UndefinedSymbolData) {
384 // Build section lookup table.
385 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
386 unsigned Index = 1;
387 for (MCAssembler::iterator it = Asm.begin(),
388 ie = Asm.end(); it != ie; ++it, ++Index)
389 SectionIndexMap[&it->getSection()] = Index;
390 assert(Index <= 256 && "Too many sections!");
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000391
392 // Index 0 is always the empty string.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000393 StringMap<uint64_t> StringIndexMap;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000394 StringTable += '\x00';
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000395
396 // Build the symbol arrays and the string table, but only for non-local
397 // symbols.
398 //
399 // The particular order that we collect the symbols and create the string
400 // table, then sort the symbols is chosen to match 'as'. Even though it
401 // doesn't matter for correctness, this is important for letting us diff .o
402 // files.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000403 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
404 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000405 MCSymbol &Symbol = it->getSymbol();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000406
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000407 if (!it->isExternal() && !Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000408 continue;
409
410 uint64_t &Entry = StringIndexMap[Symbol.getName()];
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000411 if (!Entry) {
412 Entry = StringTable.size();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000413 StringTable += Symbol.getName();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000414 StringTable += '\x00';
415 }
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000416
417 MachSymbolData MSD;
418 MSD.SymbolData = it;
419 MSD.StringIndex = Entry;
420
421 if (Symbol.isUndefined()) {
422 MSD.SectionIndex = 0;
423 UndefinedSymbolData.push_back(MSD);
424 } else if (Symbol.isAbsolute()) {
425 MSD.SectionIndex = 0;
426 ExternalSymbolData.push_back(MSD);
427 } else {
428 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
429 assert(MSD.SectionIndex && "Invalid section index!");
430 ExternalSymbolData.push_back(MSD);
431 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000432 }
433
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000434 // Now add the data for local symbols.
435 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
436 ie = Asm.symbol_end(); it != ie; ++it) {
437 MCSymbol &Symbol = it->getSymbol();
438
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000439 if (it->isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000440 continue;
441
442 uint64_t &Entry = StringIndexMap[Symbol.getName()];
443 if (!Entry) {
444 Entry = StringTable.size();
445 StringTable += Symbol.getName();
446 StringTable += '\x00';
447 }
448
449 MachSymbolData MSD;
450 MSD.SymbolData = it;
451 MSD.StringIndex = Entry;
452
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000453 if (Symbol.isAbsolute()) {
454 MSD.SectionIndex = 0;
455 LocalSymbolData.push_back(MSD);
456 } else {
457 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
458 assert(MSD.SectionIndex && "Invalid section index!");
459 LocalSymbolData.push_back(MSD);
460 }
461 }
462
463 // External and undefined symbols are required to be in lexicographic order.
464 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
465 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
466
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000467 // The string table is padded to a multiple of 4.
468 //
469 // FIXME: Check to see if this varies per arch.
470 while (StringTable.size() % 4)
471 StringTable += '\x00';
472 }
473
474 void WriteObject(MCAssembler &Asm) {
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000475 unsigned NumSections = Asm.size();
476
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000477 BindIndirectSymbols(Asm);
478
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000479 // Compute symbol table information.
480 SmallString<256> StringTable;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000481 std::vector<MachSymbolData> LocalSymbolData;
482 std::vector<MachSymbolData> ExternalSymbolData;
483 std::vector<MachSymbolData> UndefinedSymbolData;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000484 unsigned NumSymbols = Asm.symbol_size();
485
486 // No symbol table command is written if there are no symbols.
487 if (NumSymbols)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000488 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
489 UndefinedSymbolData);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000490
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000491 // Compute the file offsets for all the sections in advance, so that we can
492 // write things out in order.
493 SmallVector<uint64_t, 16> SectionFileOffsets;
494 SectionFileOffsets.resize(NumSections);
495
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000496 // The section data starts after the header, the segment load command (and
497 // section headers) and the symbol table.
498 unsigned NumLoadCommands = 1;
499 uint64_t LoadCommandsSize =
500 SegmentLoadCommand32Size + NumSections * Section32Size;
501
502 // Add the symbol table load command sizes, if used.
503 if (NumSymbols) {
504 NumLoadCommands += 2;
505 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
506 }
507
508 uint64_t FileOffset = Header32Size + LoadCommandsSize;
509 uint64_t SectionDataStartOffset = FileOffset;
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000510 uint64_t SectionDataSize = 0;
511 unsigned Index = 0;
512 for (MCAssembler::iterator it = Asm.begin(),
513 ie = Asm.end(); it != ie; ++it, ++Index) {
514 SectionFileOffsets[Index] = FileOffset;
515 FileOffset += it->getFileSize();
516 SectionDataSize += it->getFileSize();
517 }
518
519 // Write the prolog, starting with the header and load command...
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000520 WriteHeader32(NumLoadCommands, LoadCommandsSize);
521 WriteSegmentLoadCommand32(NumSections, SectionDataStartOffset,
522 SectionDataSize);
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000523
524 // ... and then the section headers.
525 Index = 0;
526 for (MCAssembler::iterator it = Asm.begin(),
527 ie = Asm.end(); it != ie; ++it, ++Index)
528 WriteSection32(*it, SectionFileOffsets[Index]);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000529
530 // Write the symbol table load command, if used.
531 if (NumSymbols) {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000532 unsigned FirstLocalSymbol = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000533 unsigned NumLocalSymbols = LocalSymbolData.size();
534 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
535 unsigned NumExternalSymbols = ExternalSymbolData.size();
536 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
537 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000538 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
539 unsigned NumSymTabSymbols =
540 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
541 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
542 uint64_t IndirectSymbolOffset = 0;
543
544 // If used, the indirect symbols are written after the section data.
545 if (NumIndirectSymbols)
546 IndirectSymbolOffset = SectionDataStartOffset + SectionDataSize;
547
548 // The symbol table is written after the indirect symbol data.
549 uint64_t SymbolTableOffset =
550 SectionDataStartOffset + SectionDataSize + IndirectSymbolSize;
551
552 // The string table is written after symbol table.
553 uint64_t StringTableOffset =
554 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
555 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
556 StringTableOffset, StringTable.size());
557
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000558 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
559 FirstExternalSymbol, NumExternalSymbols,
560 FirstUndefinedSymbol, NumUndefinedSymbols,
561 IndirectSymbolOffset, NumIndirectSymbols);
562 }
563
564 // Write the actual section data.
565 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
566 WriteFileData(OS, *it, *this);
567
568 // Write the symbol table data, if used.
569 if (NumSymbols) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000570 // Write the indirect symbol entries.
571 //
572 // FIXME: We need the symbol index map for this.
573 for (unsigned i = 0, e = Asm.indirect_symbol_size(); i != e; ++i)
574 Write32(0);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000575
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000576 // FIXME: Check that offsets match computed ones.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000577
578 // Write the symbol table entries.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000579 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
580 WriteNlist32(LocalSymbolData[i]);
581 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
582 WriteNlist32(ExternalSymbolData[i]);
583 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
584 WriteNlist32(UndefinedSymbolData[i]);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000585
586 // Write the string table.
587 OS << StringTable.str();
588 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000589 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000590};
591
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000592/* *** */
593
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000594MCFragment::MCFragment() : Kind(FragmentType(~0)) {
595}
596
597MCFragment::MCFragment(FragmentType _Kind, MCSectionData *SD)
598 : Kind(_Kind),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000599 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000600{
601 if (SD)
602 SD->getFragmentList().push_back(this);
603}
604
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000605MCFragment::~MCFragment() {
606}
607
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000608/* *** */
609
610MCSectionData::MCSectionData() : Section(*(MCSection*)0) {}
611
612MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
613 : Section(_Section),
614 Alignment(1),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000615 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000616{
617 if (A)
618 A->getSectionList().push_back(this);
619}
620
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000621/* *** */
622
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000623MCSymbolData::MCSymbolData() : Symbol(*(MCSymbol*)0) {}
624
625MCSymbolData::MCSymbolData(MCSymbol &_Symbol, MCFragment *_Fragment,
626 uint64_t _Offset, MCAssembler *A)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000627 : Symbol(_Symbol), Fragment(_Fragment), Offset(_Offset),
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000628 IsExternal(false), IsPrivateExtern(false), Flags(0)
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000629{
630 if (A)
631 A->getSymbolList().push_back(this);
632}
633
634/* *** */
635
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000636MCAssembler::MCAssembler(raw_ostream &_OS) : OS(_OS) {}
637
638MCAssembler::~MCAssembler() {
639}
640
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000641void MCAssembler::LayoutSection(MCSectionData &SD) {
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000642 uint64_t Offset = 0;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000643
644 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
645 MCFragment &F = *it;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000646
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000647 F.setOffset(Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000648
649 // Evaluate fragment size.
650 switch (F.getKind()) {
651 case MCFragment::FT_Align: {
652 MCAlignFragment &AF = cast<MCAlignFragment>(F);
653
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000654 uint64_t AlignedOffset = RoundUpToAlignment(Offset, AF.getAlignment());
655 uint64_t PaddingBytes = AlignedOffset - Offset;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000656
657 if (PaddingBytes > AF.getMaxBytesToEmit())
658 AF.setFileSize(0);
659 else
660 AF.setFileSize(PaddingBytes);
661 break;
662 }
663
664 case MCFragment::FT_Data:
665 case MCFragment::FT_Fill:
666 F.setFileSize(F.getMaxFileSize());
667 break;
668
669 case MCFragment::FT_Org: {
670 MCOrgFragment &OF = cast<MCOrgFragment>(F);
671
672 if (!OF.getOffset().isAbsolute())
673 llvm_unreachable("FIXME: Not yet implemented!");
674 uint64_t OrgOffset = OF.getOffset().getConstant();
675
676 // FIXME: We need a way to communicate this error.
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000677 if (OrgOffset < Offset)
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000678 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000679 "' (section offset '" + Twine(Offset) + "'");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000680
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000681 F.setFileSize(OrgOffset - Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000682 break;
683 }
684 }
685
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000686 Offset += F.getFileSize();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000687 }
688
689 // FIXME: Pad section?
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000690 SD.setFileSize(Offset);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000691}
692
693/// WriteFileData - Write the \arg F data to the output file.
694static void WriteFileData(raw_ostream &OS, const MCFragment &F,
695 MachObjectWriter &MOW) {
696 uint64_t Start = OS.tell();
697 (void) Start;
698
Daniel Dunbar0adcd352009-08-25 21:10:45 +0000699 ++EmittedFragments;
700
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000701 // FIXME: Embed in fragments instead?
702 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000703 case MCFragment::FT_Align: {
704 MCAlignFragment &AF = cast<MCAlignFragment>(F);
705 uint64_t Count = AF.getFileSize() / AF.getValueSize();
706
707 // FIXME: This error shouldn't actually occur (the front end should emit
708 // multiple .align directives to enforce the semantics it wants), but is
709 // severe enough that we want to report it. How to handle this?
710 if (Count * AF.getValueSize() != AF.getFileSize())
711 llvm_report_error("undefined .align directive, value size '" +
712 Twine(AF.getValueSize()) +
713 "' is not a divisor of padding size '" +
714 Twine(AF.getFileSize()) + "'");
715
716 for (uint64_t i = 0; i != Count; ++i) {
717 switch (AF.getValueSize()) {
718 default:
719 assert(0 && "Invalid size!");
720 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
721 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
722 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
723 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
724 }
725 }
726 break;
727 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000728
729 case MCFragment::FT_Data:
730 OS << cast<MCDataFragment>(F).getContents().str();
731 break;
732
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000733 case MCFragment::FT_Fill: {
734 MCFillFragment &FF = cast<MCFillFragment>(F);
735
736 if (!FF.getValue().isAbsolute())
737 llvm_unreachable("FIXME: Not yet implemented!");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000738 int64_t Value = FF.getValue().getConstant();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000739
740 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
741 switch (FF.getValueSize()) {
742 default:
743 assert(0 && "Invalid size!");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000744 case 1: MOW.Write8 (uint8_t (Value)); break;
745 case 2: MOW.Write16(uint16_t(Value)); break;
746 case 4: MOW.Write32(uint32_t(Value)); break;
747 case 8: MOW.Write64(uint64_t(Value)); break;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000748 }
749 }
750 break;
751 }
752
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000753 case MCFragment::FT_Org: {
754 MCOrgFragment &OF = cast<MCOrgFragment>(F);
755
756 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
757 MOW.Write8(uint8_t(OF.getValue()));
758
759 break;
760 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000761 }
762
763 assert(OS.tell() - Start == F.getFileSize());
764}
765
766/// WriteFileData - Write the \arg SD data to the output file.
767static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
768 MachObjectWriter &MOW) {
769 uint64_t Start = OS.tell();
770 (void) Start;
771
772 for (MCSectionData::const_iterator it = SD.begin(),
773 ie = SD.end(); it != ie; ++it)
774 WriteFileData(OS, *it, MOW);
775
776 assert(OS.tell() - Start == SD.getFileSize());
777}
778
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000779void MCAssembler::Finish() {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000780 // Layout the sections and fragments.
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000781 for (iterator it = begin(), ie = end(); it != ie; ++it)
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000782 LayoutSection(*it);
783
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000784 // Write the object file.
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000785 MachObjectWriter MOW(OS);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000786 MOW.WriteObject(*this);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000787
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000788 OS.flush();
789}