blob: 9bcb93e14716c394d3ef8afa3e4aafe0f5565097 [file] [log] [blame]
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001//===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
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
10#include "llvm/MC/MachObjectWriter.h"
11#include "llvm/ADT/StringMap.h"
12#include "llvm/ADT/Twine.h"
13#include "llvm/MC/MCAssembler.h"
Daniel Dunbar207e06e2010-03-24 03:43:40 +000014#include "llvm/MC/MCAsmLayout.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000015#include "llvm/MC/MCExpr.h"
16#include "llvm/MC/MCObjectWriter.h"
17#include "llvm/MC/MCSectionMachO.h"
18#include "llvm/MC/MCSymbol.h"
Kevin Enderbya6eeb6e2010-05-07 21:44:23 +000019#include "llvm/MC/MCMachOSymbolFlags.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000020#include "llvm/MC/MCValue.h"
21#include "llvm/Support/ErrorHandling.h"
22#include "llvm/Support/MachO.h"
23#include "llvm/Target/TargetAsmBackend.h"
24
25// FIXME: Gross.
26#include "../Target/X86/X86FixupKinds.h"
27
28#include <vector>
29using namespace llvm;
30
31static unsigned getFixupKindLog2Size(unsigned Kind) {
32 switch (Kind) {
33 default: llvm_unreachable("invalid fixup kind!");
34 case X86::reloc_pcrel_1byte:
35 case FK_Data_1: return 0;
36 case FK_Data_2: return 1;
37 case X86::reloc_pcrel_4byte:
38 case X86::reloc_riprel_4byte:
Daniel Dunbar602b40f2010-03-19 18:07:55 +000039 case X86::reloc_riprel_4byte_movq_load:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000040 case FK_Data_4: return 2;
41 case FK_Data_8: return 3;
42 }
43}
44
45static bool isFixupKindPCRel(unsigned Kind) {
46 switch (Kind) {
47 default:
48 return false;
49 case X86::reloc_pcrel_1byte:
50 case X86::reloc_pcrel_4byte:
51 case X86::reloc_riprel_4byte:
Daniel Dunbar602b40f2010-03-19 18:07:55 +000052 case X86::reloc_riprel_4byte_movq_load:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000053 return true;
54 }
55}
56
Daniel Dunbar602b40f2010-03-19 18:07:55 +000057static bool isFixupKindRIPRel(unsigned Kind) {
58 return Kind == X86::reloc_riprel_4byte ||
59 Kind == X86::reloc_riprel_4byte_movq_load;
60}
61
Daniel Dunbare9460ec2010-05-10 23:15:13 +000062static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
63 // Undefined symbols are always extern.
64 if (SD->Symbol->isUndefined())
65 return true;
66
67 // References to weak definitions require external relocation entries; the
68 // definition may not always be the one in the same object file.
69 if (SD->getFlags() & SF_WeakDefinition)
70 return true;
71
72 // Otherwise, we can use an internal relocation.
73 return false;
74}
75
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000076namespace {
77
78class MachObjectWriterImpl {
79 // See <mach-o/loader.h>.
80 enum {
81 Header_Magic32 = 0xFEEDFACE,
82 Header_Magic64 = 0xFEEDFACF
83 };
84
85 enum {
86 Header32Size = 28,
87 Header64Size = 32,
88 SegmentLoadCommand32Size = 56,
89 SegmentLoadCommand64Size = 72,
90 Section32Size = 68,
91 Section64Size = 80,
92 SymtabLoadCommandSize = 24,
93 DysymtabLoadCommandSize = 80,
94 Nlist32Size = 12,
95 Nlist64Size = 16,
96 RelocationInfoSize = 8
97 };
98
99 enum HeaderFileType {
100 HFT_Object = 0x1
101 };
102
103 enum HeaderFlags {
104 HF_SubsectionsViaSymbols = 0x2000
105 };
106
107 enum LoadCommandType {
108 LCT_Segment = 0x1,
109 LCT_Symtab = 0x2,
110 LCT_Dysymtab = 0xb,
111 LCT_Segment64 = 0x19
112 };
113
114 // See <mach-o/nlist.h>.
115 enum SymbolTypeType {
116 STT_Undefined = 0x00,
117 STT_Absolute = 0x02,
118 STT_Section = 0x0e
119 };
120
121 enum SymbolTypeFlags {
122 // If any of these bits are set, then the entry is a stab entry number (see
123 // <mach-o/stab.h>. Otherwise the other masks apply.
124 STF_StabsEntryMask = 0xe0,
125
126 STF_TypeMask = 0x0e,
127 STF_External = 0x01,
128 STF_PrivateExtern = 0x10
129 };
130
131 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
132 /// symbol entry.
133 enum IndirectSymbolFlags {
134 ISF_Local = 0x80000000,
135 ISF_Absolute = 0x40000000
136 };
137
138 /// RelocationFlags - Special flags for addresses.
139 enum RelocationFlags {
140 RF_Scattered = 0x80000000
141 };
142
143 enum RelocationInfoType {
144 RIT_Vanilla = 0,
145 RIT_Pair = 1,
146 RIT_Difference = 2,
147 RIT_PreboundLazyPointer = 3,
148 RIT_LocalDifference = 4
149 };
150
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000151 /// X86_64 uses its own relocation types.
152 enum RelocationInfoTypeX86_64 {
153 RIT_X86_64_Unsigned = 0,
154 RIT_X86_64_Signed = 1,
155 RIT_X86_64_Branch = 2,
156 RIT_X86_64_GOTLoad = 3,
157 RIT_X86_64_GOT = 4,
158 RIT_X86_64_Subtractor = 5,
159 RIT_X86_64_Signed1 = 6,
160 RIT_X86_64_Signed2 = 7,
161 RIT_X86_64_Signed4 = 8
162 };
163
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000164 /// MachSymbolData - Helper struct for containing some precomputed information
165 /// on symbols.
166 struct MachSymbolData {
167 MCSymbolData *SymbolData;
168 uint64_t StringIndex;
169 uint8_t SectionIndex;
170
171 // Support lexicographic sorting.
172 bool operator<(const MachSymbolData &RHS) const {
Benjamin Kramerc37791e2010-05-20 14:14:22 +0000173 return SymbolData->getSymbol().getName() <
174 RHS.SymbolData->getSymbol().getName();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000175 }
176 };
177
178 /// @name Relocation Data
179 /// @{
180
181 struct MachRelocationEntry {
182 uint32_t Word0;
183 uint32_t Word1;
184 };
185
186 llvm::DenseMap<const MCSectionData*,
187 std::vector<MachRelocationEntry> > Relocations;
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000188 llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000189
190 /// @}
191 /// @name Symbol Table Data
192 /// @{
193
194 SmallString<256> StringTable;
195 std::vector<MachSymbolData> LocalSymbolData;
196 std::vector<MachSymbolData> ExternalSymbolData;
197 std::vector<MachSymbolData> UndefinedSymbolData;
198
199 /// @}
200
201 MachObjectWriter *Writer;
202
203 raw_ostream &OS;
204
205 unsigned Is64Bit : 1;
206
207public:
208 MachObjectWriterImpl(MachObjectWriter *_Writer, bool _Is64Bit)
209 : Writer(_Writer), OS(Writer->getStream()), Is64Bit(_Is64Bit) {
210 }
211
212 void Write8(uint8_t Value) { Writer->Write8(Value); }
213 void Write16(uint16_t Value) { Writer->Write16(Value); }
214 void Write32(uint32_t Value) { Writer->Write32(Value); }
215 void Write64(uint64_t Value) { Writer->Write64(Value); }
216 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
217 void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
218 Writer->WriteBytes(Str, ZeroFillSize);
219 }
220
221 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
222 bool SubsectionsViaSymbols) {
223 uint32_t Flags = 0;
224
225 if (SubsectionsViaSymbols)
226 Flags |= HF_SubsectionsViaSymbols;
227
228 // struct mach_header (28 bytes) or
229 // struct mach_header_64 (32 bytes)
230
231 uint64_t Start = OS.tell();
232 (void) Start;
233
234 Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
235
236 // FIXME: Support cputype.
237 Write32(Is64Bit ? MachO::CPUTypeX86_64 : MachO::CPUTypeI386);
238 // FIXME: Support cpusubtype.
239 Write32(MachO::CPUSubType_I386_ALL);
240 Write32(HFT_Object);
241 Write32(NumLoadCommands); // Object files have a single load command, the
242 // segment.
243 Write32(LoadCommandsSize);
244 Write32(Flags);
245 if (Is64Bit)
246 Write32(0); // reserved
247
248 assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
249 }
250
251 /// WriteSegmentLoadCommand - Write a segment load command.
252 ///
253 /// \arg NumSections - The number of sections in this segment.
254 /// \arg SectionDataSize - The total size of the sections.
255 void WriteSegmentLoadCommand(unsigned NumSections,
256 uint64_t VMSize,
257 uint64_t SectionDataStartOffset,
258 uint64_t SectionDataSize) {
259 // struct segment_command (56 bytes) or
260 // struct segment_command_64 (72 bytes)
261
262 uint64_t Start = OS.tell();
263 (void) Start;
264
265 unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
266 SegmentLoadCommand32Size;
267 Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
268 Write32(SegmentLoadCommandSize +
269 NumSections * (Is64Bit ? Section64Size : Section32Size));
270
271 WriteBytes("", 16);
272 if (Is64Bit) {
273 Write64(0); // vmaddr
274 Write64(VMSize); // vmsize
275 Write64(SectionDataStartOffset); // file offset
276 Write64(SectionDataSize); // file size
277 } else {
278 Write32(0); // vmaddr
279 Write32(VMSize); // vmsize
280 Write32(SectionDataStartOffset); // file offset
281 Write32(SectionDataSize); // file size
282 }
283 Write32(0x7); // maxprot
284 Write32(0x7); // initprot
285 Write32(NumSections);
286 Write32(0); // flags
287
288 assert(OS.tell() - Start == SegmentLoadCommandSize);
289 }
290
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000291 void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
292 const MCSectionData &SD, uint64_t FileOffset,
293 uint64_t RelocationsStart, unsigned NumRelocations) {
Daniel Dunbar5d428512010-03-25 02:00:07 +0000294 uint64_t SectionSize = Layout.getSectionSize(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +0000295
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000296 // The offset is unused for virtual sections.
297 if (Asm.getBackend().isVirtualSection(SD.getSection())) {
Daniel Dunbarb026d642010-03-25 07:10:05 +0000298 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000299 FileOffset = 0;
300 }
301
302 // struct section (68 bytes) or
303 // struct section_64 (80 bytes)
304
305 uint64_t Start = OS.tell();
306 (void) Start;
307
Daniel Dunbar56279f42010-05-18 17:28:20 +0000308 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000309 WriteBytes(Section.getSectionName(), 16);
310 WriteBytes(Section.getSegmentName(), 16);
311 if (Is64Bit) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000312 Write64(Layout.getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000313 Write64(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000314 } else {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000315 Write32(Layout.getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000316 Write32(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000317 }
318 Write32(FileOffset);
319
320 unsigned Flags = Section.getTypeAndAttributes();
321 if (SD.hasInstructions())
322 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
323
324 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
325 Write32(Log2_32(SD.getAlignment()));
326 Write32(NumRelocations ? RelocationsStart : 0);
327 Write32(NumRelocations);
328 Write32(Flags);
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000329 Write32(IndirectSymBase.lookup(&SD)); // reserved1
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000330 Write32(Section.getStubSize()); // reserved2
331 if (Is64Bit)
332 Write32(0); // reserved3
333
334 assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
335 }
336
337 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
338 uint32_t StringTableOffset,
339 uint32_t StringTableSize) {
340 // struct symtab_command (24 bytes)
341
342 uint64_t Start = OS.tell();
343 (void) Start;
344
345 Write32(LCT_Symtab);
346 Write32(SymtabLoadCommandSize);
347 Write32(SymbolOffset);
348 Write32(NumSymbols);
349 Write32(StringTableOffset);
350 Write32(StringTableSize);
351
352 assert(OS.tell() - Start == SymtabLoadCommandSize);
353 }
354
355 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
356 uint32_t NumLocalSymbols,
357 uint32_t FirstExternalSymbol,
358 uint32_t NumExternalSymbols,
359 uint32_t FirstUndefinedSymbol,
360 uint32_t NumUndefinedSymbols,
361 uint32_t IndirectSymbolOffset,
362 uint32_t NumIndirectSymbols) {
363 // struct dysymtab_command (80 bytes)
364
365 uint64_t Start = OS.tell();
366 (void) Start;
367
368 Write32(LCT_Dysymtab);
369 Write32(DysymtabLoadCommandSize);
370 Write32(FirstLocalSymbol);
371 Write32(NumLocalSymbols);
372 Write32(FirstExternalSymbol);
373 Write32(NumExternalSymbols);
374 Write32(FirstUndefinedSymbol);
375 Write32(NumUndefinedSymbols);
376 Write32(0); // tocoff
377 Write32(0); // ntoc
378 Write32(0); // modtaboff
379 Write32(0); // nmodtab
380 Write32(0); // extrefsymoff
381 Write32(0); // nextrefsyms
382 Write32(IndirectSymbolOffset);
383 Write32(NumIndirectSymbols);
384 Write32(0); // extreloff
385 Write32(0); // nextrel
386 Write32(0); // locreloff
387 Write32(0); // nlocrel
388
389 assert(OS.tell() - Start == DysymtabLoadCommandSize);
390 }
391
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000392 void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000393 MCSymbolData &Data = *MSD.SymbolData;
394 const MCSymbol &Symbol = Data.getSymbol();
395 uint8_t Type = 0;
396 uint16_t Flags = Data.getFlags();
397 uint32_t Address = 0;
398
399 // Set the N_TYPE bits. See <mach-o/nlist.h>.
400 //
401 // FIXME: Are the prebound or indirect fields possible here?
402 if (Symbol.isUndefined())
403 Type = STT_Undefined;
404 else if (Symbol.isAbsolute())
405 Type = STT_Absolute;
406 else
407 Type = STT_Section;
408
409 // FIXME: Set STAB bits.
410
411 if (Data.isPrivateExtern())
412 Type |= STF_PrivateExtern;
413
414 // Set external bit.
415 if (Data.isExternal() || Symbol.isUndefined())
416 Type |= STF_External;
417
418 // Compute the symbol address.
419 if (Symbol.isDefined()) {
420 if (Symbol.isAbsolute()) {
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000421 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000422 } else {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000423 Address = Layout.getSymbolAddress(&Data);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000424 }
425 } else if (Data.isCommon()) {
426 // Common symbols are encoded with the size in the address
427 // field, and their alignment in the flags.
428 Address = Data.getCommonSize();
429
430 // Common alignment is packed into the 'desc' bits.
431 if (unsigned Align = Data.getCommonAlignment()) {
432 unsigned Log2Size = Log2_32(Align);
433 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
434 if (Log2Size > 15)
Chris Lattner75361b62010-04-07 22:58:41 +0000435 report_fatal_error("invalid 'common' alignment '" +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000436 Twine(Align) + "'");
437 // FIXME: Keep this mask with the SymbolFlags enumeration.
438 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
439 }
440 }
441
442 // struct nlist (12 bytes)
443
444 Write32(MSD.StringIndex);
445 Write8(Type);
446 Write8(MSD.SectionIndex);
447
448 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
449 // value.
450 Write16(Flags);
451 if (Is64Bit)
452 Write64(Address);
453 else
454 Write32(Address);
455 }
456
Daniel Dunbar35b06572010-03-22 23:16:43 +0000457 // FIXME: We really need to improve the relocation validation. Basically, we
458 // want to implement a separate computation which evaluates the relocation
459 // entry as the linker would, and verifies that the resultant fixup value is
460 // exactly what the encoder wanted. This will catch several classes of
461 // problems:
462 //
463 // - Relocation entry bugs, the two algorithms are unlikely to have the same
464 // exact bug.
465 //
466 // - Relaxation issues, where we forget to relax something.
467 //
468 // - Input errors, where something cannot be correctly encoded. 'as' allows
469 // these through in many cases.
470
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000471 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000472 const MCFragment *Fragment,
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000473 const MCAsmFixup &Fixup, MCValue Target,
474 uint64_t &FixedValue) {
475 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
476 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.Kind);
477 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
478
479 // See <reloc.h>.
Daniel Dunbar640e9482010-05-11 23:53:07 +0000480 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.Offset;
Daniel Dunbardb4c7e62010-05-11 23:53:11 +0000481 uint32_t FixupAddress = Layout.getFragmentAddress(Fragment) + Fixup.Offset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000482 int64_t Value = 0;
483 unsigned Index = 0;
484 unsigned IsExtern = 0;
485 unsigned Type = 0;
486
487 Value = Target.getConstant();
488
489 if (IsPCRel) {
490 // Compensate for the relocation offset, Darwin x86_64 relocations only
491 // have the addend and appear to have attempted to define it to be the
492 // actual expression addend without the PCrel bias. However, instructions
493 // with data following the relocation are not accomodated for (see comment
494 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
Benjamin Kramer454c4ce2010-04-08 15:25:57 +0000495 Value += 1LL << Log2Size;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000496 }
497
498 if (Target.isAbsolute()) { // constant
499 // SymbolNum of 0 indicates the absolute section.
500 Type = RIT_X86_64_Unsigned;
501 Index = 0;
502
503 // FIXME: I believe this is broken, I don't think the linker can
504 // understand it. I think it would require a local relocation, but I'm not
505 // sure if that would work either. The official way to get an absolute
506 // PCrel relocation is to use an absolute symbol (which we don't support
507 // yet).
508 if (IsPCRel) {
509 IsExtern = 1;
510 Type = RIT_X86_64_Branch;
511 }
512 } else if (Target.getSymB()) { // A - B + constant
513 const MCSymbol *A = &Target.getSymA()->getSymbol();
514 MCSymbolData &A_SD = Asm.getSymbolData(*A);
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000515 const MCSymbolData *A_Base = Asm.getAtom(Layout, &A_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000516
517 const MCSymbol *B = &Target.getSymB()->getSymbol();
518 MCSymbolData &B_SD = Asm.getSymbolData(*B);
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000519 const MCSymbolData *B_Base = Asm.getAtom(Layout, &B_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000520
521 // Neither symbol can be modified.
522 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
523 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000524 report_fatal_error("unsupported relocation of modified symbol");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000525
526 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
527 // implement most of these correctly.
528 if (IsPCRel)
Chris Lattner75361b62010-04-07 22:58:41 +0000529 report_fatal_error("unsupported pc-relative relocation of difference");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000530
531 // We don't currently support any situation where one or both of the
532 // symbols would require a local relocation. This is almost certainly
533 // unused and may not be possible to encode correctly.
534 if (!A_Base || !B_Base)
Chris Lattner75361b62010-04-07 22:58:41 +0000535 report_fatal_error("unsupported local relocations in difference");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000536
537 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
538 // a single SIGNED relocation); reject it for now.
539 if (A_Base == B_Base)
Chris Lattner75361b62010-04-07 22:58:41 +0000540 report_fatal_error("unsupported relocation with identical base");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000541
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000542 Value += Layout.getSymbolAddress(&A_SD) - Layout.getSymbolAddress(A_Base);
543 Value -= Layout.getSymbolAddress(&B_SD) - Layout.getSymbolAddress(B_Base);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000544
545 Index = A_Base->getIndex();
546 IsExtern = 1;
547 Type = RIT_X86_64_Unsigned;
548
549 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000550 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000551 MRE.Word1 = ((Index << 0) |
552 (IsPCRel << 24) |
553 (Log2Size << 25) |
554 (IsExtern << 27) |
555 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000556 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000557
558 Index = B_Base->getIndex();
559 IsExtern = 1;
560 Type = RIT_X86_64_Subtractor;
561 } else {
562 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
563 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000564 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000565
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000566 // Relocations inside debug sections always use local relocations when
567 // possible. This seems to be done because the debugger doesn't fully
568 // understand x86_64 relocation entries, and expects to find values that
569 // have already been fixed up.
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000570 if (Symbol->isInSection()) {
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000571 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
572 Fragment->getParent()->getSection());
573 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
574 Base = 0;
575 }
576
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000577 // x86_64 almost always uses external relocations, except when there is no
578 // symbol to use as a base address (a local symbol with no preceeding
579 // non-local symbol).
580 if (Base) {
581 Index = Base->getIndex();
582 IsExtern = 1;
583
584 // Add the local offset, if needed.
585 if (Base != &SD)
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000586 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000587 } else if (Symbol->isInSection()) {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000588 // The index is the section ordinal (1-based).
589 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000590 IsExtern = 0;
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000591 Value += Layout.getSymbolAddress(&SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000592
593 if (IsPCRel)
Daniel Dunbardb4c7e62010-05-11 23:53:11 +0000594 Value -= FixupAddress + (1 << Log2Size);
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000595 } else {
596 report_fatal_error("unsupported relocation of undefined symbol '" +
597 Symbol->getName() + "'");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000598 }
599
600 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
601 if (IsPCRel) {
602 if (IsRIPRel) {
603 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
604 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
605 // rewrite the movq to an leaq at link time if the symbol ends up in
606 // the same linkage unit.
607 if (unsigned(Fixup.Kind) == X86::reloc_riprel_4byte_movq_load)
608 Type = RIT_X86_64_GOTLoad;
609 else
610 Type = RIT_X86_64_GOT;
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000611 } else if (Modifier != MCSymbolRefExpr::VK_None) {
Chris Lattner75361b62010-04-07 22:58:41 +0000612 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000613 } else {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000614 Type = RIT_X86_64_Signed;
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000615
616 // The Darwin x86_64 relocation format has a problem where it cannot
617 // encode an address (L<foo> + <constant>) which is outside the atom
618 // containing L<foo>. Generally, this shouldn't occur but it does
619 // happen when we have a RIPrel instruction with data following the
620 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
621 // adjustment Darwin x86_64 uses, the offset is still negative and
622 // the linker has no way to recognize this.
623 //
624 // To work around this, Darwin uses several special relocation types
625 // to indicate the offsets. However, the specification or
626 // implementation of these seems to also be incomplete; they should
627 // adjust the addend as well based on the actual encoded instruction
628 // (the additional bias), but instead appear to just look at the
629 // final offset.
630 switch (-(Target.getConstant() + (1LL << Log2Size))) {
631 case 1: Type = RIT_X86_64_Signed1; break;
632 case 2: Type = RIT_X86_64_Signed2; break;
633 case 4: Type = RIT_X86_64_Signed4; break;
634 }
635 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000636 } else {
637 if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000638 report_fatal_error("unsupported symbol modifier in branch "
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000639 "relocation");
640
641 Type = RIT_X86_64_Branch;
642 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000643 } else {
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000644 if (Modifier == MCSymbolRefExpr::VK_GOT) {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000645 Type = RIT_X86_64_GOT;
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000646 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
647 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
648 // which case all we do is set the PCrel bit in the relocation entry;
649 // this is used with exception handling, for example. The source is
650 // required to include any necessary offset directly.
651 Type = RIT_X86_64_GOT;
652 IsPCRel = 1;
653 } else if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000654 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000655 else
656 Type = RIT_X86_64_Unsigned;
657 }
658 }
659
660 // x86_64 always writes custom values into the fixups.
661 FixedValue = Value;
662
663 // struct relocation_info (8 bytes)
664 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000665 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000666 MRE.Word1 = ((Index << 0) |
667 (IsPCRel << 24) |
668 (Log2Size << 25) |
669 (IsExtern << 27) |
670 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000671 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000672 }
673
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000674 void RecordScatteredRelocation(const MCAssembler &Asm,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000675 const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000676 const MCFragment *Fragment,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000677 const MCAsmFixup &Fixup, MCValue Target,
678 uint64_t &FixedValue) {
Daniel Dunbar640e9482010-05-11 23:53:07 +0000679 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.Offset;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000680 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
681 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
682 unsigned Type = RIT_Vanilla;
683
684 // See <reloc.h>.
685 const MCSymbol *A = &Target.getSymA()->getSymbol();
686 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
687
688 if (!A_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000689 report_fatal_error("symbol '" + A->getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000690 "' can not be undefined in a subtraction expression");
691
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000692 uint32_t Value = Layout.getSymbolAddress(A_SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000693 uint32_t Value2 = 0;
694
695 if (const MCSymbolRefExpr *B = Target.getSymB()) {
696 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
697
698 if (!B_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000699 report_fatal_error("symbol '" + B->getSymbol().getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000700 "' can not be undefined in a subtraction expression");
701
702 // Select the appropriate difference relocation type.
703 //
704 // Note that there is no longer any semantic difference between these two
705 // relocation types from the linkers point of view, this is done solely
706 // for pedantic compatibility with 'as'.
707 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000708 Value2 = Layout.getSymbolAddress(B_SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000709 }
710
711 // Relocations are written out in reverse order, so the PAIR comes first.
712 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
713 MachRelocationEntry MRE;
714 MRE.Word0 = ((0 << 0) |
715 (RIT_Pair << 24) |
716 (Log2Size << 28) |
717 (IsPCRel << 30) |
718 RF_Scattered);
719 MRE.Word1 = Value2;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000720 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000721 }
722
723 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000724 MRE.Word0 = ((FixupOffset << 0) |
725 (Type << 24) |
726 (Log2Size << 28) |
727 (IsPCRel << 30) |
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000728 RF_Scattered);
729 MRE.Word1 = Value;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000730 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000731 }
732
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000733 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
734 const MCFragment *Fragment, const MCAsmFixup &Fixup,
735 MCValue Target, uint64_t &FixedValue) {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000736 if (Is64Bit) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000737 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000738 return;
739 }
740
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000741 unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
742 unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
743
744 // If this is a difference or a defined symbol plus an offset, then we need
745 // a scattered relocation entry.
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000746 // Differences always require scattered relocations.
747 if (Target.getSymB())
748 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
749 Target, FixedValue);
750
751 // Get the symbol data, if any.
752 MCSymbolData *SD = 0;
753 if (Target.getSymA())
754 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
755
756 // If this is an internal relocation with an offset, it also needs a
757 // scattered relocation entry.
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000758 uint32_t Offset = Target.getConstant();
759 if (IsPCRel)
760 Offset += 1 << Log2Size;
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000761 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
762 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
763 Target, FixedValue);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000764
765 // See <reloc.h>.
Daniel Dunbar640e9482010-05-11 23:53:07 +0000766 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.Offset;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000767 uint32_t Value = 0;
768 unsigned Index = 0;
769 unsigned IsExtern = 0;
770 unsigned Type = 0;
771
772 if (Target.isAbsolute()) { // constant
773 // SymbolNum of 0 indicates the absolute section.
774 //
775 // FIXME: Currently, these are never generated (see code below). I cannot
776 // find a case where they are actually emitted.
777 Type = RIT_Vanilla;
778 Value = 0;
779 } else {
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000780 // Check whether we need an external or internal relocation.
781 if (doesSymbolRequireExternRelocation(SD)) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000782 IsExtern = 1;
783 Index = SD->getIndex();
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000784 // For external relocations, make sure to offset the fixup value to
785 // compensate for the addend of the symbol address, if it was
786 // undefined. This occurs with weak definitions, for example.
787 if (!SD->Symbol->isUndefined())
Kevin Enderbya6eeb6e2010-05-07 21:44:23 +0000788 FixedValue -= Layout.getSymbolAddress(SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000789 Value = 0;
790 } else {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000791 // The index is the section ordinal (1-based).
792 Index = SD->getFragment()->getParent()->getOrdinal() + 1;
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000793 Value = Layout.getSymbolAddress(SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000794 }
795
796 Type = RIT_Vanilla;
797 }
798
799 // struct relocation_info (8 bytes)
800 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000801 MRE.Word0 = FixupOffset;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000802 MRE.Word1 = ((Index << 0) |
803 (IsPCRel << 24) |
804 (Log2Size << 25) |
805 (IsExtern << 27) |
806 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000807 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000808 }
809
810 void BindIndirectSymbols(MCAssembler &Asm) {
811 // This is the point where 'as' creates actual symbols for indirect symbols
812 // (in the following two passes). It would be easier for us to do this
813 // sooner when we see the attribute, but that makes getting the order in the
814 // symbol table much more complicated than it is worth.
815 //
816 // FIXME: Revisit this when the dust settles.
817
818 // Bind non lazy symbol pointers first.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000819 unsigned IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000820 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000821 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000822 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +0000823 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000824
825 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
826 continue;
827
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000828 // Initialize the section indirect symbol base, if necessary.
829 if (!IndirectSymBase.count(it->SectionData))
830 IndirectSymBase[it->SectionData] = IndirectIndex;
831
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000832 Asm.getOrCreateSymbolData(*it->Symbol);
833 }
834
835 // Then lazy symbol pointers and symbol stubs.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000836 IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000837 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000838 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000839 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +0000840 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000841
842 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
843 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
844 continue;
845
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000846 // Initialize the section indirect symbol base, if necessary.
847 if (!IndirectSymBase.count(it->SectionData))
848 IndirectSymBase[it->SectionData] = IndirectIndex;
849
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000850 // Set the symbol type to undefined lazy, but only on construction.
851 //
852 // FIXME: Do not hardcode.
853 bool Created;
854 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
855 if (Created)
856 Entry.setFlags(Entry.getFlags() | 0x0001);
857 }
858 }
859
860 /// ComputeSymbolTable - Compute the symbol table data
861 ///
862 /// \param StringTable [out] - The string table data.
863 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
864 /// string table.
865 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
866 std::vector<MachSymbolData> &LocalSymbolData,
867 std::vector<MachSymbolData> &ExternalSymbolData,
868 std::vector<MachSymbolData> &UndefinedSymbolData) {
869 // Build section lookup table.
870 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
871 unsigned Index = 1;
872 for (MCAssembler::iterator it = Asm.begin(),
873 ie = Asm.end(); it != ie; ++it, ++Index)
874 SectionIndexMap[&it->getSection()] = Index;
875 assert(Index <= 256 && "Too many sections!");
876
877 // Index 0 is always the empty string.
878 StringMap<uint64_t> StringIndexMap;
879 StringTable += '\x00';
880
881 // Build the symbol arrays and the string table, but only for non-local
882 // symbols.
883 //
884 // The particular order that we collect the symbols and create the string
885 // table, then sort the symbols is chosen to match 'as'. Even though it
886 // doesn't matter for correctness, this is important for letting us diff .o
887 // files.
888 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
889 ie = Asm.symbol_end(); it != ie; ++it) {
890 const MCSymbol &Symbol = it->getSymbol();
891
892 // Ignore non-linker visible symbols.
893 if (!Asm.isSymbolLinkerVisible(it))
894 continue;
895
896 if (!it->isExternal() && !Symbol.isUndefined())
897 continue;
898
899 uint64_t &Entry = StringIndexMap[Symbol.getName()];
900 if (!Entry) {
901 Entry = StringTable.size();
902 StringTable += Symbol.getName();
903 StringTable += '\x00';
904 }
905
906 MachSymbolData MSD;
907 MSD.SymbolData = it;
908 MSD.StringIndex = Entry;
909
910 if (Symbol.isUndefined()) {
911 MSD.SectionIndex = 0;
912 UndefinedSymbolData.push_back(MSD);
913 } else if (Symbol.isAbsolute()) {
914 MSD.SectionIndex = 0;
915 ExternalSymbolData.push_back(MSD);
916 } else {
917 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
918 assert(MSD.SectionIndex && "Invalid section index!");
919 ExternalSymbolData.push_back(MSD);
920 }
921 }
922
923 // Now add the data for local symbols.
924 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
925 ie = Asm.symbol_end(); it != ie; ++it) {
926 const MCSymbol &Symbol = it->getSymbol();
927
928 // Ignore non-linker visible symbols.
929 if (!Asm.isSymbolLinkerVisible(it))
930 continue;
931
932 if (it->isExternal() || Symbol.isUndefined())
933 continue;
934
935 uint64_t &Entry = StringIndexMap[Symbol.getName()];
936 if (!Entry) {
937 Entry = StringTable.size();
938 StringTable += Symbol.getName();
939 StringTable += '\x00';
940 }
941
942 MachSymbolData MSD;
943 MSD.SymbolData = it;
944 MSD.StringIndex = Entry;
945
946 if (Symbol.isAbsolute()) {
947 MSD.SectionIndex = 0;
948 LocalSymbolData.push_back(MSD);
949 } else {
950 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
951 assert(MSD.SectionIndex && "Invalid section index!");
952 LocalSymbolData.push_back(MSD);
953 }
954 }
955
956 // External and undefined symbols are required to be in lexicographic order.
957 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
958 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
959
960 // Set the symbol indices.
961 Index = 0;
962 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
963 LocalSymbolData[i].SymbolData->setIndex(Index++);
964 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
965 ExternalSymbolData[i].SymbolData->setIndex(Index++);
966 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
967 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
968
969 // The string table is padded to a multiple of 4.
970 while (StringTable.size() % 4)
971 StringTable += '\x00';
972 }
973
Daniel Dunbar873decb2010-03-20 01:58:40 +0000974 void ExecutePostLayoutBinding(MCAssembler &Asm) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000975 // Create symbol data for any indirect symbols.
976 BindIndirectSymbols(Asm);
977
978 // Compute symbol table information and bind symbol indices.
979 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
980 UndefinedSymbolData);
981 }
982
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000983 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000984 unsigned NumSections = Asm.size();
985
986 // The section data starts after the header, the segment load command (and
987 // section headers) and the symbol table.
988 unsigned NumLoadCommands = 1;
989 uint64_t LoadCommandsSize = Is64Bit ?
990 SegmentLoadCommand64Size + NumSections * Section64Size :
991 SegmentLoadCommand32Size + NumSections * Section32Size;
992
993 // Add the symbol table load command sizes, if used.
994 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
995 UndefinedSymbolData.size();
996 if (NumSymbols) {
997 NumLoadCommands += 2;
998 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
999 }
1000
1001 // Compute the total size of the section data, as well as its file size and
1002 // vm size.
1003 uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
1004 + LoadCommandsSize;
1005 uint64_t SectionDataSize = 0;
1006 uint64_t SectionDataFileSize = 0;
1007 uint64_t VMSize = 0;
1008 for (MCAssembler::const_iterator it = Asm.begin(),
1009 ie = Asm.end(); it != ie; ++it) {
1010 const MCSectionData &SD = *it;
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001011 uint64_t Address = Layout.getSectionAddress(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +00001012 uint64_t Size = Layout.getSectionSize(&SD);
1013 uint64_t FileSize = Layout.getSectionFileSize(&SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001014
Daniel Dunbar5d428512010-03-25 02:00:07 +00001015 VMSize = std::max(VMSize, Address + Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001016
1017 if (Asm.getBackend().isVirtualSection(SD.getSection()))
1018 continue;
1019
Daniel Dunbar5d428512010-03-25 02:00:07 +00001020 SectionDataSize = std::max(SectionDataSize, Address + Size);
1021 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001022 }
1023
1024 // The section data is padded to 4 bytes.
1025 //
1026 // FIXME: Is this machine dependent?
1027 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1028 SectionDataFileSize += SectionDataPadding;
1029
1030 // Write the prolog, starting with the header and load command...
1031 WriteHeader(NumLoadCommands, LoadCommandsSize,
1032 Asm.getSubsectionsViaSymbols());
1033 WriteSegmentLoadCommand(NumSections, VMSize,
1034 SectionDataStart, SectionDataSize);
1035
1036 // ... and then the section headers.
1037 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1038 for (MCAssembler::const_iterator it = Asm.begin(),
1039 ie = Asm.end(); it != ie; ++it) {
1040 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1041 unsigned NumRelocs = Relocs.size();
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001042 uint64_t SectionStart = SectionDataStart + Layout.getSectionAddress(it);
1043 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001044 RelocTableEnd += NumRelocs * RelocationInfoSize;
1045 }
1046
1047 // Write the symbol table load command, if used.
1048 if (NumSymbols) {
1049 unsigned FirstLocalSymbol = 0;
1050 unsigned NumLocalSymbols = LocalSymbolData.size();
1051 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1052 unsigned NumExternalSymbols = ExternalSymbolData.size();
1053 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1054 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1055 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1056 unsigned NumSymTabSymbols =
1057 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1058 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1059 uint64_t IndirectSymbolOffset = 0;
1060
1061 // If used, the indirect symbols are written after the section data.
1062 if (NumIndirectSymbols)
1063 IndirectSymbolOffset = RelocTableEnd;
1064
1065 // The symbol table is written after the indirect symbol data.
1066 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1067
1068 // The string table is written after symbol table.
1069 uint64_t StringTableOffset =
1070 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
1071 Nlist32Size);
1072 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1073 StringTableOffset, StringTable.size());
1074
1075 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1076 FirstExternalSymbol, NumExternalSymbols,
1077 FirstUndefinedSymbol, NumUndefinedSymbols,
1078 IndirectSymbolOffset, NumIndirectSymbols);
1079 }
1080
1081 // Write the actual section data.
1082 for (MCAssembler::const_iterator it = Asm.begin(),
1083 ie = Asm.end(); it != ie; ++it)
Daniel Dunbar432cd5f2010-03-25 02:00:02 +00001084 Asm.WriteSectionData(it, Layout, Writer);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001085
1086 // Write the extra padding.
1087 WriteZeros(SectionDataPadding);
1088
1089 // Write the relocation entries.
1090 for (MCAssembler::const_iterator it = Asm.begin(),
1091 ie = Asm.end(); it != ie; ++it) {
1092 // Write the section relocation entries, in reverse order to match 'as'
1093 // (approximately, the exact algorithm is more complicated than this).
1094 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1095 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1096 Write32(Relocs[e - i - 1].Word0);
1097 Write32(Relocs[e - i - 1].Word1);
1098 }
1099 }
1100
1101 // Write the symbol table data, if used.
1102 if (NumSymbols) {
1103 // Write the indirect symbol entries.
1104 for (MCAssembler::const_indirect_symbol_iterator
1105 it = Asm.indirect_symbol_begin(),
1106 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1107 // Indirect symbols in the non lazy symbol pointer section have some
1108 // special handling.
1109 const MCSectionMachO &Section =
1110 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1111 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1112 // If this symbol is defined and internal, mark it as such.
1113 if (it->Symbol->isDefined() &&
1114 !Asm.getSymbolData(*it->Symbol).isExternal()) {
1115 uint32_t Flags = ISF_Local;
1116 if (it->Symbol->isAbsolute())
1117 Flags |= ISF_Absolute;
1118 Write32(Flags);
1119 continue;
1120 }
1121 }
1122
1123 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1124 }
1125
1126 // FIXME: Check that offsets match computed ones.
1127
1128 // Write the symbol table entries.
1129 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001130 WriteNlist(LocalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001131 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001132 WriteNlist(ExternalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001133 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001134 WriteNlist(UndefinedSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001135
1136 // Write the string table.
1137 OS << StringTable.str();
1138 }
1139 }
1140};
1141
1142}
1143
1144MachObjectWriter::MachObjectWriter(raw_ostream &OS,
1145 bool Is64Bit,
1146 bool IsLittleEndian)
1147 : MCObjectWriter(OS, IsLittleEndian)
1148{
1149 Impl = new MachObjectWriterImpl(this, Is64Bit);
1150}
1151
1152MachObjectWriter::~MachObjectWriter() {
1153 delete (MachObjectWriterImpl*) Impl;
1154}
1155
1156void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1157 ((MachObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1158}
1159
1160void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001161 const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +00001162 const MCFragment *Fragment,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001163 const MCAsmFixup &Fixup, MCValue Target,
1164 uint64_t &FixedValue) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001165 ((MachObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001166 Target, FixedValue);
1167}
1168
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001169void MachObjectWriter::WriteObject(const MCAssembler &Asm,
1170 const MCAsmLayout &Layout) {
1171 ((MachObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001172}