blob: 1375b779580692ec8ac362c3597eb9b66a19b3ea [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 Dunbar3f6a9602009-08-26 13:58:10 +000045 static const unsigned RelocationInfoSize = 8;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000046
47 enum HeaderFileType {
48 HFT_Object = 0x1
49 };
50
Daniel Dunbar6009db42009-08-26 21:22:22 +000051 enum HeaderFlags {
52 HF_SubsectionsViaSymbols = 0x2000
53 };
54
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000055 enum LoadCommandType {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000056 LCT_Segment = 0x1,
57 LCT_Symtab = 0x2,
58 LCT_Dysymtab = 0xb
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000059 };
60
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +000061 // See <mach-o/nlist.h>.
62 enum SymbolTypeType {
63 STT_Undefined = 0x00,
64 STT_Absolute = 0x02,
65 STT_Section = 0x0e
66 };
67
68 enum SymbolTypeFlags {
69 // If any of these bits are set, then the entry is a stab entry number (see
70 // <mach-o/stab.h>. Otherwise the other masks apply.
71 STF_StabsEntryMask = 0xe0,
72
73 STF_TypeMask = 0x0e,
74 STF_External = 0x01,
75 STF_PrivateExtern = 0x10
76 };
77
Daniel Dunbarad7c3d52009-08-26 00:18:21 +000078 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
79 /// symbol entry.
80 enum IndirectSymbolFlags {
81 ISF_Local = 0x80000000,
82 ISF_Absolute = 0x40000000
83 };
84
Daniel Dunbar3f6a9602009-08-26 13:58:10 +000085 /// RelocationFlags - Special flags for addresses.
86 enum RelocationFlags {
87 RF_Scattered = 0x80000000
88 };
89
90 enum RelocationInfoType {
91 RIT_Vanilla = 0,
92 RIT_Pair = 1,
93 RIT_Difference = 2,
94 RIT_PreboundLazyPointer = 3,
95 RIT_LocalDifference = 4
96 };
97
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +000098 /// MachSymbolData - Helper struct for containing some precomputed information
99 /// on symbols.
100 struct MachSymbolData {
101 MCSymbolData *SymbolData;
102 uint64_t StringIndex;
103 uint8_t SectionIndex;
104
105 // Support lexicographic sorting.
106 bool operator<(const MachSymbolData &RHS) const {
107 const std::string &Name = SymbolData->getSymbol().getName();
108 return Name < RHS.SymbolData->getSymbol().getName();
109 }
110 };
111
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000112 raw_ostream &OS;
113 bool IsLSB;
114
115public:
116 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
117 : OS(_OS), IsLSB(_IsLSB) {
118 }
119
120 /// @name Helper Methods
121 /// @{
122
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000123 void Write8(uint8_t Value) {
124 OS << char(Value);
125 }
126
127 void Write16(uint16_t Value) {
128 if (IsLSB) {
129 Write8(uint8_t(Value >> 0));
130 Write8(uint8_t(Value >> 8));
131 } else {
132 Write8(uint8_t(Value >> 8));
133 Write8(uint8_t(Value >> 0));
134 }
135 }
136
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000137 void Write32(uint32_t Value) {
138 if (IsLSB) {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000139 Write16(uint16_t(Value >> 0));
140 Write16(uint16_t(Value >> 16));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000141 } else {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000142 Write16(uint16_t(Value >> 16));
143 Write16(uint16_t(Value >> 0));
144 }
145 }
146
147 void Write64(uint64_t Value) {
148 if (IsLSB) {
149 Write32(uint32_t(Value >> 0));
150 Write32(uint32_t(Value >> 32));
151 } else {
152 Write32(uint32_t(Value >> 32));
153 Write32(uint32_t(Value >> 0));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000154 }
155 }
156
157 void WriteZeros(unsigned N) {
158 const char Zeros[16] = { 0 };
159
160 for (unsigned i = 0, e = N / 16; i != e; ++i)
161 OS << StringRef(Zeros, 16);
162
163 OS << StringRef(Zeros, N % 16);
164 }
165
166 void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
167 OS << Str;
168 if (ZeroFillSize)
169 WriteZeros(ZeroFillSize - Str.size());
170 }
171
172 /// @}
173
Daniel Dunbar6009db42009-08-26 21:22:22 +0000174 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
175 bool SubsectionsViaSymbols) {
176 uint32_t Flags = 0;
177
178 if (SubsectionsViaSymbols)
179 Flags |= HF_SubsectionsViaSymbols;
180
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000181 // struct mach_header (28 bytes)
182
183 uint64_t Start = OS.tell();
184 (void) Start;
185
186 Write32(Header_Magic32);
187
188 // FIXME: Support cputype.
189 Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000190 // FIXME: Support cpusubtype.
191 Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000192 Write32(HFT_Object);
Daniel Dunbar6009db42009-08-26 21:22:22 +0000193 Write32(NumLoadCommands); // Object files have a single load command, the
194 // segment.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000195 Write32(LoadCommandsSize);
Daniel Dunbar6009db42009-08-26 21:22:22 +0000196 Write32(Flags);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000197
198 assert(OS.tell() - Start == Header32Size);
199 }
200
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000201 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
202 ///
203 /// \arg NumSections - The number of sections in this segment.
204 /// \arg SectionDataSize - The total size of the sections.
205 void WriteSegmentLoadCommand32(unsigned NumSections,
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000206 uint64_t VMSize,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000207 uint64_t SectionDataStartOffset,
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000208 uint64_t SectionDataSize) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000209 // struct segment_command (56 bytes)
210
211 uint64_t Start = OS.tell();
212 (void) Start;
213
214 Write32(LCT_Segment);
215 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
216
217 WriteString("", 16);
218 Write32(0); // vmaddr
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000219 Write32(VMSize); // vmsize
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000220 Write32(SectionDataStartOffset); // file offset
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000221 Write32(SectionDataSize); // file size
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000222 Write32(0x7); // maxprot
223 Write32(0x7); // initprot
224 Write32(NumSections);
225 Write32(0); // flags
226
227 assert(OS.tell() - Start == SegmentLoadCommand32Size);
228 }
229
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000230 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
231 uint64_t RelocationsStart, unsigned NumRelocations) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000232 // struct section (68 bytes)
233
234 uint64_t Start = OS.tell();
235 (void) Start;
236
237 // FIXME: cast<> support!
238 const MCSectionMachO &Section =
239 static_cast<const MCSectionMachO&>(SD.getSection());
240 WriteString(Section.getSectionName(), 16);
241 WriteString(Section.getSegmentName(), 16);
Daniel Dunbar5e835962009-08-26 02:48:04 +0000242 Write32(SD.getAddress()); // address
Daniel Dunbar6742e342009-08-26 04:13:32 +0000243 Write32(SD.getSize()); // size
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000244 Write32(FileOffset);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000245
246 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
247 Write32(Log2_32(SD.getAlignment()));
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000248 Write32(NumRelocations ? RelocationsStart : 0);
249 Write32(NumRelocations);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000250 Write32(Section.getTypeAndAttributes());
251 Write32(0); // reserved1
252 Write32(Section.getStubSize()); // reserved2
253
254 assert(OS.tell() - Start == Section32Size);
255 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000256
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000257 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
258 uint32_t StringTableOffset,
259 uint32_t StringTableSize) {
260 // struct symtab_command (24 bytes)
261
262 uint64_t Start = OS.tell();
263 (void) Start;
264
265 Write32(LCT_Symtab);
266 Write32(SymtabLoadCommandSize);
267 Write32(SymbolOffset);
268 Write32(NumSymbols);
269 Write32(StringTableOffset);
270 Write32(StringTableSize);
271
272 assert(OS.tell() - Start == SymtabLoadCommandSize);
273 }
274
275 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
276 uint32_t NumLocalSymbols,
277 uint32_t FirstExternalSymbol,
278 uint32_t NumExternalSymbols,
279 uint32_t FirstUndefinedSymbol,
280 uint32_t NumUndefinedSymbols,
281 uint32_t IndirectSymbolOffset,
282 uint32_t NumIndirectSymbols) {
283 // struct dysymtab_command (80 bytes)
284
285 uint64_t Start = OS.tell();
286 (void) Start;
287
288 Write32(LCT_Dysymtab);
289 Write32(DysymtabLoadCommandSize);
290 Write32(FirstLocalSymbol);
291 Write32(NumLocalSymbols);
292 Write32(FirstExternalSymbol);
293 Write32(NumExternalSymbols);
294 Write32(FirstUndefinedSymbol);
295 Write32(NumUndefinedSymbols);
296 Write32(0); // tocoff
297 Write32(0); // ntoc
298 Write32(0); // modtaboff
299 Write32(0); // nmodtab
300 Write32(0); // extrefsymoff
301 Write32(0); // nextrefsyms
302 Write32(IndirectSymbolOffset);
303 Write32(NumIndirectSymbols);
304 Write32(0); // extreloff
305 Write32(0); // nextrel
306 Write32(0); // locreloff
307 Write32(0); // nlocrel
308
309 assert(OS.tell() - Start == DysymtabLoadCommandSize);
310 }
311
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000312 void WriteNlist32(MachSymbolData &MSD) {
Daniel Dunbar5e835962009-08-26 02:48:04 +0000313 MCSymbolData &Data = *MSD.SymbolData;
314 MCSymbol &Symbol = Data.getSymbol();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000315 uint8_t Type = 0;
316
317 // Set the N_TYPE bits. See <mach-o/nlist.h>.
318 //
319 // FIXME: Are the prebound or indirect fields possible here?
320 if (Symbol.isUndefined())
321 Type = STT_Undefined;
322 else if (Symbol.isAbsolute())
323 Type = STT_Absolute;
324 else
325 Type = STT_Section;
326
327 // FIXME: Set STAB bits.
328
Daniel Dunbar5e835962009-08-26 02:48:04 +0000329 if (Data.isPrivateExtern())
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000330 Type |= STF_PrivateExtern;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000331
332 // Set external bit.
Daniel Dunbar5e835962009-08-26 02:48:04 +0000333 if (Data.isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000334 Type |= STF_External;
335
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000336 // struct nlist (12 bytes)
337
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000338 Write32(MSD.StringIndex);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000339 Write8(Type);
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000340 Write8(MSD.SectionIndex);
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000341
342 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
343 // value.
Daniel Dunbar5e835962009-08-26 02:48:04 +0000344 Write16(Data.getFlags() & 0xFFFF);
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000345
Daniel Dunbar5e835962009-08-26 02:48:04 +0000346 // Write the symbol address.
347 uint32_t Address = 0;
348 if (Symbol.isDefined()) {
349 if (Symbol.isAbsolute()) {
350 llvm_unreachable("FIXME: Not yet implemented!");
351 } else {
352 Address = Data.getFragment()->getAddress() + Data.getOffset();
353 }
354 }
355 Write32(Address);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000356 }
357
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000358 struct MachRelocationEntry {
359 uint32_t Word0;
360 uint32_t Word1;
361 };
362 void ComputeScatteredRelocationInfo(MCAssembler &Asm,
363 MCSectionData::Fixup &Fixup,
364 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
365 std::vector<MachRelocationEntry> &Relocs) {
366 uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
367 unsigned IsPCRel = 0;
368 unsigned Type = RIT_Vanilla;
369
370 // See <reloc.h>.
371
372 const MCSymbol *A = Fixup.Value.getSymA();
373 MCSymbolData *SD = SymbolMap.lookup(A);
374 uint32_t Value = SD->getFragment()->getAddress() + SD->getOffset();
375 uint32_t Value2 = 0;
376
377 if (const MCSymbol *B = Fixup.Value.getSymB()) {
378 Type = RIT_LocalDifference;
379
380 MCSymbolData *SD = SymbolMap.lookup(B);
381 Value2 = SD->getFragment()->getAddress() + SD->getOffset();
382 }
383
384 unsigned Log2Size = Log2_32(Fixup.Size);
385 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
386
387 // The value which goes in the fixup is current value of the expression.
388 Fixup.FixedValue = Value - Value2 + Fixup.Value.getConstant();
389
390 MachRelocationEntry MRE;
391 MRE.Word0 = ((Address << 0) |
392 (Type << 24) |
393 (Log2Size << 28) |
394 (IsPCRel << 30) |
395 RF_Scattered);
396 MRE.Word1 = Value;
397 Relocs.push_back(MRE);
398
399 if (Type == RIT_LocalDifference) {
400 Type = RIT_Pair;
401
402 MachRelocationEntry MRE;
403 MRE.Word0 = ((0 << 0) |
404 (Type << 24) |
405 (Log2Size << 28) |
406 (0 << 30) |
407 RF_Scattered);
408 MRE.Word1 = Value2;
409 Relocs.push_back(MRE);
410 }
411 }
412
413 void ComputeRelocationInfo(MCAssembler &Asm,
414 MCSectionData::Fixup &Fixup,
415 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
416 std::vector<MachRelocationEntry> &Relocs) {
417 // If this is a local symbol plus an offset or a difference, then we need a
418 // scattered relocation entry.
419 if (Fixup.Value.getSymB()) // a - b
420 return ComputeScatteredRelocationInfo(Asm, Fixup, SymbolMap, Relocs);
421 if (Fixup.Value.getSymA() && Fixup.Value.getConstant())
422 if (!Fixup.Value.getSymA()->isUndefined())
423 return ComputeScatteredRelocationInfo(Asm, Fixup, SymbolMap, Relocs);
424
425 // See <reloc.h>.
426 uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
427 uint32_t Value = 0;
428 unsigned Index = 0;
429 unsigned IsPCRel = 0;
430 unsigned IsExtern = 0;
431 unsigned Type = 0;
432
433 if (Fixup.Value.isAbsolute()) { // constant
434 // SymbolNum of 0 indicates the absolute section.
435 Type = RIT_Vanilla;
436 Value = 0;
437 llvm_unreachable("FIXME: Not yet implemented!");
438 } else {
439 const MCSymbol *Symbol = Fixup.Value.getSymA();
440 MCSymbolData *SD = SymbolMap.lookup(Symbol);
441
442 if (Symbol->isUndefined()) {
443 IsExtern = 1;
444 Index = SD->getIndex();
445 Value = 0;
446 } else {
447 // The index is the section ordinal.
448 //
449 // FIXME: O(N)
450 Index = 1;
451 for (MCAssembler::iterator it = Asm.begin(),
452 ie = Asm.end(); it != ie; ++it, ++Index)
453 if (&*it == SD->getFragment()->getParent())
454 break;
455 Value = SD->getFragment()->getAddress() + SD->getOffset();
456 }
457
458 Type = RIT_Vanilla;
459 }
460
461 // The value which goes in the fixup is current value of the expression.
462 Fixup.FixedValue = Value + Fixup.Value.getConstant();
463
464 unsigned Log2Size = Log2_32(Fixup.Size);
465 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
466
467 // struct relocation_info (8 bytes)
468 MachRelocationEntry MRE;
469 MRE.Word0 = Address;
470 MRE.Word1 = ((Index << 0) |
471 (IsPCRel << 24) |
472 (Log2Size << 25) |
473 (IsExtern << 27) |
474 (Type << 28));
475 Relocs.push_back(MRE);
476 }
477
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000478 void BindIndirectSymbols(MCAssembler &Asm,
Daniel Dunbarbe963552009-08-26 13:57:54 +0000479 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000480 // This is the point where 'as' creates actual symbols for indirect symbols
481 // (in the following two passes). It would be easier for us to do this
482 // sooner when we see the attribute, but that makes getting the order in the
483 // symbol table much more complicated than it is worth.
484 //
485 // FIXME: Revisit this when the dust settles.
486
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000487 // Bind non lazy symbol pointers first.
488 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
489 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
490 // FIXME: cast<> support!
491 const MCSectionMachO &Section =
492 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
493
494 unsigned Type =
495 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
496 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
497 continue;
498
499 MCSymbolData *&Entry = SymbolMap[it->Symbol];
500 if (!Entry)
501 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
502 }
503
504 // Then lazy symbol pointers and symbol stubs.
505 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
506 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
507 // FIXME: cast<> support!
508 const MCSectionMachO &Section =
509 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
510
511 unsigned Type =
512 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
513 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
514 Type != MCSectionMachO::S_SYMBOL_STUBS)
515 continue;
516
517 MCSymbolData *&Entry = SymbolMap[it->Symbol];
518 if (!Entry) {
519 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
520
521 // Set the symbol type to undefined lazy, but only on construction.
522 //
523 // FIXME: Do not hardcode.
524 Entry->setFlags(Entry->getFlags() | 0x0001);
525 }
526 }
527 }
528
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000529 /// ComputeSymbolTable - Compute the symbol table data
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000530 ///
531 /// \param StringTable [out] - The string table data.
532 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
533 /// string table.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000534 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
535 std::vector<MachSymbolData> &LocalSymbolData,
536 std::vector<MachSymbolData> &ExternalSymbolData,
537 std::vector<MachSymbolData> &UndefinedSymbolData) {
538 // Build section lookup table.
539 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
540 unsigned Index = 1;
541 for (MCAssembler::iterator it = Asm.begin(),
542 ie = Asm.end(); it != ie; ++it, ++Index)
543 SectionIndexMap[&it->getSection()] = Index;
544 assert(Index <= 256 && "Too many sections!");
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000545
546 // Index 0 is always the empty string.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000547 StringMap<uint64_t> StringIndexMap;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000548 StringTable += '\x00';
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000549
550 // Build the symbol arrays and the string table, but only for non-local
551 // symbols.
552 //
553 // The particular order that we collect the symbols and create the string
554 // table, then sort the symbols is chosen to match 'as'. Even though it
555 // doesn't matter for correctness, this is important for letting us diff .o
556 // files.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000557 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
558 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000559 MCSymbol &Symbol = it->getSymbol();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000560
Daniel Dunbar959fd882009-08-26 22:13:22 +0000561 // Ignore assembler temporaries.
562 if (it->getSymbol().isTemporary())
563 continue;
564
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000565 if (!it->isExternal() && !Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000566 continue;
567
568 uint64_t &Entry = StringIndexMap[Symbol.getName()];
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000569 if (!Entry) {
570 Entry = StringTable.size();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000571 StringTable += Symbol.getName();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000572 StringTable += '\x00';
573 }
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000574
575 MachSymbolData MSD;
576 MSD.SymbolData = it;
577 MSD.StringIndex = Entry;
578
579 if (Symbol.isUndefined()) {
580 MSD.SectionIndex = 0;
581 UndefinedSymbolData.push_back(MSD);
582 } else if (Symbol.isAbsolute()) {
583 MSD.SectionIndex = 0;
584 ExternalSymbolData.push_back(MSD);
585 } else {
586 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
587 assert(MSD.SectionIndex && "Invalid section index!");
588 ExternalSymbolData.push_back(MSD);
589 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000590 }
591
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000592 // Now add the data for local symbols.
593 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
594 ie = Asm.symbol_end(); it != ie; ++it) {
595 MCSymbol &Symbol = it->getSymbol();
596
Daniel Dunbar959fd882009-08-26 22:13:22 +0000597 // Ignore assembler temporaries.
598 if (it->getSymbol().isTemporary())
599 continue;
600
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000601 if (it->isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000602 continue;
603
604 uint64_t &Entry = StringIndexMap[Symbol.getName()];
605 if (!Entry) {
606 Entry = StringTable.size();
607 StringTable += Symbol.getName();
608 StringTable += '\x00';
609 }
610
611 MachSymbolData MSD;
612 MSD.SymbolData = it;
613 MSD.StringIndex = Entry;
614
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000615 if (Symbol.isAbsolute()) {
616 MSD.SectionIndex = 0;
617 LocalSymbolData.push_back(MSD);
618 } else {
619 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
620 assert(MSD.SectionIndex && "Invalid section index!");
621 LocalSymbolData.push_back(MSD);
622 }
623 }
624
625 // External and undefined symbols are required to be in lexicographic order.
626 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
627 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
628
Daniel Dunbarbe963552009-08-26 13:57:54 +0000629 // Set the symbol indices.
630 Index = 0;
631 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
632 LocalSymbolData[i].SymbolData->setIndex(Index++);
633 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
634 ExternalSymbolData[i].SymbolData->setIndex(Index++);
635 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
636 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
637
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000638 // The string table is padded to a multiple of 4.
639 //
640 // FIXME: Check to see if this varies per arch.
641 while (StringTable.size() % 4)
642 StringTable += '\x00';
643 }
644
645 void WriteObject(MCAssembler &Asm) {
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000646 unsigned NumSections = Asm.size();
647
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000648 // Compute the symbol -> symbol data map.
649 //
650 // FIXME: This should not be here.
Daniel Dunbarbe963552009-08-26 13:57:54 +0000651 DenseMap<const MCSymbol*, MCSymbolData *> SymbolMap;
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000652 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
653 ie = Asm.symbol_end(); it != ie; ++it)
654 SymbolMap[&it->getSymbol()] = it;
655
656 // Create symbol data for any indirect symbols.
657 BindIndirectSymbols(Asm, SymbolMap);
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000658
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000659 // Compute symbol table information.
660 SmallString<256> StringTable;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000661 std::vector<MachSymbolData> LocalSymbolData;
662 std::vector<MachSymbolData> ExternalSymbolData;
663 std::vector<MachSymbolData> UndefinedSymbolData;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000664 unsigned NumSymbols = Asm.symbol_size();
665
666 // No symbol table command is written if there are no symbols.
667 if (NumSymbols)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000668 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
669 UndefinedSymbolData);
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000670
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000671 // The section data starts after the header, the segment load command (and
672 // section headers) and the symbol table.
673 unsigned NumLoadCommands = 1;
674 uint64_t LoadCommandsSize =
675 SegmentLoadCommand32Size + NumSections * Section32Size;
676
677 // Add the symbol table load command sizes, if used.
678 if (NumSymbols) {
679 NumLoadCommands += 2;
680 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
681 }
682
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000683 // Compute the total size of the section data, as well as its file size and
684 // vm size.
Daniel Dunbar6742e342009-08-26 04:13:32 +0000685 uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000686 uint64_t SectionDataSize = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000687 uint64_t SectionDataFileSize = 0;
688 uint64_t VMSize = 0;
689 for (MCAssembler::iterator it = Asm.begin(),
690 ie = Asm.end(); it != ie; ++it) {
691 MCSectionData &SD = *it;
692
693 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
694
695 SectionDataSize = std::max(SectionDataSize,
696 SD.getAddress() + SD.getSize());
697 SectionDataFileSize = std::max(SectionDataFileSize,
698 SD.getAddress() + SD.getFileSize());
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000699 }
700
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000701 // The section data is passed to 4 bytes.
702 //
703 // FIXME: Is this machine dependent?
704 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
705 SectionDataFileSize += SectionDataPadding;
706
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000707 // Write the prolog, starting with the header and load command...
Daniel Dunbar6009db42009-08-26 21:22:22 +0000708 WriteHeader32(NumLoadCommands, LoadCommandsSize,
709 Asm.getSubsectionsViaSymbols());
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000710 WriteSegmentLoadCommand32(NumSections, VMSize,
711 SectionDataStart, SectionDataSize);
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000712
713 // ... and then the section headers.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000714 //
715 // We also compute the section relocations while we do this. Note that
716 // compute relocation info will also update the fixup to have the correct
717 // value; this will be overwrite the appropriate data in the fragment when
718 // it is written.
719 std::vector<MachRelocationEntry> RelocInfos;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000720 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000721 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie;
722 ++it) {
723 MCSectionData &SD = *it;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000724
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000725 // The assembler writes relocations in the reverse order they were seen.
726 //
727 // FIXME: It is probably more complicated than this.
728 unsigned NumRelocsStart = RelocInfos.size();
729 for (unsigned i = 0, e = SD.fixup_size(); i != e; ++i)
730 ComputeRelocationInfo(Asm, SD.getFixups()[e - i - 1], SymbolMap,
731 RelocInfos);
732
733 unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
734 uint64_t SectionStart = SectionDataStart + SD.getAddress();
735 WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
736 RelocTableEnd += NumRelocs * RelocationInfoSize;
737 }
738
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000739 // Write the symbol table load command, if used.
740 if (NumSymbols) {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000741 unsigned FirstLocalSymbol = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000742 unsigned NumLocalSymbols = LocalSymbolData.size();
743 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
744 unsigned NumExternalSymbols = ExternalSymbolData.size();
745 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
746 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000747 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
748 unsigned NumSymTabSymbols =
749 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
750 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
751 uint64_t IndirectSymbolOffset = 0;
752
753 // If used, the indirect symbols are written after the section data.
754 if (NumIndirectSymbols)
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000755 IndirectSymbolOffset = RelocTableEnd;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000756
757 // The symbol table is written after the indirect symbol data.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000758 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000759
760 // The string table is written after symbol table.
761 uint64_t StringTableOffset =
762 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
763 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
764 StringTableOffset, StringTable.size());
765
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000766 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
767 FirstExternalSymbol, NumExternalSymbols,
768 FirstUndefinedSymbol, NumUndefinedSymbols,
769 IndirectSymbolOffset, NumIndirectSymbols);
770 }
771
772 // Write the actual section data.
773 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
774 WriteFileData(OS, *it, *this);
775
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000776 // Write the extra padding.
777 WriteZeros(SectionDataPadding);
778
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000779 // Write the relocation entries.
780 for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
781 Write32(RelocInfos[i].Word0);
782 Write32(RelocInfos[i].Word1);
783 }
784
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000785 // Write the symbol table data, if used.
786 if (NumSymbols) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000787 // Write the indirect symbol entries.
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000788 for (MCAssembler::indirect_symbol_iterator
789 it = Asm.indirect_symbol_begin(),
790 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
791 // Indirect symbols in the non lazy symbol pointer section have some
792 // special handling.
793 const MCSectionMachO &Section =
794 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
795 unsigned Type =
796 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
797 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
798 // If this symbol is defined and internal, mark it as such.
799 if (it->Symbol->isDefined() &&
800 !SymbolMap.lookup(it->Symbol)->isExternal()) {
801 uint32_t Flags = ISF_Local;
802 if (it->Symbol->isAbsolute())
803 Flags |= ISF_Absolute;
804 Write32(Flags);
805 continue;
806 }
807 }
808
Daniel Dunbarbe963552009-08-26 13:57:54 +0000809 Write32(SymbolMap[it->Symbol]->getIndex());
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000810 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000811
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000812 // FIXME: Check that offsets match computed ones.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000813
814 // Write the symbol table entries.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000815 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
816 WriteNlist32(LocalSymbolData[i]);
817 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
818 WriteNlist32(ExternalSymbolData[i]);
819 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
820 WriteNlist32(UndefinedSymbolData[i]);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000821
822 // Write the string table.
823 OS << StringTable.str();
824 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000825 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000826};
827
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000828/* *** */
829
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000830MCFragment::MCFragment() : Kind(FragmentType(~0)) {
831}
832
Daniel Dunbar5e835962009-08-26 02:48:04 +0000833MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000834 : Kind(_Kind),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000835 Parent(_Parent),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000836 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000837{
Daniel Dunbar5e835962009-08-26 02:48:04 +0000838 if (Parent)
839 Parent->getFragmentList().push_back(this);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000840}
841
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000842MCFragment::~MCFragment() {
843}
844
Daniel Dunbar5e835962009-08-26 02:48:04 +0000845uint64_t MCFragment::getAddress() const {
846 assert(getParent() && "Missing Section!");
847 return getParent()->getAddress() + Offset;
848}
849
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000850/* *** */
851
Daniel Dunbar81e40002009-08-27 00:38:04 +0000852MCSectionData::MCSectionData() : Section(0) {}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000853
854MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
Daniel Dunbar81e40002009-08-27 00:38:04 +0000855 : Section(&_Section),
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000856 Alignment(1),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000857 Address(~UINT64_C(0)),
Daniel Dunbar6742e342009-08-26 04:13:32 +0000858 Size(~UINT64_C(0)),
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000859 FileSize(~UINT64_C(0)),
860 LastFixupLookup(~0)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000861{
862 if (A)
863 A->getSectionList().push_back(this);
864}
865
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000866const MCSectionData::Fixup *
867MCSectionData::LookupFixup(const MCFragment *Fragment, uint64_t Offset) const {
868 // Use a one level cache to turn the common case of accessing the fixups in
869 // order into O(1) instead of O(N).
870 unsigned i = LastFixupLookup, Count = Fixups.size(), End = Fixups.size();
871 if (i >= End)
872 i = 0;
873 while (Count--) {
874 const Fixup &F = Fixups[i];
875 if (F.Fragment == Fragment && F.Offset == Offset) {
876 LastFixupLookup = i;
877 return &F;
878 }
879
880 ++i;
881 if (i == End)
882 i = 0;
883 }
884
885 return 0;
886}
887
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000888/* *** */
889
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000890MCSymbolData::MCSymbolData() : Symbol(*(MCSymbol*)0) {}
891
892MCSymbolData::MCSymbolData(MCSymbol &_Symbol, MCFragment *_Fragment,
893 uint64_t _Offset, MCAssembler *A)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000894 : Symbol(_Symbol), Fragment(_Fragment), Offset(_Offset),
Daniel Dunbarbe963552009-08-26 13:57:54 +0000895 IsExternal(false), IsPrivateExtern(false), Flags(0), Index(0)
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000896{
897 if (A)
898 A->getSymbolList().push_back(this);
899}
900
901/* *** */
902
Daniel Dunbar6009db42009-08-26 21:22:22 +0000903MCAssembler::MCAssembler(raw_ostream &_OS)
904 : OS(_OS),
905 SubsectionsViaSymbols(false)
906{
907}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000908
909MCAssembler::~MCAssembler() {
910}
911
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000912void MCAssembler::LayoutSection(MCSectionData &SD) {
Daniel Dunbar6742e342009-08-26 04:13:32 +0000913 uint64_t Address = SD.getAddress();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000914
915 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
916 MCFragment &F = *it;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000917
Daniel Dunbar6742e342009-08-26 04:13:32 +0000918 F.setOffset(Address - SD.getAddress());
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000919
920 // Evaluate fragment size.
921 switch (F.getKind()) {
922 case MCFragment::FT_Align: {
923 MCAlignFragment &AF = cast<MCAlignFragment>(F);
924
Daniel Dunbar6742e342009-08-26 04:13:32 +0000925 uint64_t Size = RoundUpToAlignment(Address, AF.getAlignment()) - Address;
926 if (Size > AF.getMaxBytesToEmit())
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000927 AF.setFileSize(0);
928 else
Daniel Dunbar6742e342009-08-26 04:13:32 +0000929 AF.setFileSize(Size);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000930 break;
931 }
932
933 case MCFragment::FT_Data:
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000934 F.setFileSize(F.getMaxFileSize());
935 break;
936
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000937 case MCFragment::FT_Fill: {
938 MCFillFragment &FF = cast<MCFillFragment>(F);
939
940 F.setFileSize(F.getMaxFileSize());
941
942 // If the fill value is constant, thats it.
943 if (FF.getValue().isAbsolute())
944 break;
945
946 // Otherwise, add fixups for the values.
947 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
948 MCSectionData::Fixup Fix(F, i * FF.getValueSize(),
949 FF.getValue(),FF.getValueSize());
950 SD.getFixups().push_back(Fix);
951 }
952 break;
953 }
954
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000955 case MCFragment::FT_Org: {
956 MCOrgFragment &OF = cast<MCOrgFragment>(F);
957
958 if (!OF.getOffset().isAbsolute())
959 llvm_unreachable("FIXME: Not yet implemented!");
960 uint64_t OrgOffset = OF.getOffset().getConstant();
Daniel Dunbar6742e342009-08-26 04:13:32 +0000961 uint64_t Offset = Address - SD.getAddress();
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000962
963 // FIXME: We need a way to communicate this error.
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000964 if (OrgOffset < Offset)
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000965 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
Daniel Dunbar6742e342009-08-26 04:13:32 +0000966 "' (at offset '" + Twine(Offset) + "'");
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000967
Daniel Dunbara5441fe2009-08-22 08:27:54 +0000968 F.setFileSize(OrgOffset - Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000969 break;
970 }
971 }
972
Daniel Dunbar6742e342009-08-26 04:13:32 +0000973 Address += F.getFileSize();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000974 }
975
Daniel Dunbar6742e342009-08-26 04:13:32 +0000976 // Set the section sizes.
977 SD.setSize(Address - SD.getAddress());
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000978 SD.setFileSize(Address - SD.getAddress());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000979}
980
981/// WriteFileData - Write the \arg F data to the output file.
982static void WriteFileData(raw_ostream &OS, const MCFragment &F,
983 MachObjectWriter &MOW) {
984 uint64_t Start = OS.tell();
985 (void) Start;
986
Daniel Dunbar0adcd352009-08-25 21:10:45 +0000987 ++EmittedFragments;
988
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000989 // FIXME: Embed in fragments instead?
990 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000991 case MCFragment::FT_Align: {
992 MCAlignFragment &AF = cast<MCAlignFragment>(F);
993 uint64_t Count = AF.getFileSize() / AF.getValueSize();
994
995 // FIXME: This error shouldn't actually occur (the front end should emit
996 // multiple .align directives to enforce the semantics it wants), but is
997 // severe enough that we want to report it. How to handle this?
998 if (Count * AF.getValueSize() != AF.getFileSize())
999 llvm_report_error("undefined .align directive, value size '" +
1000 Twine(AF.getValueSize()) +
1001 "' is not a divisor of padding size '" +
1002 Twine(AF.getFileSize()) + "'");
1003
1004 for (uint64_t i = 0; i != Count; ++i) {
1005 switch (AF.getValueSize()) {
1006 default:
1007 assert(0 && "Invalid size!");
1008 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1009 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1010 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1011 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1012 }
1013 }
1014 break;
1015 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001016
1017 case MCFragment::FT_Data:
1018 OS << cast<MCDataFragment>(F).getContents().str();
1019 break;
1020
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001021 case MCFragment::FT_Fill: {
1022 MCFillFragment &FF = cast<MCFillFragment>(F);
1023
Daniel Dunbar3f6a9602009-08-26 13:58:10 +00001024 int64_t Value = 0;
Daniel Dunbar6c31b052009-08-28 05:48:10 +00001025 if (FF.getValue().isAbsolute())
Daniel Dunbar3f6a9602009-08-26 13:58:10 +00001026 Value = FF.getValue().getConstant();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001027 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
Daniel Dunbar3f6a9602009-08-26 13:58:10 +00001028 if (!FF.getValue().isAbsolute()) {
1029 // Find the fixup.
1030 //
1031 // FIXME: Find a better way to write in the fixes.
1032 const MCSectionData::Fixup *Fixup =
1033 F.getParent()->LookupFixup(&F, i * FF.getValueSize());
1034 assert(Fixup && "Missing fixup for fill value!");
1035 Value = Fixup->FixedValue;
1036 }
1037
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001038 switch (FF.getValueSize()) {
1039 default:
1040 assert(0 && "Invalid size!");
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001041 case 1: MOW.Write8 (uint8_t (Value)); break;
1042 case 2: MOW.Write16(uint16_t(Value)); break;
1043 case 4: MOW.Write32(uint32_t(Value)); break;
1044 case 8: MOW.Write64(uint64_t(Value)); break;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001045 }
1046 }
1047 break;
1048 }
1049
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001050 case MCFragment::FT_Org: {
1051 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1052
1053 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1054 MOW.Write8(uint8_t(OF.getValue()));
1055
1056 break;
1057 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001058 }
1059
1060 assert(OS.tell() - Start == F.getFileSize());
1061}
1062
1063/// WriteFileData - Write the \arg SD data to the output file.
1064static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1065 MachObjectWriter &MOW) {
1066 uint64_t Start = OS.tell();
1067 (void) Start;
1068
1069 for (MCSectionData::const_iterator it = SD.begin(),
1070 ie = SD.end(); it != ie; ++it)
1071 WriteFileData(OS, *it, MOW);
1072
Daniel Dunbar6742e342009-08-26 04:13:32 +00001073 // Add section padding.
1074 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1075 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1076
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001077 assert(OS.tell() - Start == SD.getFileSize());
1078}
1079
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001080void MCAssembler::Finish() {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001081 // Layout the sections and fragments.
Daniel Dunbar5e835962009-08-26 02:48:04 +00001082 uint64_t Address = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001083 MCSectionData *Prev = 0;
1084 for (iterator it = begin(), ie = end(); it != ie; ++it) {
Daniel Dunbar6742e342009-08-26 04:13:32 +00001085 MCSectionData &SD = *it;
1086
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001087 // Align this section if necessary by adding padding bytes to the previous
1088 // section.
1089 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1090 assert(Prev && "Missing prev section!");
1091 Prev->setFileSize(Prev->getFileSize() + Pad);
1092 Address += Pad;
1093 }
Daniel Dunbar6742e342009-08-26 04:13:32 +00001094
1095 // Layout the section fragments and its size.
1096 SD.setAddress(Address);
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001097 LayoutSection(SD);
Daniel Dunbar6742e342009-08-26 04:13:32 +00001098 Address += SD.getFileSize();
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001099
1100 Prev = &SD;
Daniel Dunbar5e835962009-08-26 02:48:04 +00001101 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001102
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +00001103 // Write the object file.
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001104 MachObjectWriter MOW(OS);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +00001105 MOW.WriteObject(*this);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001106
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001107 OS.flush();
1108}