blob: 08943ebd93e09ea1b3889288ec514e25658fb6f4 [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"
Daniel Dunbar1253a6f2009-10-16 01:58:03 +000012#include "llvm/MC/MCExpr.h"
Chris Lattnerbea2c952009-08-22 19:19:12 +000013#include "llvm/MC/MCSectionMachO.h"
Daniel Dunbar1253a6f2009-10-16 01:58:03 +000014#include "llvm/MC/MCSymbol.h"
15#include "llvm/MC/MCValue.h"
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +000016#include "llvm/ADT/DenseMap.h"
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000017#include "llvm/ADT/SmallString.h"
Daniel Dunbar0adcd352009-08-25 21:10:45 +000018#include "llvm/ADT/Statistic.h"
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000019#include "llvm/ADT/StringMap.h"
Daniel Dunbard6f761e2009-08-21 23:07:38 +000020#include "llvm/ADT/Twine.h"
Daniel Dunbar0705fbf2009-08-21 18:29:01 +000021#include "llvm/Support/ErrorHandling.h"
Chris Lattner45f8c092010-02-02 19:38:14 +000022#include "llvm/Support/MachO.h"
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000023#include "llvm/Support/raw_ostream.h"
Chris Lattner23132b12009-08-24 03:52:50 +000024#include <vector>
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000025using namespace llvm;
26
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000027class MachObjectWriter;
28
Daniel Dunbar0adcd352009-08-25 21:10:45 +000029STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
30
Daniel Dunbar8f4d1462009-08-28 07:08:35 +000031// FIXME FIXME FIXME: There are number of places in this file where we convert
32// what is a 64-bit assembler value used for computation into a value in the
33// object file, which may truncate it. We should detect that truncation where
34// invalid and report errors back.
35
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000036static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
37 MachObjectWriter &MOW);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000038
Daniel Dunbard5a8e982009-08-28 05:49:21 +000039/// isVirtualSection - Check if this is a section which does not actually exist
40/// in the object file.
41static bool isVirtualSection(const MCSection &Section) {
42 // FIXME: Lame.
43 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
44 unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
45 return (Type == MCSectionMachO::S_ZEROFILL);
46}
47
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000048class MachObjectWriter {
49 // See <mach-o/loader.h>.
50 enum {
51 Header_Magic32 = 0xFEEDFACE,
52 Header_Magic64 = 0xFEEDFACF
53 };
Daniel Dunbar7eb85192009-10-16 01:58:15 +000054
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000055 static const unsigned Header32Size = 28;
56 static const unsigned Header64Size = 32;
57 static const unsigned SegmentLoadCommand32Size = 56;
58 static const unsigned Section32Size = 68;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000059 static const unsigned SymtabLoadCommandSize = 24;
60 static const unsigned DysymtabLoadCommandSize = 80;
61 static const unsigned Nlist32Size = 12;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +000062 static const unsigned RelocationInfoSize = 8;
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000063
64 enum HeaderFileType {
65 HFT_Object = 0x1
66 };
67
Daniel Dunbar6009db42009-08-26 21:22:22 +000068 enum HeaderFlags {
69 HF_SubsectionsViaSymbols = 0x2000
70 };
71
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000072 enum LoadCommandType {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +000073 LCT_Segment = 0x1,
74 LCT_Symtab = 0x2,
75 LCT_Dysymtab = 0xb
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +000076 };
77
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +000078 // See <mach-o/nlist.h>.
79 enum SymbolTypeType {
80 STT_Undefined = 0x00,
81 STT_Absolute = 0x02,
82 STT_Section = 0x0e
83 };
84
85 enum SymbolTypeFlags {
86 // If any of these bits are set, then the entry is a stab entry number (see
87 // <mach-o/stab.h>. Otherwise the other masks apply.
88 STF_StabsEntryMask = 0xe0,
89
90 STF_TypeMask = 0x0e,
91 STF_External = 0x01,
92 STF_PrivateExtern = 0x10
93 };
94
Daniel Dunbarad7c3d52009-08-26 00:18:21 +000095 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
96 /// symbol entry.
97 enum IndirectSymbolFlags {
98 ISF_Local = 0x80000000,
99 ISF_Absolute = 0x40000000
100 };
101
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000102 /// RelocationFlags - Special flags for addresses.
103 enum RelocationFlags {
104 RF_Scattered = 0x80000000
105 };
106
107 enum RelocationInfoType {
108 RIT_Vanilla = 0,
109 RIT_Pair = 1,
110 RIT_Difference = 2,
111 RIT_PreboundLazyPointer = 3,
112 RIT_LocalDifference = 4
113 };
114
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000115 /// MachSymbolData - Helper struct for containing some precomputed information
116 /// on symbols.
117 struct MachSymbolData {
118 MCSymbolData *SymbolData;
119 uint64_t StringIndex;
120 uint8_t SectionIndex;
121
122 // Support lexicographic sorting.
123 bool operator<(const MachSymbolData &RHS) const {
124 const std::string &Name = SymbolData->getSymbol().getName();
125 return Name < RHS.SymbolData->getSymbol().getName();
126 }
127 };
128
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000129 raw_ostream &OS;
130 bool IsLSB;
131
132public:
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000133 MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000134 : OS(_OS), IsLSB(_IsLSB) {
135 }
136
137 /// @name Helper Methods
138 /// @{
139
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000140 void Write8(uint8_t Value) {
141 OS << char(Value);
142 }
143
144 void Write16(uint16_t Value) {
145 if (IsLSB) {
146 Write8(uint8_t(Value >> 0));
147 Write8(uint8_t(Value >> 8));
148 } else {
149 Write8(uint8_t(Value >> 8));
150 Write8(uint8_t(Value >> 0));
151 }
152 }
153
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000154 void Write32(uint32_t Value) {
155 if (IsLSB) {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000156 Write16(uint16_t(Value >> 0));
157 Write16(uint16_t(Value >> 16));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000158 } else {
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000159 Write16(uint16_t(Value >> 16));
160 Write16(uint16_t(Value >> 0));
161 }
162 }
163
164 void Write64(uint64_t Value) {
165 if (IsLSB) {
166 Write32(uint32_t(Value >> 0));
167 Write32(uint32_t(Value >> 32));
168 } else {
169 Write32(uint32_t(Value >> 32));
170 Write32(uint32_t(Value >> 0));
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000171 }
172 }
173
174 void WriteZeros(unsigned N) {
175 const char Zeros[16] = { 0 };
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000176
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000177 for (unsigned i = 0, e = N / 16; i != e; ++i)
178 OS << StringRef(Zeros, 16);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000179
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000180 OS << StringRef(Zeros, N % 16);
181 }
182
Daniel Dunbar2928c832009-11-06 10:58:06 +0000183 void WriteString(StringRef Str, unsigned ZeroFillSize = 0) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000184 OS << Str;
185 if (ZeroFillSize)
186 WriteZeros(ZeroFillSize - Str.size());
187 }
188
189 /// @}
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000190
Daniel Dunbar6009db42009-08-26 21:22:22 +0000191 void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
192 bool SubsectionsViaSymbols) {
193 uint32_t Flags = 0;
194
195 if (SubsectionsViaSymbols)
196 Flags |= HF_SubsectionsViaSymbols;
197
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000198 // struct mach_header (28 bytes)
199
200 uint64_t Start = OS.tell();
201 (void) Start;
202
203 Write32(Header_Magic32);
204
205 // FIXME: Support cputype.
Chris Lattner45f8c092010-02-02 19:38:14 +0000206 Write32(MachO::CPUTypeI386);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000207 // FIXME: Support cpusubtype.
Chris Lattner45f8c092010-02-02 19:38:14 +0000208 Write32(MachO::CPUSubType_I386_ALL);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000209 Write32(HFT_Object);
Daniel Dunbar6009db42009-08-26 21:22:22 +0000210 Write32(NumLoadCommands); // Object files have a single load command, the
211 // segment.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000212 Write32(LoadCommandsSize);
Daniel Dunbar6009db42009-08-26 21:22:22 +0000213 Write32(Flags);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000214
215 assert(OS.tell() - Start == Header32Size);
216 }
217
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000218 /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
219 ///
220 /// \arg NumSections - The number of sections in this segment.
221 /// \arg SectionDataSize - The total size of the sections.
222 void WriteSegmentLoadCommand32(unsigned NumSections,
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000223 uint64_t VMSize,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000224 uint64_t SectionDataStartOffset,
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000225 uint64_t SectionDataSize) {
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000226 // struct segment_command (56 bytes)
227
228 uint64_t Start = OS.tell();
229 (void) Start;
230
231 Write32(LCT_Segment);
232 Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
233
234 WriteString("", 16);
235 Write32(0); // vmaddr
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000236 Write32(VMSize); // vmsize
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000237 Write32(SectionDataStartOffset); // file offset
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000238 Write32(SectionDataSize); // file size
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000239 Write32(0x7); // maxprot
240 Write32(0x7); // initprot
241 Write32(NumSections);
242 Write32(0); // flags
243
244 assert(OS.tell() - Start == SegmentLoadCommand32Size);
245 }
246
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000247 void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
248 uint64_t RelocationsStart, unsigned NumRelocations) {
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000249 // The offset is unused for virtual sections.
250 if (isVirtualSection(SD.getSection())) {
251 assert(SD.getFileSize() == 0 && "Invalid file size!");
252 FileOffset = 0;
253 }
254
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000255 // struct section (68 bytes)
256
257 uint64_t Start = OS.tell();
258 (void) Start;
259
260 // FIXME: cast<> support!
261 const MCSectionMachO &Section =
262 static_cast<const MCSectionMachO&>(SD.getSection());
263 WriteString(Section.getSectionName(), 16);
264 WriteString(Section.getSegmentName(), 16);
Daniel Dunbar5e835962009-08-26 02:48:04 +0000265 Write32(SD.getAddress()); // address
Daniel Dunbar6742e342009-08-26 04:13:32 +0000266 Write32(SD.getSize()); // size
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000267 Write32(FileOffset);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000268
269 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
270 Write32(Log2_32(SD.getAlignment()));
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000271 Write32(NumRelocations ? RelocationsStart : 0);
272 Write32(NumRelocations);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000273 Write32(Section.getTypeAndAttributes());
274 Write32(0); // reserved1
275 Write32(Section.getStubSize()); // reserved2
276
277 assert(OS.tell() - Start == Section32Size);
278 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000279
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000280 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
281 uint32_t StringTableOffset,
282 uint32_t StringTableSize) {
283 // struct symtab_command (24 bytes)
284
285 uint64_t Start = OS.tell();
286 (void) Start;
287
288 Write32(LCT_Symtab);
289 Write32(SymtabLoadCommandSize);
290 Write32(SymbolOffset);
291 Write32(NumSymbols);
292 Write32(StringTableOffset);
293 Write32(StringTableSize);
294
295 assert(OS.tell() - Start == SymtabLoadCommandSize);
296 }
297
298 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
299 uint32_t NumLocalSymbols,
300 uint32_t FirstExternalSymbol,
301 uint32_t NumExternalSymbols,
302 uint32_t FirstUndefinedSymbol,
303 uint32_t NumUndefinedSymbols,
304 uint32_t IndirectSymbolOffset,
305 uint32_t NumIndirectSymbols) {
306 // struct dysymtab_command (80 bytes)
307
308 uint64_t Start = OS.tell();
309 (void) Start;
310
311 Write32(LCT_Dysymtab);
312 Write32(DysymtabLoadCommandSize);
313 Write32(FirstLocalSymbol);
314 Write32(NumLocalSymbols);
315 Write32(FirstExternalSymbol);
316 Write32(NumExternalSymbols);
317 Write32(FirstUndefinedSymbol);
318 Write32(NumUndefinedSymbols);
319 Write32(0); // tocoff
320 Write32(0); // ntoc
321 Write32(0); // modtaboff
322 Write32(0); // nmodtab
323 Write32(0); // extrefsymoff
324 Write32(0); // nextrefsyms
325 Write32(IndirectSymbolOffset);
326 Write32(NumIndirectSymbols);
327 Write32(0); // extreloff
328 Write32(0); // nextrel
329 Write32(0); // locreloff
330 Write32(0); // nlocrel
331
332 assert(OS.tell() - Start == DysymtabLoadCommandSize);
333 }
334
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000335 void WriteNlist32(MachSymbolData &MSD) {
Daniel Dunbar5e835962009-08-26 02:48:04 +0000336 MCSymbolData &Data = *MSD.SymbolData;
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000337 const MCSymbol &Symbol = Data.getSymbol();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000338 uint8_t Type = 0;
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000339 uint16_t Flags = Data.getFlags();
340 uint32_t Address = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000341
342 // Set the N_TYPE bits. See <mach-o/nlist.h>.
343 //
344 // FIXME: Are the prebound or indirect fields possible here?
345 if (Symbol.isUndefined())
346 Type = STT_Undefined;
347 else if (Symbol.isAbsolute())
348 Type = STT_Absolute;
349 else
350 Type = STT_Section;
351
352 // FIXME: Set STAB bits.
353
Daniel Dunbar5e835962009-08-26 02:48:04 +0000354 if (Data.isPrivateExtern())
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000355 Type |= STF_PrivateExtern;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000356
357 // Set external bit.
Daniel Dunbar5e835962009-08-26 02:48:04 +0000358 if (Data.isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000359 Type |= STF_External;
360
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000361 // Compute the symbol address.
362 if (Symbol.isDefined()) {
363 if (Symbol.isAbsolute()) {
364 llvm_unreachable("FIXME: Not yet implemented!");
365 } else {
366 Address = Data.getFragment()->getAddress() + Data.getOffset();
367 }
368 } else if (Data.isCommon()) {
369 // Common symbols are encoded with the size in the address
370 // field, and their alignment in the flags.
371 Address = Data.getCommonSize();
372
373 // Common alignment is packed into the 'desc' bits.
374 if (unsigned Align = Data.getCommonAlignment()) {
375 unsigned Log2Size = Log2_32(Align);
376 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
377 if (Log2Size > 15)
378 llvm_report_error("invalid 'common' alignment '" +
379 Twine(Align) + "'");
380 // FIXME: Keep this mask with the SymbolFlags enumeration.
381 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
382 }
383 }
384
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000385 // struct nlist (12 bytes)
386
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000387 Write32(MSD.StringIndex);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000388 Write8(Type);
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000389 Write8(MSD.SectionIndex);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000390
Daniel Dunbar6aff2fb2009-08-24 08:40:12 +0000391 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
392 // value.
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000393 Write16(Flags);
Daniel Dunbar5e835962009-08-26 02:48:04 +0000394 Write32(Address);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000395 }
396
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000397 struct MachRelocationEntry {
398 uint32_t Word0;
399 uint32_t Word1;
400 };
401 void ComputeScatteredRelocationInfo(MCAssembler &Asm,
402 MCSectionData::Fixup &Fixup,
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000403 const MCValue &Target,
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000404 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
405 std::vector<MachRelocationEntry> &Relocs) {
406 uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
407 unsigned IsPCRel = 0;
408 unsigned Type = RIT_Vanilla;
409
410 // See <reloc.h>.
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000411 const MCSymbol *A = Target.getSymA();
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000412 MCSymbolData *SD = SymbolMap.lookup(A);
413 uint32_t Value = SD->getFragment()->getAddress() + SD->getOffset();
414 uint32_t Value2 = 0;
415
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000416 if (const MCSymbol *B = Target.getSymB()) {
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000417 Type = RIT_LocalDifference;
418
419 MCSymbolData *SD = SymbolMap.lookup(B);
420 Value2 = SD->getFragment()->getAddress() + SD->getOffset();
421 }
422
423 unsigned Log2Size = Log2_32(Fixup.Size);
424 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
425
426 // The value which goes in the fixup is current value of the expression.
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000427 Fixup.FixedValue = Value - Value2 + Target.getConstant();
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000428
429 MachRelocationEntry MRE;
430 MRE.Word0 = ((Address << 0) |
431 (Type << 24) |
432 (Log2Size << 28) |
433 (IsPCRel << 30) |
434 RF_Scattered);
435 MRE.Word1 = Value;
436 Relocs.push_back(MRE);
437
438 if (Type == RIT_LocalDifference) {
439 Type = RIT_Pair;
440
441 MachRelocationEntry MRE;
442 MRE.Word0 = ((0 << 0) |
443 (Type << 24) |
444 (Log2Size << 28) |
445 (0 << 30) |
446 RF_Scattered);
447 MRE.Word1 = Value2;
448 Relocs.push_back(MRE);
449 }
450 }
451
452 void ComputeRelocationInfo(MCAssembler &Asm,
453 MCSectionData::Fixup &Fixup,
454 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
455 std::vector<MachRelocationEntry> &Relocs) {
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000456 MCValue Target;
457 if (!Fixup.Value->EvaluateAsRelocatable(Target))
458 llvm_report_error("expected relocatable expression");
459
460 // If this is a difference or a local symbol plus an offset, then we need a
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000461 // scattered relocation entry.
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000462 if (Target.getSymB() ||
463 (Target.getSymA() && !Target.getSymA()->isUndefined() &&
464 Target.getConstant()))
465 return ComputeScatteredRelocationInfo(Asm, Fixup, Target,
466 SymbolMap, Relocs);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000467
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000468 // See <reloc.h>.
469 uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
470 uint32_t Value = 0;
471 unsigned Index = 0;
472 unsigned IsPCRel = 0;
473 unsigned IsExtern = 0;
474 unsigned Type = 0;
475
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000476 if (Target.isAbsolute()) { // constant
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000477 // SymbolNum of 0 indicates the absolute section.
478 Type = RIT_Vanilla;
479 Value = 0;
480 llvm_unreachable("FIXME: Not yet implemented!");
481 } else {
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000482 const MCSymbol *Symbol = Target.getSymA();
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000483 MCSymbolData *SD = SymbolMap.lookup(Symbol);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000484
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000485 if (Symbol->isUndefined()) {
486 IsExtern = 1;
487 Index = SD->getIndex();
488 Value = 0;
489 } else {
490 // The index is the section ordinal.
491 //
492 // FIXME: O(N)
493 Index = 1;
494 for (MCAssembler::iterator it = Asm.begin(),
495 ie = Asm.end(); it != ie; ++it, ++Index)
496 if (&*it == SD->getFragment()->getParent())
497 break;
498 Value = SD->getFragment()->getAddress() + SD->getOffset();
499 }
500
501 Type = RIT_Vanilla;
502 }
503
504 // The value which goes in the fixup is current value of the expression.
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000505 Fixup.FixedValue = Value + Target.getConstant();
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000506
507 unsigned Log2Size = Log2_32(Fixup.Size);
508 assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
509
510 // struct relocation_info (8 bytes)
511 MachRelocationEntry MRE;
512 MRE.Word0 = Address;
513 MRE.Word1 = ((Index << 0) |
514 (IsPCRel << 24) |
515 (Log2Size << 25) |
516 (IsExtern << 27) |
517 (Type << 28));
518 Relocs.push_back(MRE);
519 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000520
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000521 void BindIndirectSymbols(MCAssembler &Asm,
Daniel Dunbarbe963552009-08-26 13:57:54 +0000522 DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000523 // This is the point where 'as' creates actual symbols for indirect symbols
524 // (in the following two passes). It would be easier for us to do this
525 // sooner when we see the attribute, but that makes getting the order in the
526 // symbol table much more complicated than it is worth.
527 //
528 // FIXME: Revisit this when the dust settles.
529
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000530 // Bind non lazy symbol pointers first.
531 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
532 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
533 // FIXME: cast<> support!
534 const MCSectionMachO &Section =
535 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
536
537 unsigned Type =
538 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
539 if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
540 continue;
541
542 MCSymbolData *&Entry = SymbolMap[it->Symbol];
543 if (!Entry)
544 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
545 }
546
547 // Then lazy symbol pointers and symbol stubs.
548 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
549 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
550 // FIXME: cast<> support!
551 const MCSectionMachO &Section =
552 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
553
554 unsigned Type =
555 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
556 if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
557 Type != MCSectionMachO::S_SYMBOL_STUBS)
558 continue;
559
560 MCSymbolData *&Entry = SymbolMap[it->Symbol];
561 if (!Entry) {
562 Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
563
564 // Set the symbol type to undefined lazy, but only on construction.
565 //
566 // FIXME: Do not hardcode.
567 Entry->setFlags(Entry->getFlags() | 0x0001);
568 }
569 }
570 }
571
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000572 /// ComputeSymbolTable - Compute the symbol table data
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000573 ///
574 /// \param StringTable [out] - The string table data.
575 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
576 /// string table.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000577 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
578 std::vector<MachSymbolData> &LocalSymbolData,
579 std::vector<MachSymbolData> &ExternalSymbolData,
580 std::vector<MachSymbolData> &UndefinedSymbolData) {
581 // Build section lookup table.
582 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
583 unsigned Index = 1;
584 for (MCAssembler::iterator it = Asm.begin(),
585 ie = Asm.end(); it != ie; ++it, ++Index)
586 SectionIndexMap[&it->getSection()] = Index;
587 assert(Index <= 256 && "Too many sections!");
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000588
589 // Index 0 is always the empty string.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000590 StringMap<uint64_t> StringIndexMap;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000591 StringTable += '\x00';
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000592
593 // Build the symbol arrays and the string table, but only for non-local
594 // symbols.
595 //
596 // The particular order that we collect the symbols and create the string
597 // table, then sort the symbols is chosen to match 'as'. Even though it
598 // doesn't matter for correctness, this is important for letting us diff .o
599 // files.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000600 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
601 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000602 const MCSymbol &Symbol = it->getSymbol();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000603
Daniel Dunbar959fd882009-08-26 22:13:22 +0000604 // Ignore assembler temporaries.
605 if (it->getSymbol().isTemporary())
606 continue;
607
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000608 if (!it->isExternal() && !Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000609 continue;
610
611 uint64_t &Entry = StringIndexMap[Symbol.getName()];
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000612 if (!Entry) {
613 Entry = StringTable.size();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000614 StringTable += Symbol.getName();
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000615 StringTable += '\x00';
616 }
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000617
618 MachSymbolData MSD;
619 MSD.SymbolData = it;
620 MSD.StringIndex = Entry;
621
622 if (Symbol.isUndefined()) {
623 MSD.SectionIndex = 0;
624 UndefinedSymbolData.push_back(MSD);
625 } else if (Symbol.isAbsolute()) {
626 MSD.SectionIndex = 0;
627 ExternalSymbolData.push_back(MSD);
628 } else {
629 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
630 assert(MSD.SectionIndex && "Invalid section index!");
631 ExternalSymbolData.push_back(MSD);
632 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000633 }
634
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000635 // Now add the data for local symbols.
636 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
637 ie = Asm.symbol_end(); it != ie; ++it) {
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000638 const MCSymbol &Symbol = it->getSymbol();
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000639
Daniel Dunbar959fd882009-08-26 22:13:22 +0000640 // Ignore assembler temporaries.
641 if (it->getSymbol().isTemporary())
642 continue;
643
Daniel Dunbar50e48b32009-08-24 08:39:57 +0000644 if (it->isExternal() || Symbol.isUndefined())
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000645 continue;
646
647 uint64_t &Entry = StringIndexMap[Symbol.getName()];
648 if (!Entry) {
649 Entry = StringTable.size();
650 StringTable += Symbol.getName();
651 StringTable += '\x00';
652 }
653
654 MachSymbolData MSD;
655 MSD.SymbolData = it;
656 MSD.StringIndex = Entry;
657
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000658 if (Symbol.isAbsolute()) {
659 MSD.SectionIndex = 0;
660 LocalSymbolData.push_back(MSD);
661 } else {
662 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
663 assert(MSD.SectionIndex && "Invalid section index!");
664 LocalSymbolData.push_back(MSD);
665 }
666 }
667
668 // External and undefined symbols are required to be in lexicographic order.
669 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
670 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
671
Daniel Dunbarbe963552009-08-26 13:57:54 +0000672 // Set the symbol indices.
673 Index = 0;
674 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
675 LocalSymbolData[i].SymbolData->setIndex(Index++);
676 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
677 ExternalSymbolData[i].SymbolData->setIndex(Index++);
678 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
679 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
680
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000681 // The string table is padded to a multiple of 4.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000682 while (StringTable.size() % 4)
683 StringTable += '\x00';
684 }
685
686 void WriteObject(MCAssembler &Asm) {
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000687 unsigned NumSections = Asm.size();
688
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000689 // Compute the symbol -> symbol data map.
690 //
691 // FIXME: This should not be here.
Daniel Dunbarbe963552009-08-26 13:57:54 +0000692 DenseMap<const MCSymbol*, MCSymbolData *> SymbolMap;
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000693 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
694 ie = Asm.symbol_end(); it != ie; ++it)
695 SymbolMap[&it->getSymbol()] = it;
696
697 // Create symbol data for any indirect symbols.
698 BindIndirectSymbols(Asm, SymbolMap);
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000699
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000700 // Compute symbol table information.
701 SmallString<256> StringTable;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000702 std::vector<MachSymbolData> LocalSymbolData;
703 std::vector<MachSymbolData> ExternalSymbolData;
704 std::vector<MachSymbolData> UndefinedSymbolData;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000705 unsigned NumSymbols = Asm.symbol_size();
706
707 // No symbol table command is written if there are no symbols.
708 if (NumSymbols)
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000709 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
710 UndefinedSymbolData);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000711
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000712 // The section data starts after the header, the segment load command (and
713 // section headers) and the symbol table.
714 unsigned NumLoadCommands = 1;
715 uint64_t LoadCommandsSize =
716 SegmentLoadCommand32Size + NumSections * Section32Size;
717
718 // Add the symbol table load command sizes, if used.
719 if (NumSymbols) {
720 NumLoadCommands += 2;
721 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
722 }
723
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000724 // Compute the total size of the section data, as well as its file size and
725 // vm size.
Daniel Dunbar6742e342009-08-26 04:13:32 +0000726 uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000727 uint64_t SectionDataSize = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000728 uint64_t SectionDataFileSize = 0;
729 uint64_t VMSize = 0;
730 for (MCAssembler::iterator it = Asm.begin(),
731 ie = Asm.end(); it != ie; ++it) {
732 MCSectionData &SD = *it;
733
734 VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
735
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000736 if (isVirtualSection(SD.getSection()))
737 continue;
738
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000739 SectionDataSize = std::max(SectionDataSize,
740 SD.getAddress() + SD.getSize());
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000741 SectionDataFileSize = std::max(SectionDataFileSize,
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000742 SD.getAddress() + SD.getFileSize());
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000743 }
744
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000745 // The section data is passed to 4 bytes.
746 //
747 // FIXME: Is this machine dependent?
748 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
749 SectionDataFileSize += SectionDataPadding;
750
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000751 // Write the prolog, starting with the header and load command...
Daniel Dunbar6009db42009-08-26 21:22:22 +0000752 WriteHeader32(NumLoadCommands, LoadCommandsSize,
753 Asm.getSubsectionsViaSymbols());
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000754 WriteSegmentLoadCommand32(NumSections, VMSize,
755 SectionDataStart, SectionDataSize);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000756
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000757 // ... and then the section headers.
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000758 //
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000759 // We also compute the section relocations while we do this. Note that
760 // compute relocation info will also update the fixup to have the correct
761 // value; this will be overwrite the appropriate data in the fragment when
762 // it is written.
763 std::vector<MachRelocationEntry> RelocInfos;
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000764 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000765 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie;
766 ++it) {
767 MCSectionData &SD = *it;
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000768
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000769 // The assembler writes relocations in the reverse order they were seen.
770 //
771 // FIXME: It is probably more complicated than this.
772 unsigned NumRelocsStart = RelocInfos.size();
773 for (unsigned i = 0, e = SD.fixup_size(); i != e; ++i)
774 ComputeRelocationInfo(Asm, SD.getFixups()[e - i - 1], SymbolMap,
775 RelocInfos);
776
777 unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
778 uint64_t SectionStart = SectionDataStart + SD.getAddress();
779 WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
780 RelocTableEnd += NumRelocs * RelocationInfoSize;
781 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000782
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000783 // Write the symbol table load command, if used.
784 if (NumSymbols) {
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000785 unsigned FirstLocalSymbol = 0;
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000786 unsigned NumLocalSymbols = LocalSymbolData.size();
787 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
788 unsigned NumExternalSymbols = ExternalSymbolData.size();
789 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
790 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000791 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
792 unsigned NumSymTabSymbols =
793 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
794 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
795 uint64_t IndirectSymbolOffset = 0;
796
797 // If used, the indirect symbols are written after the section data.
798 if (NumIndirectSymbols)
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000799 IndirectSymbolOffset = RelocTableEnd;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000800
801 // The symbol table is written after the indirect symbol data.
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000802 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000803
804 // The string table is written after symbol table.
805 uint64_t StringTableOffset =
806 SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
807 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
808 StringTableOffset, StringTable.size());
809
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000810 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
811 FirstExternalSymbol, NumExternalSymbols,
812 FirstUndefinedSymbol, NumUndefinedSymbols,
813 IndirectSymbolOffset, NumIndirectSymbols);
814 }
815
816 // Write the actual section data.
817 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
818 WriteFileData(OS, *it, *this);
819
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000820 // Write the extra padding.
821 WriteZeros(SectionDataPadding);
822
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000823 // Write the relocation entries.
824 for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
825 Write32(RelocInfos[i].Word0);
826 Write32(RelocInfos[i].Word1);
827 }
828
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000829 // Write the symbol table data, if used.
830 if (NumSymbols) {
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000831 // Write the indirect symbol entries.
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000832 for (MCAssembler::indirect_symbol_iterator
833 it = Asm.indirect_symbol_begin(),
834 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
835 // Indirect symbols in the non lazy symbol pointer section have some
836 // special handling.
837 const MCSectionMachO &Section =
838 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
839 unsigned Type =
840 Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
841 if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
842 // If this symbol is defined and internal, mark it as such.
843 if (it->Symbol->isDefined() &&
844 !SymbolMap.lookup(it->Symbol)->isExternal()) {
845 uint32_t Flags = ISF_Local;
846 if (it->Symbol->isAbsolute())
847 Flags |= ISF_Absolute;
848 Write32(Flags);
849 continue;
850 }
851 }
852
Daniel Dunbarbe963552009-08-26 13:57:54 +0000853 Write32(SymbolMap[it->Symbol]->getIndex());
Daniel Dunbarad7c3d52009-08-26 00:18:21 +0000854 }
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000855
Daniel Dunbar0c7761b2009-08-24 11:56:58 +0000856 // FIXME: Check that offsets match computed ones.
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000857
858 // Write the symbol table entries.
Daniel Dunbar3edd9bb2009-08-22 11:41:10 +0000859 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
860 WriteNlist32(LocalSymbolData[i]);
861 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
862 WriteNlist32(ExternalSymbolData[i]);
863 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
864 WriteNlist32(UndefinedSymbolData[i]);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000865
866 // Write the string table.
867 OS << StringTable.str();
868 }
Daniel Dunbar2ae58f22009-08-22 08:28:27 +0000869 }
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000870};
871
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000872/* *** */
873
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000874MCFragment::MCFragment() : Kind(FragmentType(~0)) {
875}
876
Daniel Dunbar5e835962009-08-26 02:48:04 +0000877MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000878 : Kind(_Kind),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000879 Parent(_Parent),
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000880 FileSize(~UINT64_C(0))
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000881{
Daniel Dunbar5e835962009-08-26 02:48:04 +0000882 if (Parent)
883 Parent->getFragmentList().push_back(this);
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000884}
885
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000886MCFragment::~MCFragment() {
887}
888
Daniel Dunbar5e835962009-08-26 02:48:04 +0000889uint64_t MCFragment::getAddress() const {
890 assert(getParent() && "Missing Section!");
891 return getParent()->getAddress() + Offset;
892}
893
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000894/* *** */
895
Daniel Dunbar81e40002009-08-27 00:38:04 +0000896MCSectionData::MCSectionData() : Section(0) {}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000897
898MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
Daniel Dunbar81e40002009-08-27 00:38:04 +0000899 : Section(&_Section),
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000900 Alignment(1),
Daniel Dunbar5e835962009-08-26 02:48:04 +0000901 Address(~UINT64_C(0)),
Daniel Dunbar6742e342009-08-26 04:13:32 +0000902 Size(~UINT64_C(0)),
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000903 FileSize(~UINT64_C(0)),
904 LastFixupLookup(~0)
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000905{
906 if (A)
907 A->getSectionList().push_back(this);
908}
909
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000910const MCSectionData::Fixup *
911MCSectionData::LookupFixup(const MCFragment *Fragment, uint64_t Offset) const {
912 // Use a one level cache to turn the common case of accessing the fixups in
913 // order into O(1) instead of O(N).
914 unsigned i = LastFixupLookup, Count = Fixups.size(), End = Fixups.size();
915 if (i >= End)
916 i = 0;
917 while (Count--) {
918 const Fixup &F = Fixups[i];
919 if (F.Fragment == Fragment && F.Offset == Offset) {
920 LastFixupLookup = i;
921 return &F;
922 }
923
924 ++i;
925 if (i == End)
926 i = 0;
927 }
928
929 return 0;
930}
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000931
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000932/* *** */
933
Daniel Dunbarefbb5332009-09-01 04:09:03 +0000934MCSymbolData::MCSymbolData() : Symbol(0) {}
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000935
Daniel Dunbarcb579b32009-08-31 08:08:06 +0000936MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000937 uint64_t _Offset, MCAssembler *A)
Daniel Dunbarefbb5332009-09-01 04:09:03 +0000938 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
Daniel Dunbar8f4d1462009-08-28 07:08:35 +0000939 IsExternal(false), IsPrivateExtern(false),
940 CommonSize(0), CommonAlign(0), Flags(0), Index(0)
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +0000941{
942 if (A)
943 A->getSymbolList().push_back(this);
944}
945
946/* *** */
947
Daniel Dunbara03a3682009-08-31 08:07:55 +0000948MCAssembler::MCAssembler(MCContext &_Context, raw_ostream &_OS)
949 : Context(_Context), OS(_OS), SubsectionsViaSymbols(false)
Daniel Dunbar6009db42009-08-26 21:22:22 +0000950{
951}
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +0000952
953MCAssembler::~MCAssembler() {
954}
955
Daniel Dunbaredc670f2009-08-28 05:49:04 +0000956void MCAssembler::LayoutSection(MCSectionData &SD) {
Daniel Dunbar6742e342009-08-26 04:13:32 +0000957 uint64_t Address = SD.getAddress();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +0000958
959 for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
960 MCFragment &F = *it;
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000961
Daniel Dunbar6742e342009-08-26 04:13:32 +0000962 F.setOffset(Address - SD.getAddress());
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000963
964 // Evaluate fragment size.
965 switch (F.getKind()) {
966 case MCFragment::FT_Align: {
967 MCAlignFragment &AF = cast<MCAlignFragment>(F);
Daniel Dunbar7eb85192009-10-16 01:58:15 +0000968
Daniel Dunbard5a8e982009-08-28 05:49:21 +0000969 uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
Daniel Dunbar6742e342009-08-26 04:13:32 +0000970 if (Size > AF.getMaxBytesToEmit())
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000971 AF.setFileSize(0);
972 else
Daniel Dunbar6742e342009-08-26 04:13:32 +0000973 AF.setFileSize(Size);
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000974 break;
975 }
976
977 case MCFragment::FT_Data:
Daniel Dunbard6f761e2009-08-21 23:07:38 +0000978 F.setFileSize(F.getMaxFileSize());
979 break;
980
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000981 case MCFragment::FT_Fill: {
982 MCFillFragment &FF = cast<MCFillFragment>(F);
983
984 F.setFileSize(F.getMaxFileSize());
985
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000986 MCValue Target;
987 if (!FF.getValue().EvaluateAsRelocatable(Target))
988 llvm_report_error("expected relocatable expression");
989
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000990 // If the fill value is constant, thats it.
Daniel Dunbar1253a6f2009-10-16 01:58:03 +0000991 if (Target.isAbsolute())
Daniel Dunbar3f6a9602009-08-26 13:58:10 +0000992 break;
993
994 // Otherwise, add fixups for the values.
995 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
996 MCSectionData::Fixup Fix(F, i * FF.getValueSize(),
997 FF.getValue(),FF.getValueSize());
998 SD.getFixups().push_back(Fix);
999 }
1000 break;
1001 }
1002
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001003 case MCFragment::FT_Org: {
1004 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1005
Daniel Dunbar1253a6f2009-10-16 01:58:03 +00001006 MCValue Target;
1007 if (!OF.getOffset().EvaluateAsRelocatable(Target))
1008 llvm_report_error("expected relocatable expression");
1009
1010 if (!Target.isAbsolute())
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001011 llvm_unreachable("FIXME: Not yet implemented!");
Daniel Dunbar1253a6f2009-10-16 01:58:03 +00001012 uint64_t OrgOffset = Target.getConstant();
Daniel Dunbar6742e342009-08-26 04:13:32 +00001013 uint64_t Offset = Address - SD.getAddress();
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001014
1015 // FIXME: We need a way to communicate this error.
Daniel Dunbara5441fe2009-08-22 08:27:54 +00001016 if (OrgOffset < Offset)
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001017 llvm_report_error("invalid .org offset '" + Twine(OrgOffset) +
Daniel Dunbar6742e342009-08-26 04:13:32 +00001018 "' (at offset '" + Twine(Offset) + "'");
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001019
Daniel Dunbara5441fe2009-08-22 08:27:54 +00001020 F.setFileSize(OrgOffset - Offset);
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001021 break;
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001022 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001023
1024 case MCFragment::FT_ZeroFill: {
1025 MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1026
1027 // Align the fragment offset; it is safe to adjust the offset freely since
1028 // this is only in virtual sections.
1029 uint64_t Aligned = RoundUpToAlignment(Address, ZFF.getAlignment());
1030 F.setOffset(Aligned - SD.getAddress());
1031
1032 // FIXME: This is misnamed.
1033 F.setFileSize(ZFF.getSize());
1034 break;
1035 }
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001036 }
1037
Daniel Dunbar6742e342009-08-26 04:13:32 +00001038 Address += F.getFileSize();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001039 }
1040
Daniel Dunbar6742e342009-08-26 04:13:32 +00001041 // Set the section sizes.
1042 SD.setSize(Address - SD.getAddress());
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001043 if (isVirtualSection(SD.getSection()))
1044 SD.setFileSize(0);
1045 else
1046 SD.setFileSize(Address - SD.getAddress());
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001047}
1048
1049/// WriteFileData - Write the \arg F data to the output file.
1050static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1051 MachObjectWriter &MOW) {
1052 uint64_t Start = OS.tell();
1053 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001054
Daniel Dunbar0adcd352009-08-25 21:10:45 +00001055 ++EmittedFragments;
1056
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001057 // FIXME: Embed in fragments instead?
1058 switch (F.getKind()) {
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001059 case MCFragment::FT_Align: {
1060 MCAlignFragment &AF = cast<MCAlignFragment>(F);
1061 uint64_t Count = AF.getFileSize() / AF.getValueSize();
1062
1063 // FIXME: This error shouldn't actually occur (the front end should emit
1064 // multiple .align directives to enforce the semantics it wants), but is
1065 // severe enough that we want to report it. How to handle this?
1066 if (Count * AF.getValueSize() != AF.getFileSize())
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001067 llvm_report_error("undefined .align directive, value size '" +
1068 Twine(AF.getValueSize()) +
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001069 "' is not a divisor of padding size '" +
1070 Twine(AF.getFileSize()) + "'");
1071
1072 for (uint64_t i = 0; i != Count; ++i) {
1073 switch (AF.getValueSize()) {
1074 default:
1075 assert(0 && "Invalid size!");
1076 case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1077 case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1078 case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1079 case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1080 }
1081 }
1082 break;
1083 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001084
1085 case MCFragment::FT_Data:
1086 OS << cast<MCDataFragment>(F).getContents().str();
1087 break;
1088
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001089 case MCFragment::FT_Fill: {
1090 MCFillFragment &FF = cast<MCFillFragment>(F);
1091
Daniel Dunbar3f6a9602009-08-26 13:58:10 +00001092 int64_t Value = 0;
Daniel Dunbar1253a6f2009-10-16 01:58:03 +00001093
1094 MCValue Target;
1095 if (!FF.getValue().EvaluateAsRelocatable(Target))
1096 llvm_report_error("expected relocatable expression");
1097
1098 if (Target.isAbsolute())
1099 Value = Target.getConstant();
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001100 for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
Daniel Dunbar1253a6f2009-10-16 01:58:03 +00001101 if (!Target.isAbsolute()) {
Daniel Dunbar3f6a9602009-08-26 13:58:10 +00001102 // Find the fixup.
1103 //
1104 // FIXME: Find a better way to write in the fixes.
1105 const MCSectionData::Fixup *Fixup =
1106 F.getParent()->LookupFixup(&F, i * FF.getValueSize());
1107 assert(Fixup && "Missing fixup for fill value!");
1108 Value = Fixup->FixedValue;
1109 }
1110
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001111 switch (FF.getValueSize()) {
1112 default:
1113 assert(0 && "Invalid size!");
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001114 case 1: MOW.Write8 (uint8_t (Value)); break;
1115 case 2: MOW.Write16(uint16_t(Value)); break;
1116 case 4: MOW.Write32(uint32_t(Value)); break;
1117 case 8: MOW.Write64(uint64_t(Value)); break;
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001118 }
1119 }
1120 break;
1121 }
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001122
Daniel Dunbard6f761e2009-08-21 23:07:38 +00001123 case MCFragment::FT_Org: {
1124 MCOrgFragment &OF = cast<MCOrgFragment>(F);
1125
1126 for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1127 MOW.Write8(uint8_t(OF.getValue()));
1128
1129 break;
1130 }
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001131
1132 case MCFragment::FT_ZeroFill: {
1133 assert(0 && "Invalid zero fill fragment in concrete section!");
1134 break;
1135 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001136 }
1137
1138 assert(OS.tell() - Start == F.getFileSize());
1139}
1140
1141/// WriteFileData - Write the \arg SD data to the output file.
1142static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1143 MachObjectWriter &MOW) {
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001144 // Ignore virtual sections.
1145 if (isVirtualSection(SD.getSection())) {
1146 assert(SD.getFileSize() == 0);
1147 return;
1148 }
1149
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001150 uint64_t Start = OS.tell();
1151 (void) Start;
Daniel Dunbar7eb85192009-10-16 01:58:15 +00001152
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001153 for (MCSectionData::const_iterator it = SD.begin(),
1154 ie = SD.end(); it != ie; ++it)
1155 WriteFileData(OS, *it, MOW);
1156
Daniel Dunbar6742e342009-08-26 04:13:32 +00001157 // Add section padding.
1158 assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1159 MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1160
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001161 assert(OS.tell() - Start == SD.getFileSize());
1162}
1163
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001164void MCAssembler::Finish() {
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001165 // Layout the concrete sections and fragments.
Daniel Dunbar5e835962009-08-26 02:48:04 +00001166 uint64_t Address = 0;
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001167 MCSectionData *Prev = 0;
1168 for (iterator it = begin(), ie = end(); it != ie; ++it) {
Daniel Dunbar6742e342009-08-26 04:13:32 +00001169 MCSectionData &SD = *it;
1170
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001171 // Skip virtual sections.
1172 if (isVirtualSection(SD.getSection()))
1173 continue;
1174
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001175 // Align this section if necessary by adding padding bytes to the previous
1176 // section.
1177 if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1178 assert(Prev && "Missing prev section!");
1179 Prev->setFileSize(Prev->getFileSize() + Pad);
1180 Address += Pad;
1181 }
Daniel Dunbar6742e342009-08-26 04:13:32 +00001182
1183 // Layout the section fragments and its size.
1184 SD.setAddress(Address);
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001185 LayoutSection(SD);
Daniel Dunbar6742e342009-08-26 04:13:32 +00001186 Address += SD.getFileSize();
Daniel Dunbaredc670f2009-08-28 05:49:04 +00001187
1188 Prev = &SD;
Daniel Dunbar5e835962009-08-26 02:48:04 +00001189 }
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001190
Daniel Dunbard5a8e982009-08-28 05:49:21 +00001191 // Layout the virtual sections.
1192 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1193 MCSectionData &SD = *it;
1194
1195 if (!isVirtualSection(SD.getSection()))
1196 continue;
1197
1198 SD.setAddress(Address);
1199 LayoutSection(SD);
1200 Address += SD.getSize();
1201 }
1202
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +00001203 // Write the object file.
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001204 MachObjectWriter MOW(OS);
Daniel Dunbarf3d2ef02009-08-22 10:13:24 +00001205 MOW.WriteObject(*this);
Daniel Dunbar0705fbf2009-08-21 18:29:01 +00001206
Daniel Dunbarfb4a6b32009-08-21 09:11:24 +00001207 OS.flush();
1208}