blob: 8057fcb3593337a881631937ed060da7058ca2b3 [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
Daniel Dunbard5a8e982009-08-28 05:49:21 +000031/// isVirtualSection - Check if this is a section which does not actually exist
32/// in the object file.
33static bool isVirtualSection(const MCSection &Section) {
34 // FIXME: Lame.
35 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
36 unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
37 return (Type == MCSectionMachO::S_ZEROFILL);
38}
39
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000040class MachObjectWriter {
41 // See <mach-o/loader.h>.
42 enum {
43 Header_Magic32 = 0xFEEDFACE,
44 Header_Magic64 = 0xFEEDFACF
45 };
46
47 static const unsigned Header32Size = 28;
48 static const unsigned Header64Size = 32;
49 static const unsigned SegmentLoadCommand32Size = 56;
50 static const unsigned Section32Size = 68;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000051 static const unsigned SymtabLoadCommandSize = 24;
52 static const unsigned DysymtabLoadCommandSize = 80;
53 static const unsigned Nlist32Size = 12;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +000054 static const unsigned RelocationInfoSize = 8;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000055
56 enum HeaderFileType {
57 HFT_Object = 0x1
58 };
59
Daniel Dunbar6009db42009-08-26 21:22:22 +000060 enum HeaderFlags {
61 HF_SubsectionsViaSymbols = 0x2000
62 };
63
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000064 enum LoadCommandType {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000065 LCT_Segment = 0x1,
66 LCT_Symtab = 0x2,
67 LCT_Dysymtab = 0xb
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000068 };
69
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +000070 // See <mach-o/nlist.h>.
71 enum SymbolTypeType {
72 STT_Undefined = 0x00,
73 STT_Absolute = 0x02,
74 STT_Section = 0x0e
75 };
76
77 enum SymbolTypeFlags {
78 // If any of these bits are set, then the entry is a stab entry number (see
79 // <mach-o/stab.h>. Otherwise the other masks apply.
80 STF_StabsEntryMask = 0xe0,
81
82 STF_TypeMask = 0x0e,
83 STF_External = 0x01,
84 STF_PrivateExtern = 0x10
85 };
86
Daniel Dunbarad7c3d52009-08-26 00:18:21 +000087 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
88 /// symbol entry.
89 enum IndirectSymbolFlags {
90 ISF_Local = 0x80000000,
91 ISF_Absolute = 0x40000000
92 };
93
Daniel Dunbar3f6a9602009-08-26 13:58:10 +000094 /// RelocationFlags - Special flags for addresses.
95 enum RelocationFlags {
96 RF_Scattered = 0x80000000
97 };
98
99 enum RelocationInfoType {
100 RIT_Vanilla = 0,
101 RIT_Pair = 1,
102 RIT_Difference = 2,
103 RIT_PreboundLazyPointer = 3,
104 RIT_LocalDifference = 4
105 };
106
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000107 /// MachSymbolData - Helper struct for containing some precomputed information
108 /// on symbols.
109 struct MachSymbolData {
110 MCSymbolData *SymbolData;
111 uint64_t StringIndex;
112 uint8_t SectionIndex;
113
114 // Support lexicographic sorting.
115 bool operator<(const MachSymbolData &RHS) const {
116 const std::string &Name = SymbolData->getSymbol().getName();
117 return Name < RHS.SymbolData->getSymbol().getName();
118 }
119 };
120
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000121 raw_ostream &OS;
122 bool IsLSB;
123
124public:
125 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
126 : OS(_OS), IsLSB(_IsLSB) {
127 }
128
129 /// @name Helper Methods
130 /// @{
131
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000132 void Write8(uint8_t Value) {
133 OS << char(Value);
134 }
135
136 void Write16(uint16_t Value) {
137 if (IsLSB) {
138 Write8(uint8_t(Value >> 0));
139 Write8(uint8_t(Value >> 8));
140 } else {
141 Write8(uint8_t(Value >> 8));
142 Write8(uint8_t(Value >> 0));
143 }
144 }
145
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000146 void Write32(uint32_t Value) {
147 if (IsLSB) {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000148 Write16(uint16_t(Value >> 0));
149 Write16(uint16_t(Value >> 16));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000150 } else {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000151 Write16(uint16_t(Value >> 16));
152 Write16(uint16_t(Value >> 0));
153 }
154 }
155
156 void Write64(uint64_t Value) {
157 if (IsLSB) {
158 Write32(uint32_t(Value >> 0));
159 Write32(uint32_t(Value >> 32));
160 } else {
161 Write32(uint32_t(Value >> 32));
162 Write32(uint32_t(Value >> 0));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000163 }
164 }
165
166 void WriteZeros(unsigned N) {
167 const char Zeros[16] = { 0 };
168
169 for (unsigned i = 0, e = N / 16; i != e; ++i)
170 OS << StringRef(Zeros, 16);
171
172 OS << StringRef(Zeros, N % 16);
173 }
174
175 void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
176 OS << Str;
177 if (ZeroFillSize)
178 WriteZeros(ZeroFillSize - Str.size());
179 }
180
181 /// @}
182
Daniel Dunbar6009db42009-08-26 21:22:22 +0000183 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
184 bool SubsectionsViaSymbols) {
185 uint32_t Flags = 0;
186
187 if (SubsectionsViaSymbols)
188 Flags |= HF_SubsectionsViaSymbols;
189
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000190 // struct mach_header (28 bytes)
191
192 uint64_t Start = OS.tell();
193 (void) Start;
194
195 Write32(Header_Magic32);
196
197 // FIXME: Support cputype.
198 Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000199 // FIXME: Support cpusubtype.
200 Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000201 Write32(HFT_Object);
Daniel Dunbar6009db42009-08-26 21:22:22 +0000202 Write32(NumLoadCommands); // Object files have a single load command, the
203 // segment.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000204 Write32(LoadCommandsSize);
Daniel Dunbar6009db42009-08-26 21:22:22 +0000205 Write32(Flags);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000206
207 assert(OS.tell() - Start == Header32Size);
208 }
209
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000210 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
211 ///
212 /// \arg NumSections - The number of sections in this segment.
213 /// \arg SectionDataSize - The total size of the sections.
214 void WriteSegmentLoadCommand32(unsigned NumSections,
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000215 uint64_t VMSize,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000216 uint64_t SectionDataStartOffset,
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000217 uint64_t SectionDataSize) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000218 // struct segment_command (56 bytes)
219
220 uint64_t Start = OS.tell();
221 (void) Start;
222
223 Write32(LCT_Segment);
224 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
225
226 WriteString("", 16);
227 Write32(0); // vmaddr
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000228 Write32(VMSize); // vmsize
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000229 Write32(SectionDataStartOffset); // file offset
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000230 Write32(SectionDataSize); // file size
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000231 Write32(0x7); // maxprot
232 Write32(0x7); // initprot
233 Write32(NumSections);
234 Write32(0); // flags
235
236 assert(OS.tell() - Start == SegmentLoadCommand32Size);
237 }
238
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000239 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
240 uint64_t RelocationsStart, unsigned NumRelocations) {
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000241 // The offset is unused for virtual sections.
242 if (isVirtualSection(SD.getSection())) {
243 assert(SD.getFileSize() == 0 && "Invalid file size!");
244 FileOffset = 0;
245 }
246
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000247 // struct section (68 bytes)
248
249 uint64_t Start = OS.tell();
250 (void) Start;
251
252 // FIXME: cast<> support!
253 const MCSectionMachO &Section =
254 static_cast<const MCSectionMachO&>(SD.getSection());
255 WriteString(Section.getSectionName(), 16);
256 WriteString(Section.getSegmentName(), 16);
Daniel Dunbar5e835962009-08-26 02:48:04 +0000257 Write32(SD.getAddress()); // address
Daniel Dunbar6742e342009-08-26 04:13:32 +0000258 Write32(SD.getSize()); // size
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000259 Write32(FileOffset);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000260
261 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
262 Write32(Log2_32(SD.getAlignment()));
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000263 Write32(NumRelocations ? RelocationsStart : 0);
264 Write32(NumRelocations);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000265 Write32(Section.getTypeAndAttributes());
266 Write32(0); // reserved1
267 Write32(Section.getStubSize()); // reserved2
268
269 assert(OS.tell() - Start == Section32Size);
270 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000271
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000272 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
273 uint32_t StringTableOffset,
274 uint32_t StringTableSize) {
275 // struct symtab_command (24 bytes)
276
277 uint64_t Start = OS.tell();
278 (void) Start;
279
280 Write32(LCT_Symtab);
281 Write32(SymtabLoadCommandSize);
282 Write32(SymbolOffset);
283 Write32(NumSymbols);
284 Write32(StringTableOffset);
285 Write32(StringTableSize);
286
287 assert(OS.tell() - Start == SymtabLoadCommandSize);
288 }
289
290 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
291 uint32_t NumLocalSymbols,
292 uint32_t FirstExternalSymbol,
293 uint32_t NumExternalSymbols,
294 uint32_t FirstUndefinedSymbol,
295 uint32_t NumUndefinedSymbols,
296 uint32_t IndirectSymbolOffset,
297 uint32_t NumIndirectSymbols) {
298 // struct dysymtab_command (80 bytes)
299
300 uint64_t Start = OS.tell();
301 (void) Start;
302
303 Write32(LCT_Dysymtab);
304 Write32(DysymtabLoadCommandSize);
305 Write32(FirstLocalSymbol);
306 Write32(NumLocalSymbols);
307 Write32(FirstExternalSymbol);
308 Write32(NumExternalSymbols);
309 Write32(FirstUndefinedSymbol);
310 Write32(NumUndefinedSymbols);
311 Write32(0); // tocoff
312 Write32(0); // ntoc
313 Write32(0); // modtaboff
314 Write32(0); // nmodtab
315 Write32(0); // extrefsymoff
316 Write32(0); // nextrefsyms
317 Write32(IndirectSymbolOffset);
318 Write32(NumIndirectSymbols);
319 Write32(0); // extreloff
320 Write32(0); // nextrel
321 Write32(0); // locreloff
322 Write32(0); // nlocrel
323
324 assert(OS.tell() - Start == DysymtabLoadCommandSize);
325 }
326
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000327 void WriteNlist32(MachSymbolData &MSD) {
Daniel Dunbar5e835962009-08-26 02:48:04 +0000328 MCSymbolData &Data = *MSD.SymbolData;
329 MCSymbol &Symbol = Data.getSymbol();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000330 uint8_t Type = 0;
331
332 // Set the N_TYPE bits. See <mach-o/nlist.h>.
333 //
334 // FIXME: Are the prebound or indirect fields possible here?
335 if (Symbol.isUndefined())
336 Type = STT_Undefined;
337 else if (Symbol.isAbsolute())
338 Type = STT_Absolute;
339 else
340 Type = STT_Section;
341
342 // FIXME: Set STAB bits.
343
Daniel Dunbar5e835962009-08-26 02:48:04 +0000344 if (Data.isPrivateExtern())
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000345 Type |= STF_PrivateExtern;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000346
347 // Set external bit.
Daniel Dunbar5e835962009-08-26 02:48:04 +0000348 if (Data.isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000349 Type |= STF_External;
350
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000351 // struct nlist (12 bytes)
352
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000353 Write32(MSD.StringIndex);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000354 Write8(Type);
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000355 Write8(MSD.SectionIndex);
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000356
357 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
358 // value.
Daniel Dunbar5e835962009-08-26 02:48:04 +0000359 Write16(Data.getFlags() & 0xFFFF);
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000360
Daniel Dunbar5e835962009-08-26 02:48:04 +0000361 // Write the symbol address.
362 uint32_t Address = 0;
363 if (Symbol.isDefined()) {
364 if (Symbol.isAbsolute()) {
365 llvm_unreachable("FIXME: Not yet implemented!");
366 } else {
367 Address = Data.getFragment()->getAddress() + Data.getOffset();
368 }
369 }
370 Write32(Address);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000371 }
372
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000373 struct MachRelocationEntry {
374 uint32_t Word0;
375 uint32_t Word1;
376 };
377 void ComputeScatteredRelocationInfo(MCAssembler &Asm,
378 MCSectionData::Fixup &Fixup,
379 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
380 std::vector<MachRelocationEntry> &Relocs) {
381 uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
382 unsigned IsPCRel = 0;
383 unsigned Type = RIT_Vanilla;
384
385 // See <reloc.h>.
386
387 const MCSymbol *A = Fixup.Value.getSymA();
388 MCSymbolData *SD = SymbolMap.lookup(A);
389 uint32_t Value = SD->getFragment()->getAddress() + SD->getOffset();
390 uint32_t Value2 = 0;
391
392 if (const MCSymbol *B = Fixup.Value.getSymB()) {
393 Type = RIT_LocalDifference;
394
395 MCSymbolData *SD = SymbolMap.lookup(B);
396 Value2 = SD->getFragment()->getAddress() + SD->getOffset();
397 }
398
399 unsigned Log2Size = Log2_32(Fixup.Size);
400 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
401
402 // The value which goes in the fixup is current value of the expression.
403 Fixup.FixedValue = Value - Value2 + Fixup.Value.getConstant();
404
405 MachRelocationEntry MRE;
406 MRE.Word0 = ((Address << 0) |
407 (Type << 24) |
408 (Log2Size << 28) |
409 (IsPCRel << 30) |
410 RF_Scattered);
411 MRE.Word1 = Value;
412 Relocs.push_back(MRE);
413
414 if (Type == RIT_LocalDifference) {
415 Type = RIT_Pair;
416
417 MachRelocationEntry MRE;
418 MRE.Word0 = ((0 << 0) |
419 (Type << 24) |
420 (Log2Size << 28) |
421 (0 << 30) |
422 RF_Scattered);
423 MRE.Word1 = Value2;
424 Relocs.push_back(MRE);
425 }
426 }
427
428 void ComputeRelocationInfo(MCAssembler &Asm,
429 MCSectionData::Fixup &Fixup,
430 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
431 std::vector<MachRelocationEntry> &Relocs) {
432 // If this is a local symbol plus an offset or a difference, then we need a
433 // scattered relocation entry.
434 if (Fixup.Value.getSymB()) // a - b
435 return ComputeScatteredRelocationInfo(Asm, Fixup, SymbolMap, Relocs);
436 if (Fixup.Value.getSymA() && Fixup.Value.getConstant())
437 if (!Fixup.Value.getSymA()->isUndefined())
438 return ComputeScatteredRelocationInfo(Asm, Fixup, SymbolMap, Relocs);
439
440 // See <reloc.h>.
441 uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
442 uint32_t Value = 0;
443 unsigned Index = 0;
444 unsigned IsPCRel = 0;
445 unsigned IsExtern = 0;
446 unsigned Type = 0;
447
448 if (Fixup.Value.isAbsolute()) { // constant
449 // SymbolNum of 0 indicates the absolute section.
450 Type = RIT_Vanilla;
451 Value = 0;
452 llvm_unreachable("FIXME: Not yet implemented!");
453 } else {
454 const MCSymbol *Symbol = Fixup.Value.getSymA();
455 MCSymbolData *SD = SymbolMap.lookup(Symbol);
456
457 if (Symbol->isUndefined()) {
458 IsExtern = 1;
459 Index = SD->getIndex();
460 Value = 0;
461 } else {
462 // The index is the section ordinal.
463 //
464 // FIXME: O(N)
465 Index = 1;
466 for (MCAssembler::iterator it = Asm.begin(),
467 ie = Asm.end(); it != ie; ++it, ++Index)
468 if (&*it == SD->getFragment()->getParent())
469 break;
470 Value = SD->getFragment()->getAddress() + SD->getOffset();
471 }
472
473 Type = RIT_Vanilla;
474 }
475
476 // The value which goes in the fixup is current value of the expression.
477 Fixup.FixedValue = Value + Fixup.Value.getConstant();
478
479 unsigned Log2Size = Log2_32(Fixup.Size);
480 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
481
482 // struct relocation_info (8 bytes)
483 MachRelocationEntry MRE;
484 MRE.Word0 = Address;
485 MRE.Word1 = ((Index << 0) |
486 (IsPCRel << 24) |
487 (Log2Size << 25) |
488 (IsExtern << 27) |
489 (Type << 28));
490 Relocs.push_back(MRE);
491 }
492
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000493 void BindIndirectSymbols(MCAssembler &Asm,
Daniel Dunbarbe963552009-08-26 13:57:54 +0000494 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000495 // This is the point where 'as' creates actual symbols for indirect symbols
496 // (in the following two passes). It would be easier for us to do this
497 // sooner when we see the attribute, but that makes getting the order in the
498 // symbol table much more complicated than it is worth.
499 //
500 // FIXME: Revisit this when the dust settles.
501
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000502 // Bind non lazy symbol pointers first.
503 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
504 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
505 // FIXME: cast<> support!
506 const MCSectionMachO &Section =
507 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
508
509 unsigned Type =
510 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
511 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
512 continue;
513
514 MCSymbolData *&Entry = SymbolMap[it->Symbol];
515 if (!Entry)
516 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
517 }
518
519 // Then lazy symbol pointers and symbol stubs.
520 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
521 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
522 // FIXME: cast<> support!
523 const MCSectionMachO &Section =
524 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
525
526 unsigned Type =
527 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
528 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
529 Type != MCSectionMachO::S_SYMBOL_STUBS)
530 continue;
531
532 MCSymbolData *&Entry = SymbolMap[it->Symbol];
533 if (!Entry) {
534 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
535
536 // Set the symbol type to undefined lazy, but only on construction.
537 //
538 // FIXME: Do not hardcode.
539 Entry->setFlags(Entry->getFlags() | 0x0001);
540 }
541 }
542 }
543
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000544 /// ComputeSymbolTable - Compute the symbol table data
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000545 ///
546 /// \param StringTable [out] - The string table data.
547 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
548 /// string table.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000549 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
550 std::vector<MachSymbolData> &LocalSymbolData,
551 std::vector<MachSymbolData> &ExternalSymbolData,
552 std::vector<MachSymbolData> &UndefinedSymbolData) {
553 // Build section lookup table.
554 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
555 unsigned Index = 1;
556 for (MCAssembler::iterator it = Asm.begin(),
557 ie = Asm.end(); it != ie; ++it, ++Index)
558 SectionIndexMap[&it->getSection()] = Index;
559 assert(Index <= 256 && "Too many sections!");
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000560
561 // Index 0 is always the empty string.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000562 StringMap<uint64_t> StringIndexMap;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000563 StringTable += '\x00';
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000564
565 // Build the symbol arrays and the string table, but only for non-local
566 // symbols.
567 //
568 // The particular order that we collect the symbols and create the string
569 // table, then sort the symbols is chosen to match 'as'. Even though it
570 // doesn't matter for correctness, this is important for letting us diff .o
571 // files.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000572 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
573 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000574 MCSymbol &Symbol = it->getSymbol();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000575
Daniel Dunbar959fd882009-08-26 22:13:22 +0000576 // Ignore assembler temporaries.
577 if (it->getSymbol().isTemporary())
578 continue;
579
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000580 if (!it->isExternal() && !Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000581 continue;
582
583 uint64_t &Entry = StringIndexMap[Symbol.getName()];
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000584 if (!Entry) {
585 Entry = StringTable.size();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000586 StringTable += Symbol.getName();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000587 StringTable += '\x00';
588 }
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000589
590 MachSymbolData MSD;
591 MSD.SymbolData = it;
592 MSD.StringIndex = Entry;
593
594 if (Symbol.isUndefined()) {
595 MSD.SectionIndex = 0;
596 UndefinedSymbolData.push_back(MSD);
597 } else if (Symbol.isAbsolute()) {
598 MSD.SectionIndex = 0;
599 ExternalSymbolData.push_back(MSD);
600 } else {
601 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
602 assert(MSD.SectionIndex && "Invalid section index!");
603 ExternalSymbolData.push_back(MSD);
604 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000605 }
606
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000607 // Now add the data for local symbols.
608 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
609 ie = Asm.symbol_end(); it != ie; ++it) {
610 MCSymbol &Symbol = it->getSymbol();
611
Daniel Dunbar959fd882009-08-26 22:13:22 +0000612 // Ignore assembler temporaries.
613 if (it->getSymbol().isTemporary())
614 continue;
615
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000616 if (it->isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000617 continue;
618
619 uint64_t &Entry = StringIndexMap[Symbol.getName()];
620 if (!Entry) {
621 Entry = StringTable.size();
622 StringTable += Symbol.getName();
623 StringTable += '\x00';
624 }
625
626 MachSymbolData MSD;
627 MSD.SymbolData = it;
628 MSD.StringIndex = Entry;
629
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000630 if (Symbol.isAbsolute()) {
631 MSD.SectionIndex = 0;
632 LocalSymbolData.push_back(MSD);
633 } else {
634 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
635 assert(MSD.SectionIndex && "Invalid section index!");
636 LocalSymbolData.push_back(MSD);
637 }
638 }
639
640 // External and undefined symbols are required to be in lexicographic order.
641 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
642 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
643
Daniel Dunbarbe963552009-08-26 13:57:54 +0000644 // Set the symbol indices.
645 Index = 0;
646 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
647 LocalSymbolData[i].SymbolData->setIndex(Index++);
648 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
649 ExternalSymbolData[i].SymbolData->setIndex(Index++);
650 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
651 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
652
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000653 // The string table is padded to a multiple of 4.
654 //
655 // FIXME: Check to see if this varies per arch.
656 while (StringTable.size() % 4)
657 StringTable += '\x00';
658 }
659
660 void WriteObject(MCAssembler &Asm) {
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000661 unsigned NumSections = Asm.size();
662
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000663 // Compute the symbol -> symbol data map.
664 //
665 // FIXME: This should not be here.
Daniel Dunbarbe963552009-08-26 13:57:54 +0000666 DenseMap<const MCSymbol*, MCSymbolData *> SymbolMap;
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000667 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
668 ie = Asm.symbol_end(); it != ie; ++it)
669 SymbolMap[&it->getSymbol()] = it;
670
671 // Create symbol data for any indirect symbols.
672 BindIndirectSymbols(Asm, SymbolMap);
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000673
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000674 // Compute symbol table information.
675 SmallString<256> StringTable;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000676 std::vector<MachSymbolData> LocalSymbolData;
677 std::vector<MachSymbolData> ExternalSymbolData;
678 std::vector<MachSymbolData> UndefinedSymbolData;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000679 unsigned NumSymbols = Asm.symbol_size();
680
681 // No symbol table command is written if there are no symbols.
682 if (NumSymbols)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000683 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
684 UndefinedSymbolData);
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000685
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000686 // The section data starts after the header, the segment load command (and
687 // section headers) and the symbol table.
688 unsigned NumLoadCommands = 1;
689 uint64_t LoadCommandsSize =
690 SegmentLoadCommand32Size + NumSections * Section32Size;
691
692 // Add the symbol table load command sizes, if used.
693 if (NumSymbols) {
694 NumLoadCommands += 2;
695 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
696 }
697
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000698 // Compute the total size of the section data, as well as its file size and
699 // vm size.
Daniel Dunbar6742e342009-08-26 04:13:32 +0000700 uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000701 uint64_t SectionDataSize = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000702 uint64_t SectionDataFileSize = 0;
703 uint64_t VMSize = 0;
704 for (MCAssembler::iterator it = Asm.begin(),
705 ie = Asm.end(); it != ie; ++it) {
706 MCSectionData &SD = *it;
707
708 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
709
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000710 if (isVirtualSection(SD.getSection()))
711 continue;
712
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000713 SectionDataSize = std::max(SectionDataSize,
714 SD.getAddress() + SD.getSize());
715 SectionDataFileSize = std::max(SectionDataFileSize,
716 SD.getAddress() + SD.getFileSize());
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000717 }
718
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000719 // The section data is passed to 4 bytes.
720 //
721 // FIXME: Is this machine dependent?
722 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
723 SectionDataFileSize += SectionDataPadding;
724
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000725 // Write the prolog, starting with the header and load command...
Daniel Dunbar6009db42009-08-26 21:22:22 +0000726 WriteHeader32(NumLoadCommands, LoadCommandsSize,
727 Asm.getSubsectionsViaSymbols());
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000728 WriteSegmentLoadCommand32(NumSections, VMSize,
729 SectionDataStart, SectionDataSize);
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000730
731 // ... and then the section headers.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000732 //
733 // We also compute the section relocations while we do this. Note that
734 // compute relocation info will also update the fixup to have the correct
735 // value; this will be overwrite the appropriate data in the fragment when
736 // it is written.
737 std::vector<MachRelocationEntry> RelocInfos;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000738 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000739 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie;
740 ++it) {
741 MCSectionData &SD = *it;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000742
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000743 // The assembler writes relocations in the reverse order they were seen.
744 //
745 // FIXME: It is probably more complicated than this.
746 unsigned NumRelocsStart = RelocInfos.size();
747 for (unsigned i = 0, e = SD.fixup_size(); i != e; ++i)
748 ComputeRelocationInfo(Asm, SD.getFixups()[e - i - 1], SymbolMap,
749 RelocInfos);
750
751 unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
752 uint64_t SectionStart = SectionDataStart + SD.getAddress();
753 WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
754 RelocTableEnd += NumRelocs * RelocationInfoSize;
755 }
756
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000757 // Write the symbol table load command, if used.
758 if (NumSymbols) {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000759 unsigned FirstLocalSymbol = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000760 unsigned NumLocalSymbols = LocalSymbolData.size();
761 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
762 unsigned NumExternalSymbols = ExternalSymbolData.size();
763 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
764 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000765 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
766 unsigned NumSymTabSymbols =
767 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
768 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
769 uint64_t IndirectSymbolOffset = 0;
770
771 // If used, the indirect symbols are written after the section data.
772 if (NumIndirectSymbols)
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000773 IndirectSymbolOffset = RelocTableEnd;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000774
775 // The symbol table is written after the indirect symbol data.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000776 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000777
778 // The string table is written after symbol table.
779 uint64_t StringTableOffset =
780 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
781 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
782 StringTableOffset, StringTable.size());
783
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000784 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
785 FirstExternalSymbol, NumExternalSymbols,
786 FirstUndefinedSymbol, NumUndefinedSymbols,
787 IndirectSymbolOffset, NumIndirectSymbols);
788 }
789
790 // Write the actual section data.
791 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
792 WriteFileData(OS, *it, *this);
793
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000794 // Write the extra padding.
795 WriteZeros(SectionDataPadding);
796
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000797 // Write the relocation entries.
798 for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
799 Write32(RelocInfos[i].Word0);
800 Write32(RelocInfos[i].Word1);
801 }
802
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000803 // Write the symbol table data, if used.
804 if (NumSymbols) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000805 // Write the indirect symbol entries.
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000806 for (MCAssembler::indirect_symbol_iterator
807 it = Asm.indirect_symbol_begin(),
808 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
809 // Indirect symbols in the non lazy symbol pointer section have some
810 // special handling.
811 const MCSectionMachO &Section =
812 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
813 unsigned Type =
814 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
815 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
816 // If this symbol is defined and internal, mark it as such.
817 if (it->Symbol->isDefined() &&
818 !SymbolMap.lookup(it->Symbol)->isExternal()) {
819 uint32_t Flags = ISF_Local;
820 if (it->Symbol->isAbsolute())
821 Flags |= ISF_Absolute;
822 Write32(Flags);
823 continue;
824 }
825 }
826
Daniel Dunbarbe963552009-08-26 13:57:54 +0000827 Write32(SymbolMap[it->Symbol]->getIndex());
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000828 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000829
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000830 // FIXME: Check that offsets match computed ones.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000831
832 // Write the symbol table entries.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000833 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
834 WriteNlist32(LocalSymbolData[i]);
835 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
836 WriteNlist32(ExternalSymbolData[i]);
837 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
838 WriteNlist32(UndefinedSymbolData[i]);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000839
840 // Write the string table.
841 OS << StringTable.str();
842 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000843 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000844};
845
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000846/* *** */
847
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000848MCFragment::MCFragment() : Kind(FragmentType(~0)) {
849}
850
Daniel Dunbar5e835962009-08-26 02:48:04 +0000851MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000852 : Kind(_Kind),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000853 Parent(_Parent),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000854 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000855{
Daniel Dunbar5e835962009-08-26 02:48:04 +0000856 if (Parent)
857 Parent->getFragmentList().push_back(this);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000858}
859
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000860MCFragment::~MCFragment() {
861}
862
Daniel Dunbar5e835962009-08-26 02:48:04 +0000863uint64_t MCFragment::getAddress() const {
864 assert(getParent() && "Missing Section!");
865 return getParent()->getAddress() + Offset;
866}
867
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000868/* *** */
869
Daniel Dunbar81e40002009-08-27 00:38:04 +0000870MCSectionData::MCSectionData() : Section(0) {}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000871
872MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
Daniel Dunbar81e40002009-08-27 00:38:04 +0000873 : Section(&_Section),
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000874 Alignment(1),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000875 Address(~UINT64_C(0)),
Daniel Dunbar6742e342009-08-26 04:13:32 +0000876 Size(~UINT64_C(0)),
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000877 FileSize(~UINT64_C(0)),
878 LastFixupLookup(~0)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000879{
880 if (A)
881 A->getSectionList().push_back(this);
882}
883
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000884const MCSectionData::Fixup *
885MCSectionData::LookupFixup(const MCFragment *Fragment, uint64_t Offset) const {
886 // Use a one level cache to turn the common case of accessing the fixups in
887 // order into O(1) instead of O(N).
888 unsigned i = LastFixupLookup, Count = Fixups.size(), End = Fixups.size();
889 if (i >= End)
890 i = 0;
891 while (Count--) {
892 const Fixup &F = Fixups[i];
893 if (F.Fragment == Fragment && F.Offset == Offset) {
894 LastFixupLookup = i;
895 return &F;
896 }
897
898 ++i;
899 if (i == End)
900 i = 0;
901 }
902
903 return 0;
904}
905
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000906/* *** */
907
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000908MCSymbolData::MCSymbolData() : Symbol(*(MCSymbol*)0) {}
909
910MCSymbolData::MCSymbolData(MCSymbol &_Symbol, MCFragment *_Fragment,
911 uint64_t _Offset, MCAssembler *A)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000912 : Symbol(_Symbol), Fragment(_Fragment), Offset(_Offset),
Daniel Dunbarbe963552009-08-26 13:57:54 +0000913 IsExternal(false), IsPrivateExtern(false), Flags(0), Index(0)
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000914{
915 if (A)
916 A->getSymbolList().push_back(this);
917}
918
919/* *** */
920
Daniel Dunbar6009db42009-08-26 21:22:22 +0000921MCAssembler::MCAssembler(raw_ostream &_OS)
922 : OS(_OS),
923 SubsectionsViaSymbols(false)
924{
925}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000926
927MCAssembler::~MCAssembler() {
928}
929
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000930void MCAssembler::LayoutSection(MCSectionData &SD) {
Daniel Dunbar6742e342009-08-26 04:13:32 +0000931 uint64_t Address = SD.getAddress();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000932
933 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
934 MCFragment &F = *it;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000935
Daniel Dunbar6742e342009-08-26 04:13:32 +0000936 F.setOffset(Address - SD.getAddress());
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000937
938 // Evaluate fragment size.
939 switch (F.getKind()) {
940 case MCFragment::FT_Align: {
941 MCAlignFragment &AF = cast<MCAlignFragment>(F);
942
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000943 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
Daniel Dunbar6742e342009-08-26 04:13:32 +0000944 if (Size > AF.getMaxBytesToEmit())
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000945 AF.setFileSize(0);
946 else
Daniel Dunbar6742e342009-08-26 04:13:32 +0000947 AF.setFileSize(Size);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000948 break;
949 }
950
951 case MCFragment::FT_Data:
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000952 F.setFileSize(F.getMaxFileSize());
953 break;
954
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000955 case MCFragment::FT_Fill: {
956 MCFillFragment &FF = cast<MCFillFragment>(F);
957
958 F.setFileSize(F.getMaxFileSize());
959
960 // If the fill value is constant, thats it.
961 if (FF.getValue().isAbsolute())
962 break;
963
964 // Otherwise, add fixups for the values.
965 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
966 MCSectionData::Fixup Fix(F, i * FF.getValueSize(),
967 FF.getValue(),FF.getValueSize());
968 SD.getFixups().push_back(Fix);
969 }
970 break;
971 }
972
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000973 case MCFragment::FT_Org: {
974 MCOrgFragment &OF = cast<MCOrgFragment>(F);
975
976 if (!OF.getOffset().isAbsolute())
977 llvm_unreachable("FIXME: Not yet implemented!");
978 uint64_t OrgOffset = OF.getOffset().getConstant();
Daniel Dunbar6742e342009-08-26 04:13:32 +0000979 uint64_t Offset = Address - SD.getAddress();
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000980
981 // FIXME: We need a way to communicate this error.
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000982 if (OrgOffset < Offset)
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000983 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
Daniel Dunbar6742e342009-08-26 04:13:32 +0000984 "' (at offset '" + Twine(Offset) + "'");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000985
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000986 F.setFileSize(OrgOffset - Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000987 break;
988 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000989
990 case MCFragment::FT_ZeroFill: {
991 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
992
993 // Align the fragment offset; it is safe to adjust the offset freely since
994 // this is only in virtual sections.
995 uint64_t Aligned = RoundUpToAlignment(Address, ZFF.getAlignment());
996 F.setOffset(Aligned - SD.getAddress());
997
998 // FIXME: This is misnamed.
999 F.setFileSize(ZFF.getSize());
1000 break;
1001 }
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001002 }
1003
Daniel Dunbar6742e342009-08-26 04:13:32 +00001004 Address += F.getFileSize();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001005 }
1006
Daniel Dunbar6742e342009-08-26 04:13:32 +00001007 // Set the section sizes.
1008 SD.setSize(Address - SD.getAddress());
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001009 if (isVirtualSection(SD.getSection()))
1010 SD.setFileSize(0);
1011 else
1012 SD.setFileSize(Address - SD.getAddress());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001013}
1014
1015/// WriteFileData - Write the \arg F data to the output file.
1016static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1017 MachObjectWriter &MOW) {
1018 uint64_t Start = OS.tell();
1019 (void) Start;
1020
Daniel Dunbar0adcd352009-08-25 21:10:45 +00001021 ++EmittedFragments;
1022
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001023 // FIXME: Embed in fragments instead?
1024 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001025 case MCFragment::FT_Align: {
1026 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1027 uint64_t Count = AF.getFileSize() / AF.getValueSize();
1028
1029 // FIXME: This error shouldn't actually occur (the front end should emit
1030 // multiple .align directives to enforce the semantics it wants), but is
1031 // severe enough that we want to report it. How to handle this?
1032 if (Count * AF.getValueSize() != AF.getFileSize())
1033 llvm_report_error("undefined .align directive, value size '" +
1034 Twine(AF.getValueSize()) +
1035 "' is not a divisor of padding size '" +
1036 Twine(AF.getFileSize()) + "'");
1037
1038 for (uint64_t i = 0; i != Count; ++i) {
1039 switch (AF.getValueSize()) {
1040 default:
1041 assert(0 && "Invalid size!");
1042 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1043 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1044 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1045 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1046 }
1047 }
1048 break;
1049 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001050
1051 case MCFragment::FT_Data:
1052 OS << cast<MCDataFragment>(F).getContents().str();
1053 break;
1054
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001055 case MCFragment::FT_Fill: {
1056 MCFillFragment &FF = cast<MCFillFragment>(F);
1057
Daniel Dunbar3f6a9602009-08-26 13:58:10 +00001058 int64_t Value = 0;
Daniel Dunbar6c31b052009-08-28 05:48:10 +00001059 if (FF.getValue().isAbsolute())
Daniel Dunbar3f6a9602009-08-26 13:58:10 +00001060 Value = FF.getValue().getConstant();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001061 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
Daniel Dunbar3f6a9602009-08-26 13:58:10 +00001062 if (!FF.getValue().isAbsolute()) {
1063 // Find the fixup.
1064 //
1065 // FIXME: Find a better way to write in the fixes.
1066 const MCSectionData::Fixup *Fixup =
1067 F.getParent()->LookupFixup(&F, i * FF.getValueSize());
1068 assert(Fixup && "Missing fixup for fill value!");
1069 Value = Fixup->FixedValue;
1070 }
1071
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001072 switch (FF.getValueSize()) {
1073 default:
1074 assert(0 && "Invalid size!");
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001075 case 1: MOW.Write8 (uint8_t (Value)); break;
1076 case 2: MOW.Write16(uint16_t(Value)); break;
1077 case 4: MOW.Write32(uint32_t(Value)); break;
1078 case 8: MOW.Write64(uint64_t(Value)); break;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001079 }
1080 }
1081 break;
1082 }
1083
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001084 case MCFragment::FT_Org: {
1085 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1086
1087 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1088 MOW.Write8(uint8_t(OF.getValue()));
1089
1090 break;
1091 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001092
1093 case MCFragment::FT_ZeroFill: {
1094 assert(0 && "Invalid zero fill fragment in concrete section!");
1095 break;
1096 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001097 }
1098
1099 assert(OS.tell() - Start == F.getFileSize());
1100}
1101
1102/// WriteFileData - Write the \arg SD data to the output file.
1103static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1104 MachObjectWriter &MOW) {
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001105 // Ignore virtual sections.
1106 if (isVirtualSection(SD.getSection())) {
1107 assert(SD.getFileSize() == 0);
1108 return;
1109 }
1110
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001111 uint64_t Start = OS.tell();
1112 (void) Start;
1113
1114 for (MCSectionData::const_iterator it = SD.begin(),
1115 ie = SD.end(); it != ie; ++it)
1116 WriteFileData(OS, *it, MOW);
1117
Daniel Dunbar6742e342009-08-26 04:13:32 +00001118 // Add section padding.
1119 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1120 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1121
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001122 assert(OS.tell() - Start == SD.getFileSize());
1123}
1124
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001125void MCAssembler::Finish() {
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001126 // Layout the concrete sections and fragments.
Daniel Dunbar5e835962009-08-26 02:48:04 +00001127 uint64_t Address = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001128 MCSectionData *Prev = 0;
1129 for (iterator it = begin(), ie = end(); it != ie; ++it) {
Daniel Dunbar6742e342009-08-26 04:13:32 +00001130 MCSectionData &SD = *it;
1131
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001132 // Skip virtual sections.
1133 if (isVirtualSection(SD.getSection()))
1134 continue;
1135
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001136 // Align this section if necessary by adding padding bytes to the previous
1137 // section.
1138 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1139 assert(Prev && "Missing prev section!");
1140 Prev->setFileSize(Prev->getFileSize() + Pad);
1141 Address += Pad;
1142 }
Daniel Dunbar6742e342009-08-26 04:13:32 +00001143
1144 // Layout the section fragments and its size.
1145 SD.setAddress(Address);
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001146 LayoutSection(SD);
Daniel Dunbar6742e342009-08-26 04:13:32 +00001147 Address += SD.getFileSize();
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001148
1149 Prev = &SD;
Daniel Dunbar5e835962009-08-26 02:48:04 +00001150 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001151
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001152 // Layout the virtual sections.
1153 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1154 MCSectionData &SD = *it;
1155
1156 if (!isVirtualSection(SD.getSection()))
1157 continue;
1158
1159 SD.setAddress(Address);
1160 LayoutSection(SD);
1161 Address += SD.getSize();
1162 }
1163
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +00001164 // Write the object file.
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001165 MachObjectWriter MOW(OS);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +00001166 MOW.WriteObject(*this);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001167
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001168 OS.flush();
1169}