blob: 0afdf98cbe797a6b80470e8c7b12694080b508cd [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 Dunbar8f4d1462009-08-28 07:08:35 +000028// FIXME FIXME FIXME: There are number of places in this file where we convert
29// what is a 64-bit assembler value used for computation into a value in the
30// object file, which may truncate it. We should detect that truncation where
31// invalid and report errors back.
32
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000033static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
34 MachObjectWriter &MOW);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000035
Daniel Dunbard5a8e982009-08-28 05:49:21 +000036/// isVirtualSection - Check if this is a section which does not actually exist
37/// in the object file.
38static bool isVirtualSection(const MCSection &Section) {
39 // FIXME: Lame.
40 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
41 unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
42 return (Type == MCSectionMachO::S_ZEROFILL);
43}
44
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000045class MachObjectWriter {
46 // See <mach-o/loader.h>.
47 enum {
48 Header_Magic32 = 0xFEEDFACE,
49 Header_Magic64 = 0xFEEDFACF
50 };
51
52 static const unsigned Header32Size = 28;
53 static const unsigned Header64Size = 32;
54 static const unsigned SegmentLoadCommand32Size = 56;
55 static const unsigned Section32Size = 68;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000056 static const unsigned SymtabLoadCommandSize = 24;
57 static const unsigned DysymtabLoadCommandSize = 80;
58 static const unsigned Nlist32Size = 12;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +000059 static const unsigned RelocationInfoSize = 8;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000060
61 enum HeaderFileType {
62 HFT_Object = 0x1
63 };
64
Daniel Dunbar6009db42009-08-26 21:22:22 +000065 enum HeaderFlags {
66 HF_SubsectionsViaSymbols = 0x2000
67 };
68
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000069 enum LoadCommandType {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000070 LCT_Segment = 0x1,
71 LCT_Symtab = 0x2,
72 LCT_Dysymtab = 0xb
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000073 };
74
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +000075 // See <mach-o/nlist.h>.
76 enum SymbolTypeType {
77 STT_Undefined = 0x00,
78 STT_Absolute = 0x02,
79 STT_Section = 0x0e
80 };
81
82 enum SymbolTypeFlags {
83 // If any of these bits are set, then the entry is a stab entry number (see
84 // <mach-o/stab.h>. Otherwise the other masks apply.
85 STF_StabsEntryMask = 0xe0,
86
87 STF_TypeMask = 0x0e,
88 STF_External = 0x01,
89 STF_PrivateExtern = 0x10
90 };
91
Daniel Dunbarad7c3d52009-08-26 00:18:21 +000092 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
93 /// symbol entry.
94 enum IndirectSymbolFlags {
95 ISF_Local = 0x80000000,
96 ISF_Absolute = 0x40000000
97 };
98
Daniel Dunbar3f6a9602009-08-26 13:58:10 +000099 /// RelocationFlags - Special flags for addresses.
100 enum RelocationFlags {
101 RF_Scattered = 0x80000000
102 };
103
104 enum RelocationInfoType {
105 RIT_Vanilla = 0,
106 RIT_Pair = 1,
107 RIT_Difference = 2,
108 RIT_PreboundLazyPointer = 3,
109 RIT_LocalDifference = 4
110 };
111
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000112 /// MachSymbolData - Helper struct for containing some precomputed information
113 /// on symbols.
114 struct MachSymbolData {
115 MCSymbolData *SymbolData;
116 uint64_t StringIndex;
117 uint8_t SectionIndex;
118
119 // Support lexicographic sorting.
120 bool operator<(const MachSymbolData &RHS) const {
121 const std::string &Name = SymbolData->getSymbol().getName();
122 return Name < RHS.SymbolData->getSymbol().getName();
123 }
124 };
125
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000126 raw_ostream &OS;
127 bool IsLSB;
128
129public:
130 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
131 : OS(_OS), IsLSB(_IsLSB) {
132 }
133
134 /// @name Helper Methods
135 /// @{
136
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000137 void Write8(uint8_t Value) {
138 OS << char(Value);
139 }
140
141 void Write16(uint16_t Value) {
142 if (IsLSB) {
143 Write8(uint8_t(Value >> 0));
144 Write8(uint8_t(Value >> 8));
145 } else {
146 Write8(uint8_t(Value >> 8));
147 Write8(uint8_t(Value >> 0));
148 }
149 }
150
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000151 void Write32(uint32_t Value) {
152 if (IsLSB) {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000153 Write16(uint16_t(Value >> 0));
154 Write16(uint16_t(Value >> 16));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000155 } else {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000156 Write16(uint16_t(Value >> 16));
157 Write16(uint16_t(Value >> 0));
158 }
159 }
160
161 void Write64(uint64_t Value) {
162 if (IsLSB) {
163 Write32(uint32_t(Value >> 0));
164 Write32(uint32_t(Value >> 32));
165 } else {
166 Write32(uint32_t(Value >> 32));
167 Write32(uint32_t(Value >> 0));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000168 }
169 }
170
171 void WriteZeros(unsigned N) {
172 const char Zeros[16] = { 0 };
173
174 for (unsigned i = 0, e = N / 16; i != e; ++i)
175 OS << StringRef(Zeros, 16);
176
177 OS << StringRef(Zeros, N % 16);
178 }
179
180 void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
181 OS << Str;
182 if (ZeroFillSize)
183 WriteZeros(ZeroFillSize - Str.size());
184 }
185
186 /// @}
187
Daniel Dunbar6009db42009-08-26 21:22:22 +0000188 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
189 bool SubsectionsViaSymbols) {
190 uint32_t Flags = 0;
191
192 if (SubsectionsViaSymbols)
193 Flags |= HF_SubsectionsViaSymbols;
194
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000195 // struct mach_header (28 bytes)
196
197 uint64_t Start = OS.tell();
198 (void) Start;
199
200 Write32(Header_Magic32);
201
202 // FIXME: Support cputype.
203 Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000204 // FIXME: Support cpusubtype.
205 Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000206 Write32(HFT_Object);
Daniel Dunbar6009db42009-08-26 21:22:22 +0000207 Write32(NumLoadCommands); // Object files have a single load command, the
208 // segment.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000209 Write32(LoadCommandsSize);
Daniel Dunbar6009db42009-08-26 21:22:22 +0000210 Write32(Flags);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000211
212 assert(OS.tell() - Start == Header32Size);
213 }
214
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000215 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
216 ///
217 /// \arg NumSections - The number of sections in this segment.
218 /// \arg SectionDataSize - The total size of the sections.
219 void WriteSegmentLoadCommand32(unsigned NumSections,
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000220 uint64_t VMSize,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000221 uint64_t SectionDataStartOffset,
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000222 uint64_t SectionDataSize) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000223 // struct segment_command (56 bytes)
224
225 uint64_t Start = OS.tell();
226 (void) Start;
227
228 Write32(LCT_Segment);
229 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
230
231 WriteString("", 16);
232 Write32(0); // vmaddr
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000233 Write32(VMSize); // vmsize
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000234 Write32(SectionDataStartOffset); // file offset
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000235 Write32(SectionDataSize); // file size
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000236 Write32(0x7); // maxprot
237 Write32(0x7); // initprot
238 Write32(NumSections);
239 Write32(0); // flags
240
241 assert(OS.tell() - Start == SegmentLoadCommand32Size);
242 }
243
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000244 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
245 uint64_t RelocationsStart, unsigned NumRelocations) {
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000246 // The offset is unused for virtual sections.
247 if (isVirtualSection(SD.getSection())) {
248 assert(SD.getFileSize() == 0 && "Invalid file size!");
249 FileOffset = 0;
250 }
251
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000252 // struct section (68 bytes)
253
254 uint64_t Start = OS.tell();
255 (void) Start;
256
257 // FIXME: cast<> support!
258 const MCSectionMachO &Section =
259 static_cast<const MCSectionMachO&>(SD.getSection());
260 WriteString(Section.getSectionName(), 16);
261 WriteString(Section.getSegmentName(), 16);
Daniel Dunbar5e835962009-08-26 02:48:04 +0000262 Write32(SD.getAddress()); // address
Daniel Dunbar6742e342009-08-26 04:13:32 +0000263 Write32(SD.getSize()); // size
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000264 Write32(FileOffset);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000265
266 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
267 Write32(Log2_32(SD.getAlignment()));
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000268 Write32(NumRelocations ? RelocationsStart : 0);
269 Write32(NumRelocations);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000270 Write32(Section.getTypeAndAttributes());
271 Write32(0); // reserved1
272 Write32(Section.getStubSize()); // reserved2
273
274 assert(OS.tell() - Start == Section32Size);
275 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000276
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000277 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
278 uint32_t StringTableOffset,
279 uint32_t StringTableSize) {
280 // struct symtab_command (24 bytes)
281
282 uint64_t Start = OS.tell();
283 (void) Start;
284
285 Write32(LCT_Symtab);
286 Write32(SymtabLoadCommandSize);
287 Write32(SymbolOffset);
288 Write32(NumSymbols);
289 Write32(StringTableOffset);
290 Write32(StringTableSize);
291
292 assert(OS.tell() - Start == SymtabLoadCommandSize);
293 }
294
295 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
296 uint32_t NumLocalSymbols,
297 uint32_t FirstExternalSymbol,
298 uint32_t NumExternalSymbols,
299 uint32_t FirstUndefinedSymbol,
300 uint32_t NumUndefinedSymbols,
301 uint32_t IndirectSymbolOffset,
302 uint32_t NumIndirectSymbols) {
303 // struct dysymtab_command (80 bytes)
304
305 uint64_t Start = OS.tell();
306 (void) Start;
307
308 Write32(LCT_Dysymtab);
309 Write32(DysymtabLoadCommandSize);
310 Write32(FirstLocalSymbol);
311 Write32(NumLocalSymbols);
312 Write32(FirstExternalSymbol);
313 Write32(NumExternalSymbols);
314 Write32(FirstUndefinedSymbol);
315 Write32(NumUndefinedSymbols);
316 Write32(0); // tocoff
317 Write32(0); // ntoc
318 Write32(0); // modtaboff
319 Write32(0); // nmodtab
320 Write32(0); // extrefsymoff
321 Write32(0); // nextrefsyms
322 Write32(IndirectSymbolOffset);
323 Write32(NumIndirectSymbols);
324 Write32(0); // extreloff
325 Write32(0); // nextrel
326 Write32(0); // locreloff
327 Write32(0); // nlocrel
328
329 assert(OS.tell() - Start == DysymtabLoadCommandSize);
330 }
331
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000332 void WriteNlist32(MachSymbolData &MSD) {
Daniel Dunbar5e835962009-08-26 02:48:04 +0000333 MCSymbolData &Data = *MSD.SymbolData;
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000334 const MCSymbol &Symbol = Data.getSymbol();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000335 uint8_t Type = 0;
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000336 uint16_t Flags = Data.getFlags();
337 uint32_t Address = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000338
339 // Set the N_TYPE bits. See <mach-o/nlist.h>.
340 //
341 // FIXME: Are the prebound or indirect fields possible here?
342 if (Symbol.isUndefined())
343 Type = STT_Undefined;
344 else if (Symbol.isAbsolute())
345 Type = STT_Absolute;
346 else
347 Type = STT_Section;
348
349 // FIXME: Set STAB bits.
350
Daniel Dunbar5e835962009-08-26 02:48:04 +0000351 if (Data.isPrivateExtern())
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000352 Type |= STF_PrivateExtern;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000353
354 // Set external bit.
Daniel Dunbar5e835962009-08-26 02:48:04 +0000355 if (Data.isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000356 Type |= STF_External;
357
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000358 // Compute the symbol address.
359 if (Symbol.isDefined()) {
360 if (Symbol.isAbsolute()) {
361 llvm_unreachable("FIXME: Not yet implemented!");
362 } else {
363 Address = Data.getFragment()->getAddress() + Data.getOffset();
364 }
365 } else if (Data.isCommon()) {
366 // Common symbols are encoded with the size in the address
367 // field, and their alignment in the flags.
368 Address = Data.getCommonSize();
369
370 // Common alignment is packed into the 'desc' bits.
371 if (unsigned Align = Data.getCommonAlignment()) {
372 unsigned Log2Size = Log2_32(Align);
373 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
374 if (Log2Size > 15)
375 llvm_report_error("invalid 'common' alignment '" +
376 Twine(Align) + "'");
377 // FIXME: Keep this mask with the SymbolFlags enumeration.
378 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
379 }
380 }
381
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000382 // struct nlist (12 bytes)
383
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000384 Write32(MSD.StringIndex);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000385 Write8(Type);
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000386 Write8(MSD.SectionIndex);
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000387
388 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
389 // value.
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000390 Write16(Flags);
Daniel Dunbar5e835962009-08-26 02:48:04 +0000391 Write32(Address);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000392 }
393
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000394 struct MachRelocationEntry {
395 uint32_t Word0;
396 uint32_t Word1;
397 };
398 void ComputeScatteredRelocationInfo(MCAssembler &Asm,
399 MCSectionData::Fixup &Fixup,
400 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
401 std::vector<MachRelocationEntry> &Relocs) {
402 uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
403 unsigned IsPCRel = 0;
404 unsigned Type = RIT_Vanilla;
405
406 // See <reloc.h>.
407
408 const MCSymbol *A = Fixup.Value.getSymA();
409 MCSymbolData *SD = SymbolMap.lookup(A);
410 uint32_t Value = SD->getFragment()->getAddress() + SD->getOffset();
411 uint32_t Value2 = 0;
412
413 if (const MCSymbol *B = Fixup.Value.getSymB()) {
414 Type = RIT_LocalDifference;
415
416 MCSymbolData *SD = SymbolMap.lookup(B);
417 Value2 = SD->getFragment()->getAddress() + SD->getOffset();
418 }
419
420 unsigned Log2Size = Log2_32(Fixup.Size);
421 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
422
423 // The value which goes in the fixup is current value of the expression.
424 Fixup.FixedValue = Value - Value2 + Fixup.Value.getConstant();
425
426 MachRelocationEntry MRE;
427 MRE.Word0 = ((Address << 0) |
428 (Type << 24) |
429 (Log2Size << 28) |
430 (IsPCRel << 30) |
431 RF_Scattered);
432 MRE.Word1 = Value;
433 Relocs.push_back(MRE);
434
435 if (Type == RIT_LocalDifference) {
436 Type = RIT_Pair;
437
438 MachRelocationEntry MRE;
439 MRE.Word0 = ((0 << 0) |
440 (Type << 24) |
441 (Log2Size << 28) |
442 (0 << 30) |
443 RF_Scattered);
444 MRE.Word1 = Value2;
445 Relocs.push_back(MRE);
446 }
447 }
448
449 void ComputeRelocationInfo(MCAssembler &Asm,
450 MCSectionData::Fixup &Fixup,
451 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
452 std::vector<MachRelocationEntry> &Relocs) {
453 // If this is a local symbol plus an offset or a difference, then we need a
454 // scattered relocation entry.
455 if (Fixup.Value.getSymB()) // a - b
456 return ComputeScatteredRelocationInfo(Asm, Fixup, SymbolMap, Relocs);
457 if (Fixup.Value.getSymA() && Fixup.Value.getConstant())
458 if (!Fixup.Value.getSymA()->isUndefined())
459 return ComputeScatteredRelocationInfo(Asm, Fixup, SymbolMap, Relocs);
460
461 // See <reloc.h>.
462 uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
463 uint32_t Value = 0;
464 unsigned Index = 0;
465 unsigned IsPCRel = 0;
466 unsigned IsExtern = 0;
467 unsigned Type = 0;
468
469 if (Fixup.Value.isAbsolute()) { // constant
470 // SymbolNum of 0 indicates the absolute section.
471 Type = RIT_Vanilla;
472 Value = 0;
473 llvm_unreachable("FIXME: Not yet implemented!");
474 } else {
475 const MCSymbol *Symbol = Fixup.Value.getSymA();
476 MCSymbolData *SD = SymbolMap.lookup(Symbol);
477
478 if (Symbol->isUndefined()) {
479 IsExtern = 1;
480 Index = SD->getIndex();
481 Value = 0;
482 } else {
483 // The index is the section ordinal.
484 //
485 // FIXME: O(N)
486 Index = 1;
487 for (MCAssembler::iterator it = Asm.begin(),
488 ie = Asm.end(); it != ie; ++it, ++Index)
489 if (&*it == SD->getFragment()->getParent())
490 break;
491 Value = SD->getFragment()->getAddress() + SD->getOffset();
492 }
493
494 Type = RIT_Vanilla;
495 }
496
497 // The value which goes in the fixup is current value of the expression.
498 Fixup.FixedValue = Value + Fixup.Value.getConstant();
499
500 unsigned Log2Size = Log2_32(Fixup.Size);
501 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
502
503 // struct relocation_info (8 bytes)
504 MachRelocationEntry MRE;
505 MRE.Word0 = Address;
506 MRE.Word1 = ((Index << 0) |
507 (IsPCRel << 24) |
508 (Log2Size << 25) |
509 (IsExtern << 27) |
510 (Type << 28));
511 Relocs.push_back(MRE);
512 }
513
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000514 void BindIndirectSymbols(MCAssembler &Asm,
Daniel Dunbarbe963552009-08-26 13:57:54 +0000515 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000516 // This is the point where 'as' creates actual symbols for indirect symbols
517 // (in the following two passes). It would be easier for us to do this
518 // sooner when we see the attribute, but that makes getting the order in the
519 // symbol table much more complicated than it is worth.
520 //
521 // FIXME: Revisit this when the dust settles.
522
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000523 // Bind non lazy symbol pointers first.
524 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
525 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
526 // FIXME: cast<> support!
527 const MCSectionMachO &Section =
528 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
529
530 unsigned Type =
531 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
532 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
533 continue;
534
535 MCSymbolData *&Entry = SymbolMap[it->Symbol];
536 if (!Entry)
537 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
538 }
539
540 // Then lazy symbol pointers and symbol stubs.
541 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
542 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
543 // FIXME: cast<> support!
544 const MCSectionMachO &Section =
545 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
546
547 unsigned Type =
548 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
549 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
550 Type != MCSectionMachO::S_SYMBOL_STUBS)
551 continue;
552
553 MCSymbolData *&Entry = SymbolMap[it->Symbol];
554 if (!Entry) {
555 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
556
557 // Set the symbol type to undefined lazy, but only on construction.
558 //
559 // FIXME: Do not hardcode.
560 Entry->setFlags(Entry->getFlags() | 0x0001);
561 }
562 }
563 }
564
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000565 /// ComputeSymbolTable - Compute the symbol table data
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000566 ///
567 /// \param StringTable [out] - The string table data.
568 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
569 /// string table.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000570 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
571 std::vector<MachSymbolData> &LocalSymbolData,
572 std::vector<MachSymbolData> &ExternalSymbolData,
573 std::vector<MachSymbolData> &UndefinedSymbolData) {
574 // Build section lookup table.
575 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
576 unsigned Index = 1;
577 for (MCAssembler::iterator it = Asm.begin(),
578 ie = Asm.end(); it != ie; ++it, ++Index)
579 SectionIndexMap[&it->getSection()] = Index;
580 assert(Index <= 256 && "Too many sections!");
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000581
582 // Index 0 is always the empty string.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000583 StringMap<uint64_t> StringIndexMap;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000584 StringTable += '\x00';
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000585
586 // Build the symbol arrays and the string table, but only for non-local
587 // symbols.
588 //
589 // The particular order that we collect the symbols and create the string
590 // table, then sort the symbols is chosen to match 'as'. Even though it
591 // doesn't matter for correctness, this is important for letting us diff .o
592 // files.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000593 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
594 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000595 const MCSymbol &Symbol = it->getSymbol();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000596
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()];
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000605 if (!Entry) {
606 Entry = StringTable.size();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000607 StringTable += Symbol.getName();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000608 StringTable += '\x00';
609 }
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000610
611 MachSymbolData MSD;
612 MSD.SymbolData = it;
613 MSD.StringIndex = Entry;
614
615 if (Symbol.isUndefined()) {
616 MSD.SectionIndex = 0;
617 UndefinedSymbolData.push_back(MSD);
618 } else if (Symbol.isAbsolute()) {
619 MSD.SectionIndex = 0;
620 ExternalSymbolData.push_back(MSD);
621 } else {
622 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
623 assert(MSD.SectionIndex && "Invalid section index!");
624 ExternalSymbolData.push_back(MSD);
625 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000626 }
627
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000628 // Now add the data for local symbols.
629 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
630 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000631 const MCSymbol &Symbol = it->getSymbol();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000632
Daniel Dunbar959fd882009-08-26 22:13:22 +0000633 // Ignore assembler temporaries.
634 if (it->getSymbol().isTemporary())
635 continue;
636
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000637 if (it->isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000638 continue;
639
640 uint64_t &Entry = StringIndexMap[Symbol.getName()];
641 if (!Entry) {
642 Entry = StringTable.size();
643 StringTable += Symbol.getName();
644 StringTable += '\x00';
645 }
646
647 MachSymbolData MSD;
648 MSD.SymbolData = it;
649 MSD.StringIndex = Entry;
650
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000651 if (Symbol.isAbsolute()) {
652 MSD.SectionIndex = 0;
653 LocalSymbolData.push_back(MSD);
654 } else {
655 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
656 assert(MSD.SectionIndex && "Invalid section index!");
657 LocalSymbolData.push_back(MSD);
658 }
659 }
660
661 // External and undefined symbols are required to be in lexicographic order.
662 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
663 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
664
Daniel Dunbarbe963552009-08-26 13:57:54 +0000665 // Set the symbol indices.
666 Index = 0;
667 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
668 LocalSymbolData[i].SymbolData->setIndex(Index++);
669 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
670 ExternalSymbolData[i].SymbolData->setIndex(Index++);
671 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
672 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
673
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000674 // The string table is padded to a multiple of 4.
675 //
676 // FIXME: Check to see if this varies per arch.
677 while (StringTable.size() % 4)
678 StringTable += '\x00';
679 }
680
681 void WriteObject(MCAssembler &Asm) {
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000682 unsigned NumSections = Asm.size();
683
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000684 // Compute the symbol -> symbol data map.
685 //
686 // FIXME: This should not be here.
Daniel Dunbarbe963552009-08-26 13:57:54 +0000687 DenseMap<const MCSymbol*, MCSymbolData *> SymbolMap;
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000688 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
689 ie = Asm.symbol_end(); it != ie; ++it)
690 SymbolMap[&it->getSymbol()] = it;
691
692 // Create symbol data for any indirect symbols.
693 BindIndirectSymbols(Asm, SymbolMap);
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000694
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000695 // Compute symbol table information.
696 SmallString<256> StringTable;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000697 std::vector<MachSymbolData> LocalSymbolData;
698 std::vector<MachSymbolData> ExternalSymbolData;
699 std::vector<MachSymbolData> UndefinedSymbolData;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000700 unsigned NumSymbols = Asm.symbol_size();
701
702 // No symbol table command is written if there are no symbols.
703 if (NumSymbols)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000704 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
705 UndefinedSymbolData);
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000706
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000707 // The section data starts after the header, the segment load command (and
708 // section headers) and the symbol table.
709 unsigned NumLoadCommands = 1;
710 uint64_t LoadCommandsSize =
711 SegmentLoadCommand32Size + NumSections * Section32Size;
712
713 // Add the symbol table load command sizes, if used.
714 if (NumSymbols) {
715 NumLoadCommands += 2;
716 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
717 }
718
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000719 // Compute the total size of the section data, as well as its file size and
720 // vm size.
Daniel Dunbar6742e342009-08-26 04:13:32 +0000721 uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000722 uint64_t SectionDataSize = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000723 uint64_t SectionDataFileSize = 0;
724 uint64_t VMSize = 0;
725 for (MCAssembler::iterator it = Asm.begin(),
726 ie = Asm.end(); it != ie; ++it) {
727 MCSectionData &SD = *it;
728
729 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
730
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000731 if (isVirtualSection(SD.getSection()))
732 continue;
733
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000734 SectionDataSize = std::max(SectionDataSize,
735 SD.getAddress() + SD.getSize());
736 SectionDataFileSize = std::max(SectionDataFileSize,
737 SD.getAddress() + SD.getFileSize());
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000738 }
739
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000740 // The section data is passed to 4 bytes.
741 //
742 // FIXME: Is this machine dependent?
743 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
744 SectionDataFileSize += SectionDataPadding;
745
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000746 // Write the prolog, starting with the header and load command...
Daniel Dunbar6009db42009-08-26 21:22:22 +0000747 WriteHeader32(NumLoadCommands, LoadCommandsSize,
748 Asm.getSubsectionsViaSymbols());
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000749 WriteSegmentLoadCommand32(NumSections, VMSize,
750 SectionDataStart, SectionDataSize);
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000751
752 // ... and then the section headers.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000753 //
754 // We also compute the section relocations while we do this. Note that
755 // compute relocation info will also update the fixup to have the correct
756 // value; this will be overwrite the appropriate data in the fragment when
757 // it is written.
758 std::vector<MachRelocationEntry> RelocInfos;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000759 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000760 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie;
761 ++it) {
762 MCSectionData &SD = *it;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000763
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000764 // The assembler writes relocations in the reverse order they were seen.
765 //
766 // FIXME: It is probably more complicated than this.
767 unsigned NumRelocsStart = RelocInfos.size();
768 for (unsigned i = 0, e = SD.fixup_size(); i != e; ++i)
769 ComputeRelocationInfo(Asm, SD.getFixups()[e - i - 1], SymbolMap,
770 RelocInfos);
771
772 unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
773 uint64_t SectionStart = SectionDataStart + SD.getAddress();
774 WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
775 RelocTableEnd += NumRelocs * RelocationInfoSize;
776 }
777
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000778 // Write the symbol table load command, if used.
779 if (NumSymbols) {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000780 unsigned FirstLocalSymbol = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000781 unsigned NumLocalSymbols = LocalSymbolData.size();
782 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
783 unsigned NumExternalSymbols = ExternalSymbolData.size();
784 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
785 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000786 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
787 unsigned NumSymTabSymbols =
788 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
789 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
790 uint64_t IndirectSymbolOffset = 0;
791
792 // If used, the indirect symbols are written after the section data.
793 if (NumIndirectSymbols)
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000794 IndirectSymbolOffset = RelocTableEnd;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000795
796 // The symbol table is written after the indirect symbol data.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000797 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000798
799 // The string table is written after symbol table.
800 uint64_t StringTableOffset =
801 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
802 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
803 StringTableOffset, StringTable.size());
804
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000805 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
806 FirstExternalSymbol, NumExternalSymbols,
807 FirstUndefinedSymbol, NumUndefinedSymbols,
808 IndirectSymbolOffset, NumIndirectSymbols);
809 }
810
811 // Write the actual section data.
812 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
813 WriteFileData(OS, *it, *this);
814
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000815 // Write the extra padding.
816 WriteZeros(SectionDataPadding);
817
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000818 // Write the relocation entries.
819 for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
820 Write32(RelocInfos[i].Word0);
821 Write32(RelocInfos[i].Word1);
822 }
823
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000824 // Write the symbol table data, if used.
825 if (NumSymbols) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000826 // Write the indirect symbol entries.
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000827 for (MCAssembler::indirect_symbol_iterator
828 it = Asm.indirect_symbol_begin(),
829 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
830 // Indirect symbols in the non lazy symbol pointer section have some
831 // special handling.
832 const MCSectionMachO &Section =
833 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
834 unsigned Type =
835 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
836 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
837 // If this symbol is defined and internal, mark it as such.
838 if (it->Symbol->isDefined() &&
839 !SymbolMap.lookup(it->Symbol)->isExternal()) {
840 uint32_t Flags = ISF_Local;
841 if (it->Symbol->isAbsolute())
842 Flags |= ISF_Absolute;
843 Write32(Flags);
844 continue;
845 }
846 }
847
Daniel Dunbarbe963552009-08-26 13:57:54 +0000848 Write32(SymbolMap[it->Symbol]->getIndex());
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000849 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000850
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000851 // FIXME: Check that offsets match computed ones.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000852
853 // Write the symbol table entries.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000854 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
855 WriteNlist32(LocalSymbolData[i]);
856 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
857 WriteNlist32(ExternalSymbolData[i]);
858 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
859 WriteNlist32(UndefinedSymbolData[i]);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000860
861 // Write the string table.
862 OS << StringTable.str();
863 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000864 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000865};
866
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000867/* *** */
868
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000869MCFragment::MCFragment() : Kind(FragmentType(~0)) {
870}
871
Daniel Dunbar5e835962009-08-26 02:48:04 +0000872MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000873 : Kind(_Kind),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000874 Parent(_Parent),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000875 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000876{
Daniel Dunbar5e835962009-08-26 02:48:04 +0000877 if (Parent)
878 Parent->getFragmentList().push_back(this);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000879}
880
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000881MCFragment::~MCFragment() {
882}
883
Daniel Dunbar5e835962009-08-26 02:48:04 +0000884uint64_t MCFragment::getAddress() const {
885 assert(getParent() && "Missing Section!");
886 return getParent()->getAddress() + Offset;
887}
888
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000889/* *** */
890
Daniel Dunbar81e40002009-08-27 00:38:04 +0000891MCSectionData::MCSectionData() : Section(0) {}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000892
893MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
Daniel Dunbar81e40002009-08-27 00:38:04 +0000894 : Section(&_Section),
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000895 Alignment(1),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000896 Address(~UINT64_C(0)),
Daniel Dunbar6742e342009-08-26 04:13:32 +0000897 Size(~UINT64_C(0)),
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000898 FileSize(~UINT64_C(0)),
899 LastFixupLookup(~0)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000900{
901 if (A)
902 A->getSectionList().push_back(this);
903}
904
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000905const MCSectionData::Fixup *
906MCSectionData::LookupFixup(const MCFragment *Fragment, uint64_t Offset) const {
907 // Use a one level cache to turn the common case of accessing the fixups in
908 // order into O(1) instead of O(N).
909 unsigned i = LastFixupLookup, Count = Fixups.size(), End = Fixups.size();
910 if (i >= End)
911 i = 0;
912 while (Count--) {
913 const Fixup &F = Fixups[i];
914 if (F.Fragment == Fragment && F.Offset == Offset) {
915 LastFixupLookup = i;
916 return &F;
917 }
918
919 ++i;
920 if (i == End)
921 i = 0;
922 }
923
924 return 0;
925}
926
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000927/* *** */
928
Daniel Dunbarefbb5332009-09-01 04:09:03 +0000929MCSymbolData::MCSymbolData() : Symbol(0) {}
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000930
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000931MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000932 uint64_t _Offset, MCAssembler *A)
Daniel Dunbarefbb5332009-09-01 04:09:03 +0000933 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000934 IsExternal(false), IsPrivateExtern(false),
935 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000936{
937 if (A)
938 A->getSymbolList().push_back(this);
939}
940
941/* *** */
942
Daniel Dunbara03a3682009-08-31 08:07:55 +0000943MCAssembler::MCAssembler(MCContext &_Context, raw_ostream &_OS)
944 : Context(_Context), OS(_OS), SubsectionsViaSymbols(false)
Daniel Dunbar6009db42009-08-26 21:22:22 +0000945{
946}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000947
948MCAssembler::~MCAssembler() {
949}
950
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000951void MCAssembler::LayoutSection(MCSectionData &SD) {
Daniel Dunbar6742e342009-08-26 04:13:32 +0000952 uint64_t Address = SD.getAddress();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000953
954 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
955 MCFragment &F = *it;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000956
Daniel Dunbar6742e342009-08-26 04:13:32 +0000957 F.setOffset(Address - SD.getAddress());
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000958
959 // Evaluate fragment size.
960 switch (F.getKind()) {
961 case MCFragment::FT_Align: {
962 MCAlignFragment &AF = cast<MCAlignFragment>(F);
963
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000964 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
Daniel Dunbar6742e342009-08-26 04:13:32 +0000965 if (Size > AF.getMaxBytesToEmit())
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000966 AF.setFileSize(0);
967 else
Daniel Dunbar6742e342009-08-26 04:13:32 +0000968 AF.setFileSize(Size);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000969 break;
970 }
971
972 case MCFragment::FT_Data:
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000973 F.setFileSize(F.getMaxFileSize());
974 break;
975
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000976 case MCFragment::FT_Fill: {
977 MCFillFragment &FF = cast<MCFillFragment>(F);
978
979 F.setFileSize(F.getMaxFileSize());
980
981 // If the fill value is constant, thats it.
982 if (FF.getValue().isAbsolute())
983 break;
984
985 // Otherwise, add fixups for the values.
986 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
987 MCSectionData::Fixup Fix(F, i * FF.getValueSize(),
988 FF.getValue(),FF.getValueSize());
989 SD.getFixups().push_back(Fix);
990 }
991 break;
992 }
993
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000994 case MCFragment::FT_Org: {
995 MCOrgFragment &OF = cast<MCOrgFragment>(F);
996
997 if (!OF.getOffset().isAbsolute())
998 llvm_unreachable("FIXME: Not yet implemented!");
999 uint64_t OrgOffset = OF.getOffset().getConstant();
Daniel Dunbar6742e342009-08-26 04:13:32 +00001000 uint64_t Offset = Address - SD.getAddress();
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001001
1002 // FIXME: We need a way to communicate this error.
Daniel Dunbara5441fe2009-08-22 08:27:54 +00001003 if (OrgOffset < Offset)
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001004 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
Daniel Dunbar6742e342009-08-26 04:13:32 +00001005 "' (at offset '" + Twine(Offset) + "'");
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001006
Daniel Dunbara5441fe2009-08-22 08:27:54 +00001007 F.setFileSize(OrgOffset - Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001008 break;
1009 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001010
1011 case MCFragment::FT_ZeroFill: {
1012 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1013
1014 // Align the fragment offset; it is safe to adjust the offset freely since
1015 // this is only in virtual sections.
1016 uint64_t Aligned = RoundUpToAlignment(Address, ZFF.getAlignment());
1017 F.setOffset(Aligned - SD.getAddress());
1018
1019 // FIXME: This is misnamed.
1020 F.setFileSize(ZFF.getSize());
1021 break;
1022 }
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001023 }
1024
Daniel Dunbar6742e342009-08-26 04:13:32 +00001025 Address += F.getFileSize();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001026 }
1027
Daniel Dunbar6742e342009-08-26 04:13:32 +00001028 // Set the section sizes.
1029 SD.setSize(Address - SD.getAddress());
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001030 if (isVirtualSection(SD.getSection()))
1031 SD.setFileSize(0);
1032 else
1033 SD.setFileSize(Address - SD.getAddress());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001034}
1035
1036/// WriteFileData - Write the \arg F data to the output file.
1037static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1038 MachObjectWriter &MOW) {
1039 uint64_t Start = OS.tell();
1040 (void) Start;
1041
Daniel Dunbar0adcd352009-08-25 21:10:45 +00001042 ++EmittedFragments;
1043
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001044 // FIXME: Embed in fragments instead?
1045 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001046 case MCFragment::FT_Align: {
1047 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1048 uint64_t Count = AF.getFileSize() / AF.getValueSize();
1049
1050 // FIXME: This error shouldn't actually occur (the front end should emit
1051 // multiple .align directives to enforce the semantics it wants), but is
1052 // severe enough that we want to report it. How to handle this?
1053 if (Count * AF.getValueSize() != AF.getFileSize())
1054 llvm_report_error("undefined .align directive, value size '" +
1055 Twine(AF.getValueSize()) +
1056 "' is not a divisor of padding size '" +
1057 Twine(AF.getFileSize()) + "'");
1058
1059 for (uint64_t i = 0; i != Count; ++i) {
1060 switch (AF.getValueSize()) {
1061 default:
1062 assert(0 && "Invalid size!");
1063 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1064 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1065 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1066 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1067 }
1068 }
1069 break;
1070 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001071
1072 case MCFragment::FT_Data:
1073 OS << cast<MCDataFragment>(F).getContents().str();
1074 break;
1075
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001076 case MCFragment::FT_Fill: {
1077 MCFillFragment &FF = cast<MCFillFragment>(F);
1078
Daniel Dunbar3f6a9602009-08-26 13:58:10 +00001079 int64_t Value = 0;
Daniel Dunbar6c31b052009-08-28 05:48:10 +00001080 if (FF.getValue().isAbsolute())
Daniel Dunbar3f6a9602009-08-26 13:58:10 +00001081 Value = FF.getValue().getConstant();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001082 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
Daniel Dunbar3f6a9602009-08-26 13:58:10 +00001083 if (!FF.getValue().isAbsolute()) {
1084 // Find the fixup.
1085 //
1086 // FIXME: Find a better way to write in the fixes.
1087 const MCSectionData::Fixup *Fixup =
1088 F.getParent()->LookupFixup(&F, i * FF.getValueSize());
1089 assert(Fixup && "Missing fixup for fill value!");
1090 Value = Fixup->FixedValue;
1091 }
1092
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001093 switch (FF.getValueSize()) {
1094 default:
1095 assert(0 && "Invalid size!");
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001096 case 1: MOW.Write8 (uint8_t (Value)); break;
1097 case 2: MOW.Write16(uint16_t(Value)); break;
1098 case 4: MOW.Write32(uint32_t(Value)); break;
1099 case 8: MOW.Write64(uint64_t(Value)); break;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001100 }
1101 }
1102 break;
1103 }
1104
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001105 case MCFragment::FT_Org: {
1106 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1107
1108 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1109 MOW.Write8(uint8_t(OF.getValue()));
1110
1111 break;
1112 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001113
1114 case MCFragment::FT_ZeroFill: {
1115 assert(0 && "Invalid zero fill fragment in concrete section!");
1116 break;
1117 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001118 }
1119
1120 assert(OS.tell() - Start == F.getFileSize());
1121}
1122
1123/// WriteFileData - Write the \arg SD data to the output file.
1124static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1125 MachObjectWriter &MOW) {
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001126 // Ignore virtual sections.
1127 if (isVirtualSection(SD.getSection())) {
1128 assert(SD.getFileSize() == 0);
1129 return;
1130 }
1131
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001132 uint64_t Start = OS.tell();
1133 (void) Start;
1134
1135 for (MCSectionData::const_iterator it = SD.begin(),
1136 ie = SD.end(); it != ie; ++it)
1137 WriteFileData(OS, *it, MOW);
1138
Daniel Dunbar6742e342009-08-26 04:13:32 +00001139 // Add section padding.
1140 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1141 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1142
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001143 assert(OS.tell() - Start == SD.getFileSize());
1144}
1145
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001146void MCAssembler::Finish() {
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001147 // Layout the concrete sections and fragments.
Daniel Dunbar5e835962009-08-26 02:48:04 +00001148 uint64_t Address = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001149 MCSectionData *Prev = 0;
1150 for (iterator it = begin(), ie = end(); it != ie; ++it) {
Daniel Dunbar6742e342009-08-26 04:13:32 +00001151 MCSectionData &SD = *it;
1152
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001153 // Skip virtual sections.
1154 if (isVirtualSection(SD.getSection()))
1155 continue;
1156
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001157 // Align this section if necessary by adding padding bytes to the previous
1158 // section.
1159 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1160 assert(Prev && "Missing prev section!");
1161 Prev->setFileSize(Prev->getFileSize() + Pad);
1162 Address += Pad;
1163 }
Daniel Dunbar6742e342009-08-26 04:13:32 +00001164
1165 // Layout the section fragments and its size.
1166 SD.setAddress(Address);
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001167 LayoutSection(SD);
Daniel Dunbar6742e342009-08-26 04:13:32 +00001168 Address += SD.getFileSize();
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001169
1170 Prev = &SD;
Daniel Dunbar5e835962009-08-26 02:48:04 +00001171 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001172
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001173 // Layout the virtual sections.
1174 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1175 MCSectionData &SD = *it;
1176
1177 if (!isVirtualSection(SD.getSection()))
1178 continue;
1179
1180 SD.setAddress(Address);
1181 LayoutSection(SD);
1182 Address += SD.getSize();
1183 }
1184
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +00001185 // Write the object file.
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001186 MachObjectWriter MOW(OS);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +00001187 MOW.WriteObject(*this);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001188
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001189 OS.flush();
1190}