blob: 02a5575606dfde9451c4915ab3c44fe1dbda08fe [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;
Chris Lattnerda3051a2010-07-07 22:35:13 +000036 case X86::reloc_pcrel_2byte:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000037 case FK_Data_2: return 1;
38 case X86::reloc_pcrel_4byte:
39 case X86::reloc_riprel_4byte:
Daniel Dunbar602b40f2010-03-19 18:07:55 +000040 case X86::reloc_riprel_4byte_movq_load:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000041 case FK_Data_4: return 2;
42 case FK_Data_8: return 3;
43 }
44}
45
46static bool isFixupKindPCRel(unsigned Kind) {
47 switch (Kind) {
48 default:
49 return false;
50 case X86::reloc_pcrel_1byte:
Chris Lattnerda3051a2010-07-07 22:35:13 +000051 case X86::reloc_pcrel_2byte:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000052 case X86::reloc_pcrel_4byte:
53 case X86::reloc_riprel_4byte:
Daniel Dunbar602b40f2010-03-19 18:07:55 +000054 case X86::reloc_riprel_4byte_movq_load:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000055 return true;
56 }
57}
58
Daniel Dunbar602b40f2010-03-19 18:07:55 +000059static bool isFixupKindRIPRel(unsigned Kind) {
60 return Kind == X86::reloc_riprel_4byte ||
61 Kind == X86::reloc_riprel_4byte_movq_load;
62}
63
Daniel Dunbare9460ec2010-05-10 23:15:13 +000064static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
65 // Undefined symbols are always extern.
66 if (SD->Symbol->isUndefined())
67 return true;
68
69 // References to weak definitions require external relocation entries; the
70 // definition may not always be the one in the same object file.
71 if (SD->getFlags() & SF_WeakDefinition)
72 return true;
73
74 // Otherwise, we can use an internal relocation.
75 return false;
76}
77
Rafael Espindola70703872010-09-30 02:22:20 +000078static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
79 const MCValue Target,
80 const MCSymbolData *BaseSymbol) {
81 // The effective fixup address is
82 // addr(atom(A)) + offset(A)
83 // - addr(atom(B)) - offset(B)
84 // - addr(BaseSymbol) + <fixup offset from base symbol>
85 // and the offsets are not relocatable, so the fixup is fully resolved when
86 // addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
87 //
88 // Note that "false" is almost always conservatively correct (it means we emit
89 // a relocation which is unnecessary), except when it would force us to emit a
90 // relocation which the target cannot encode.
91
92 const MCSymbolData *A_Base = 0, *B_Base = 0;
93 if (const MCSymbolRefExpr *A = Target.getSymA()) {
94 // Modified symbol references cannot be resolved.
95 if (A->getKind() != MCSymbolRefExpr::VK_None)
96 return false;
97
98 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
99 if (!A_Base)
100 return false;
101 }
102
103 if (const MCSymbolRefExpr *B = Target.getSymB()) {
104 // Modified symbol references cannot be resolved.
105 if (B->getKind() != MCSymbolRefExpr::VK_None)
106 return false;
107
108 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
109 if (!B_Base)
110 return false;
111 }
112
113 // If there is no base, A and B have to be the same atom for this fixup to be
114 // fully resolved.
115 if (!BaseSymbol)
116 return A_Base == B_Base;
117
118 // Otherwise, B must be missing and A must be the base.
119 return !B_Base && BaseSymbol == A_Base;
120}
121
122static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
123 const MCValue Target,
124 const MCSection *BaseSection) {
125 // The effective fixup address is
126 // addr(atom(A)) + offset(A)
127 // - addr(atom(B)) - offset(B)
128 // - addr(<base symbol>) + <fixup offset from base symbol>
129 // and the offsets are not relocatable, so the fixup is fully resolved when
130 // addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
131 //
132 // The simple (Darwin, except on x86_64) way of dealing with this was to
133 // assume that any reference to a temporary symbol *must* be a temporary
134 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
135 // relocation to a temporary symbol (in the same section) is fully
136 // resolved. This also works in conjunction with absolutized .set, which
137 // requires the compiler to use .set to absolutize the differences between
138 // symbols which the compiler knows to be assembly time constants, so we don't
139 // need to worry about considering symbol differences fully resolved.
140
141 // Non-relative fixups are only resolved if constant.
142 if (!BaseSection)
143 return Target.isAbsolute();
144
145 // Otherwise, relative fixups are only resolved if not a difference and the
146 // target is a temporary in the same section.
147 if (Target.isAbsolute() || Target.getSymB())
148 return false;
149
150 const MCSymbol *A = &Target.getSymA()->getSymbol();
151 if (!A->isTemporary() || !A->isInSection() ||
152 &A->getSection() != BaseSection)
153 return false;
154
155 return true;
156}
157
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000158namespace {
159
160class MachObjectWriterImpl {
161 // See <mach-o/loader.h>.
162 enum {
163 Header_Magic32 = 0xFEEDFACE,
164 Header_Magic64 = 0xFEEDFACF
165 };
166
167 enum {
168 Header32Size = 28,
169 Header64Size = 32,
170 SegmentLoadCommand32Size = 56,
171 SegmentLoadCommand64Size = 72,
172 Section32Size = 68,
173 Section64Size = 80,
174 SymtabLoadCommandSize = 24,
175 DysymtabLoadCommandSize = 80,
176 Nlist32Size = 12,
177 Nlist64Size = 16,
178 RelocationInfoSize = 8
179 };
180
181 enum HeaderFileType {
182 HFT_Object = 0x1
183 };
184
185 enum HeaderFlags {
186 HF_SubsectionsViaSymbols = 0x2000
187 };
188
189 enum LoadCommandType {
190 LCT_Segment = 0x1,
191 LCT_Symtab = 0x2,
192 LCT_Dysymtab = 0xb,
193 LCT_Segment64 = 0x19
194 };
195
196 // See <mach-o/nlist.h>.
197 enum SymbolTypeType {
198 STT_Undefined = 0x00,
199 STT_Absolute = 0x02,
200 STT_Section = 0x0e
201 };
202
203 enum SymbolTypeFlags {
204 // If any of these bits are set, then the entry is a stab entry number (see
205 // <mach-o/stab.h>. Otherwise the other masks apply.
206 STF_StabsEntryMask = 0xe0,
207
208 STF_TypeMask = 0x0e,
209 STF_External = 0x01,
210 STF_PrivateExtern = 0x10
211 };
212
213 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
214 /// symbol entry.
215 enum IndirectSymbolFlags {
216 ISF_Local = 0x80000000,
217 ISF_Absolute = 0x40000000
218 };
219
220 /// RelocationFlags - Special flags for addresses.
221 enum RelocationFlags {
222 RF_Scattered = 0x80000000
223 };
224
225 enum RelocationInfoType {
226 RIT_Vanilla = 0,
227 RIT_Pair = 1,
228 RIT_Difference = 2,
229 RIT_PreboundLazyPointer = 3,
Eric Christopher96ac5152010-05-26 00:02:12 +0000230 RIT_LocalDifference = 4,
231 RIT_TLV = 5
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000232 };
233
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000234 /// X86_64 uses its own relocation types.
235 enum RelocationInfoTypeX86_64 {
236 RIT_X86_64_Unsigned = 0,
237 RIT_X86_64_Signed = 1,
238 RIT_X86_64_Branch = 2,
239 RIT_X86_64_GOTLoad = 3,
240 RIT_X86_64_GOT = 4,
241 RIT_X86_64_Subtractor = 5,
242 RIT_X86_64_Signed1 = 6,
243 RIT_X86_64_Signed2 = 7,
Eric Christopher96ac5152010-05-26 00:02:12 +0000244 RIT_X86_64_Signed4 = 8,
245 RIT_X86_64_TLV = 9
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000246 };
247
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000248 /// MachSymbolData - Helper struct for containing some precomputed information
249 /// on symbols.
250 struct MachSymbolData {
251 MCSymbolData *SymbolData;
252 uint64_t StringIndex;
253 uint8_t SectionIndex;
254
255 // Support lexicographic sorting.
256 bool operator<(const MachSymbolData &RHS) const {
Benjamin Kramerc37791e2010-05-20 14:14:22 +0000257 return SymbolData->getSymbol().getName() <
258 RHS.SymbolData->getSymbol().getName();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000259 }
260 };
261
262 /// @name Relocation Data
263 /// @{
264
265 struct MachRelocationEntry {
266 uint32_t Word0;
267 uint32_t Word1;
268 };
269
270 llvm::DenseMap<const MCSectionData*,
271 std::vector<MachRelocationEntry> > Relocations;
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000272 llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000273
274 /// @}
275 /// @name Symbol Table Data
276 /// @{
277
278 SmallString<256> StringTable;
279 std::vector<MachSymbolData> LocalSymbolData;
280 std::vector<MachSymbolData> ExternalSymbolData;
281 std::vector<MachSymbolData> UndefinedSymbolData;
282
283 /// @}
284
285 MachObjectWriter *Writer;
286
287 raw_ostream &OS;
288
289 unsigned Is64Bit : 1;
290
291public:
292 MachObjectWriterImpl(MachObjectWriter *_Writer, bool _Is64Bit)
293 : Writer(_Writer), OS(Writer->getStream()), Is64Bit(_Is64Bit) {
294 }
295
296 void Write8(uint8_t Value) { Writer->Write8(Value); }
297 void Write16(uint16_t Value) { Writer->Write16(Value); }
298 void Write32(uint32_t Value) { Writer->Write32(Value); }
299 void Write64(uint64_t Value) { Writer->Write64(Value); }
300 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
301 void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
302 Writer->WriteBytes(Str, ZeroFillSize);
303 }
304
305 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
306 bool SubsectionsViaSymbols) {
307 uint32_t Flags = 0;
308
309 if (SubsectionsViaSymbols)
310 Flags |= HF_SubsectionsViaSymbols;
311
312 // struct mach_header (28 bytes) or
313 // struct mach_header_64 (32 bytes)
314
315 uint64_t Start = OS.tell();
316 (void) Start;
317
318 Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
319
320 // FIXME: Support cputype.
321 Write32(Is64Bit ? MachO::CPUTypeX86_64 : MachO::CPUTypeI386);
322 // FIXME: Support cpusubtype.
323 Write32(MachO::CPUSubType_I386_ALL);
324 Write32(HFT_Object);
325 Write32(NumLoadCommands); // Object files have a single load command, the
326 // segment.
327 Write32(LoadCommandsSize);
328 Write32(Flags);
329 if (Is64Bit)
330 Write32(0); // reserved
331
332 assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
333 }
334
335 /// WriteSegmentLoadCommand - Write a segment load command.
336 ///
337 /// \arg NumSections - The number of sections in this segment.
338 /// \arg SectionDataSize - The total size of the sections.
339 void WriteSegmentLoadCommand(unsigned NumSections,
340 uint64_t VMSize,
341 uint64_t SectionDataStartOffset,
342 uint64_t SectionDataSize) {
343 // struct segment_command (56 bytes) or
344 // struct segment_command_64 (72 bytes)
345
346 uint64_t Start = OS.tell();
347 (void) Start;
348
349 unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
350 SegmentLoadCommand32Size;
351 Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
352 Write32(SegmentLoadCommandSize +
353 NumSections * (Is64Bit ? Section64Size : Section32Size));
354
355 WriteBytes("", 16);
356 if (Is64Bit) {
357 Write64(0); // vmaddr
358 Write64(VMSize); // vmsize
359 Write64(SectionDataStartOffset); // file offset
360 Write64(SectionDataSize); // file size
361 } else {
362 Write32(0); // vmaddr
363 Write32(VMSize); // vmsize
364 Write32(SectionDataStartOffset); // file offset
365 Write32(SectionDataSize); // file size
366 }
367 Write32(0x7); // maxprot
368 Write32(0x7); // initprot
369 Write32(NumSections);
370 Write32(0); // flags
371
372 assert(OS.tell() - Start == SegmentLoadCommandSize);
373 }
374
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000375 void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
376 const MCSectionData &SD, uint64_t FileOffset,
377 uint64_t RelocationsStart, unsigned NumRelocations) {
Daniel Dunbar5d428512010-03-25 02:00:07 +0000378 uint64_t SectionSize = Layout.getSectionSize(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +0000379
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000380 // The offset is unused for virtual sections.
381 if (Asm.getBackend().isVirtualSection(SD.getSection())) {
Daniel Dunbarb026d642010-03-25 07:10:05 +0000382 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000383 FileOffset = 0;
384 }
385
386 // struct section (68 bytes) or
387 // struct section_64 (80 bytes)
388
389 uint64_t Start = OS.tell();
390 (void) Start;
391
Daniel Dunbar56279f42010-05-18 17:28:20 +0000392 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000393 WriteBytes(Section.getSectionName(), 16);
394 WriteBytes(Section.getSegmentName(), 16);
395 if (Is64Bit) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000396 Write64(Layout.getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000397 Write64(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000398 } else {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000399 Write32(Layout.getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000400 Write32(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000401 }
402 Write32(FileOffset);
403
404 unsigned Flags = Section.getTypeAndAttributes();
405 if (SD.hasInstructions())
406 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
407
408 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
409 Write32(Log2_32(SD.getAlignment()));
410 Write32(NumRelocations ? RelocationsStart : 0);
411 Write32(NumRelocations);
412 Write32(Flags);
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000413 Write32(IndirectSymBase.lookup(&SD)); // reserved1
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000414 Write32(Section.getStubSize()); // reserved2
415 if (Is64Bit)
416 Write32(0); // reserved3
417
418 assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
419 }
420
421 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
422 uint32_t StringTableOffset,
423 uint32_t StringTableSize) {
424 // struct symtab_command (24 bytes)
425
426 uint64_t Start = OS.tell();
427 (void) Start;
428
429 Write32(LCT_Symtab);
430 Write32(SymtabLoadCommandSize);
431 Write32(SymbolOffset);
432 Write32(NumSymbols);
433 Write32(StringTableOffset);
434 Write32(StringTableSize);
435
436 assert(OS.tell() - Start == SymtabLoadCommandSize);
437 }
438
439 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
440 uint32_t NumLocalSymbols,
441 uint32_t FirstExternalSymbol,
442 uint32_t NumExternalSymbols,
443 uint32_t FirstUndefinedSymbol,
444 uint32_t NumUndefinedSymbols,
445 uint32_t IndirectSymbolOffset,
446 uint32_t NumIndirectSymbols) {
447 // struct dysymtab_command (80 bytes)
448
449 uint64_t Start = OS.tell();
450 (void) Start;
451
452 Write32(LCT_Dysymtab);
453 Write32(DysymtabLoadCommandSize);
454 Write32(FirstLocalSymbol);
455 Write32(NumLocalSymbols);
456 Write32(FirstExternalSymbol);
457 Write32(NumExternalSymbols);
458 Write32(FirstUndefinedSymbol);
459 Write32(NumUndefinedSymbols);
460 Write32(0); // tocoff
461 Write32(0); // ntoc
462 Write32(0); // modtaboff
463 Write32(0); // nmodtab
464 Write32(0); // extrefsymoff
465 Write32(0); // nextrefsyms
466 Write32(IndirectSymbolOffset);
467 Write32(NumIndirectSymbols);
468 Write32(0); // extreloff
469 Write32(0); // nextrel
470 Write32(0); // locreloff
471 Write32(0); // nlocrel
472
473 assert(OS.tell() - Start == DysymtabLoadCommandSize);
474 }
475
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000476 void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000477 MCSymbolData &Data = *MSD.SymbolData;
478 const MCSymbol &Symbol = Data.getSymbol();
479 uint8_t Type = 0;
480 uint16_t Flags = Data.getFlags();
481 uint32_t Address = 0;
482
483 // Set the N_TYPE bits. See <mach-o/nlist.h>.
484 //
485 // FIXME: Are the prebound or indirect fields possible here?
486 if (Symbol.isUndefined())
487 Type = STT_Undefined;
488 else if (Symbol.isAbsolute())
489 Type = STT_Absolute;
490 else
491 Type = STT_Section;
492
493 // FIXME: Set STAB bits.
494
495 if (Data.isPrivateExtern())
496 Type |= STF_PrivateExtern;
497
498 // Set external bit.
499 if (Data.isExternal() || Symbol.isUndefined())
500 Type |= STF_External;
501
502 // Compute the symbol address.
503 if (Symbol.isDefined()) {
504 if (Symbol.isAbsolute()) {
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000505 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000506 } else {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000507 Address = Layout.getSymbolAddress(&Data);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000508 }
509 } else if (Data.isCommon()) {
510 // Common symbols are encoded with the size in the address
511 // field, and their alignment in the flags.
512 Address = Data.getCommonSize();
513
514 // Common alignment is packed into the 'desc' bits.
515 if (unsigned Align = Data.getCommonAlignment()) {
516 unsigned Log2Size = Log2_32(Align);
517 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
518 if (Log2Size > 15)
Chris Lattner75361b62010-04-07 22:58:41 +0000519 report_fatal_error("invalid 'common' alignment '" +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000520 Twine(Align) + "'");
521 // FIXME: Keep this mask with the SymbolFlags enumeration.
522 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
523 }
524 }
525
526 // struct nlist (12 bytes)
527
528 Write32(MSD.StringIndex);
529 Write8(Type);
530 Write8(MSD.SectionIndex);
531
532 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
533 // value.
534 Write16(Flags);
535 if (Is64Bit)
536 Write64(Address);
537 else
538 Write32(Address);
539 }
540
Daniel Dunbar35b06572010-03-22 23:16:43 +0000541 // FIXME: We really need to improve the relocation validation. Basically, we
542 // want to implement a separate computation which evaluates the relocation
543 // entry as the linker would, and verifies that the resultant fixup value is
544 // exactly what the encoder wanted. This will catch several classes of
545 // problems:
546 //
547 // - Relocation entry bugs, the two algorithms are unlikely to have the same
548 // exact bug.
549 //
550 // - Relaxation issues, where we forget to relax something.
551 //
552 // - Input errors, where something cannot be correctly encoded. 'as' allows
553 // these through in many cases.
554
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000555 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000556 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000557 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000558 uint64_t &FixedValue) {
Daniel Dunbar482ad802010-05-26 15:18:31 +0000559 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
560 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
561 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000562
563 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000564 uint32_t FixupOffset =
565 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
566 uint32_t FixupAddress =
567 Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000568 int64_t Value = 0;
569 unsigned Index = 0;
570 unsigned IsExtern = 0;
571 unsigned Type = 0;
572
573 Value = Target.getConstant();
574
575 if (IsPCRel) {
576 // Compensate for the relocation offset, Darwin x86_64 relocations only
577 // have the addend and appear to have attempted to define it to be the
578 // actual expression addend without the PCrel bias. However, instructions
579 // with data following the relocation are not accomodated for (see comment
580 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
Benjamin Kramer454c4ce2010-04-08 15:25:57 +0000581 Value += 1LL << Log2Size;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000582 }
583
584 if (Target.isAbsolute()) { // constant
585 // SymbolNum of 0 indicates the absolute section.
586 Type = RIT_X86_64_Unsigned;
587 Index = 0;
588
589 // FIXME: I believe this is broken, I don't think the linker can
590 // understand it. I think it would require a local relocation, but I'm not
591 // sure if that would work either. The official way to get an absolute
592 // PCrel relocation is to use an absolute symbol (which we don't support
593 // yet).
594 if (IsPCRel) {
595 IsExtern = 1;
596 Type = RIT_X86_64_Branch;
597 }
598 } else if (Target.getSymB()) { // A - B + constant
599 const MCSymbol *A = &Target.getSymA()->getSymbol();
600 MCSymbolData &A_SD = Asm.getSymbolData(*A);
Rafael Espindolab8141102010-09-27 18:13:03 +0000601 const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000602
603 const MCSymbol *B = &Target.getSymB()->getSymbol();
604 MCSymbolData &B_SD = Asm.getSymbolData(*B);
Rafael Espindolab8141102010-09-27 18:13:03 +0000605 const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000606
607 // Neither symbol can be modified.
608 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
609 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000610 report_fatal_error("unsupported relocation of modified symbol");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000611
612 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
613 // implement most of these correctly.
614 if (IsPCRel)
Chris Lattner75361b62010-04-07 22:58:41 +0000615 report_fatal_error("unsupported pc-relative relocation of difference");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000616
617 // We don't currently support any situation where one or both of the
618 // symbols would require a local relocation. This is almost certainly
619 // unused and may not be possible to encode correctly.
620 if (!A_Base || !B_Base)
Chris Lattner75361b62010-04-07 22:58:41 +0000621 report_fatal_error("unsupported local relocations in difference");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000622
623 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
624 // a single SIGNED relocation); reject it for now.
625 if (A_Base == B_Base)
Chris Lattner75361b62010-04-07 22:58:41 +0000626 report_fatal_error("unsupported relocation with identical base");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000627
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000628 Value += Layout.getSymbolAddress(&A_SD) - Layout.getSymbolAddress(A_Base);
629 Value -= Layout.getSymbolAddress(&B_SD) - Layout.getSymbolAddress(B_Base);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000630
631 Index = A_Base->getIndex();
632 IsExtern = 1;
633 Type = RIT_X86_64_Unsigned;
634
635 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000636 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000637 MRE.Word1 = ((Index << 0) |
638 (IsPCRel << 24) |
639 (Log2Size << 25) |
640 (IsExtern << 27) |
641 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000642 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000643
644 Index = B_Base->getIndex();
645 IsExtern = 1;
646 Type = RIT_X86_64_Subtractor;
647 } else {
648 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
649 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
Rafael Espindolab8141102010-09-27 18:13:03 +0000650 const MCSymbolData *Base = Asm.getAtom(&SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000651
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000652 // Relocations inside debug sections always use local relocations when
653 // possible. This seems to be done because the debugger doesn't fully
654 // understand x86_64 relocation entries, and expects to find values that
655 // have already been fixed up.
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000656 if (Symbol->isInSection()) {
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000657 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
658 Fragment->getParent()->getSection());
659 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
660 Base = 0;
661 }
662
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000663 // x86_64 almost always uses external relocations, except when there is no
664 // symbol to use as a base address (a local symbol with no preceeding
665 // non-local symbol).
666 if (Base) {
667 Index = Base->getIndex();
668 IsExtern = 1;
669
670 // Add the local offset, if needed.
671 if (Base != &SD)
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000672 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000673 } else if (Symbol->isInSection()) {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000674 // The index is the section ordinal (1-based).
675 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000676 IsExtern = 0;
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000677 Value += Layout.getSymbolAddress(&SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000678
679 if (IsPCRel)
Daniel Dunbardb4c7e62010-05-11 23:53:11 +0000680 Value -= FixupAddress + (1 << Log2Size);
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000681 } else {
682 report_fatal_error("unsupported relocation of undefined symbol '" +
683 Symbol->getName() + "'");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000684 }
685
686 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
687 if (IsPCRel) {
688 if (IsRIPRel) {
689 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
690 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
691 // rewrite the movq to an leaq at link time if the symbol ends up in
692 // the same linkage unit.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000693 if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000694 Type = RIT_X86_64_GOTLoad;
695 else
696 Type = RIT_X86_64_GOT;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000697 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
Eric Christopher96ac5152010-05-26 00:02:12 +0000698 Type = RIT_X86_64_TLV;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000699 } else if (Modifier != MCSymbolRefExpr::VK_None) {
700 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000701 } else {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000702 Type = RIT_X86_64_Signed;
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000703
704 // The Darwin x86_64 relocation format has a problem where it cannot
705 // encode an address (L<foo> + <constant>) which is outside the atom
706 // containing L<foo>. Generally, this shouldn't occur but it does
707 // happen when we have a RIPrel instruction with data following the
708 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
709 // adjustment Darwin x86_64 uses, the offset is still negative and
710 // the linker has no way to recognize this.
711 //
712 // To work around this, Darwin uses several special relocation types
713 // to indicate the offsets. However, the specification or
714 // implementation of these seems to also be incomplete; they should
715 // adjust the addend as well based on the actual encoded instruction
716 // (the additional bias), but instead appear to just look at the
717 // final offset.
718 switch (-(Target.getConstant() + (1LL << Log2Size))) {
719 case 1: Type = RIT_X86_64_Signed1; break;
720 case 2: Type = RIT_X86_64_Signed2; break;
721 case 4: Type = RIT_X86_64_Signed4; break;
722 }
723 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000724 } else {
725 if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000726 report_fatal_error("unsupported symbol modifier in branch "
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000727 "relocation");
728
729 Type = RIT_X86_64_Branch;
730 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000731 } else {
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000732 if (Modifier == MCSymbolRefExpr::VK_GOT) {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000733 Type = RIT_X86_64_GOT;
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000734 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
735 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
736 // which case all we do is set the PCrel bit in the relocation entry;
737 // this is used with exception handling, for example. The source is
738 // required to include any necessary offset directly.
739 Type = RIT_X86_64_GOT;
740 IsPCRel = 1;
Eric Christopher96ac5152010-05-26 00:02:12 +0000741 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
742 report_fatal_error("TLVP symbol modifier should have been rip-rel");
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000743 } else if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000744 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000745 else
746 Type = RIT_X86_64_Unsigned;
747 }
748 }
749
750 // x86_64 always writes custom values into the fixups.
751 FixedValue = Value;
752
753 // struct relocation_info (8 bytes)
754 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000755 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000756 MRE.Word1 = ((Index << 0) |
757 (IsPCRel << 24) |
758 (Log2Size << 25) |
759 (IsExtern << 27) |
760 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000761 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000762 }
763
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000764 void RecordScatteredRelocation(const MCAssembler &Asm,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000765 const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000766 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000767 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000768 uint64_t &FixedValue) {
Daniel Dunbar482ad802010-05-26 15:18:31 +0000769 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
770 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
771 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000772 unsigned Type = RIT_Vanilla;
773
774 // See <reloc.h>.
775 const MCSymbol *A = &Target.getSymA()->getSymbol();
776 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
777
778 if (!A_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000779 report_fatal_error("symbol '" + A->getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000780 "' can not be undefined in a subtraction expression");
781
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000782 uint32_t Value = Layout.getSymbolAddress(A_SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000783 uint32_t Value2 = 0;
784
785 if (const MCSymbolRefExpr *B = Target.getSymB()) {
786 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
787
788 if (!B_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000789 report_fatal_error("symbol '" + B->getSymbol().getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000790 "' can not be undefined in a subtraction expression");
791
792 // Select the appropriate difference relocation type.
793 //
794 // Note that there is no longer any semantic difference between these two
795 // relocation types from the linkers point of view, this is done solely
796 // for pedantic compatibility with 'as'.
797 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000798 Value2 = Layout.getSymbolAddress(B_SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000799 }
800
801 // Relocations are written out in reverse order, so the PAIR comes first.
802 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
803 MachRelocationEntry MRE;
804 MRE.Word0 = ((0 << 0) |
805 (RIT_Pair << 24) |
806 (Log2Size << 28) |
807 (IsPCRel << 30) |
808 RF_Scattered);
809 MRE.Word1 = Value2;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000810 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000811 }
812
813 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000814 MRE.Word0 = ((FixupOffset << 0) |
815 (Type << 24) |
816 (Log2Size << 28) |
817 (IsPCRel << 30) |
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000818 RF_Scattered);
819 MRE.Word1 = Value;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000820 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000821 }
822
Eric Christopherc9ada472010-06-15 22:59:05 +0000823 void RecordTLVPRelocation(const MCAssembler &Asm,
Eric Christophere48dbf82010-06-16 00:26:36 +0000824 const MCAsmLayout &Layout,
825 const MCFragment *Fragment,
826 const MCFixup &Fixup, MCValue Target,
827 uint64_t &FixedValue) {
Eric Christopherc9ada472010-06-15 22:59:05 +0000828 assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
829 !Is64Bit &&
830 "Should only be called with a 32-bit TLVP relocation!");
831
Eric Christopherc9ada472010-06-15 22:59:05 +0000832 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
833 uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
834 unsigned IsPCRel = 0;
835
836 // Get the symbol data.
837 MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
838 unsigned Index = SD_A->getIndex();
839
Eric Christopherbc067372010-06-16 21:32:38 +0000840 // We're only going to have a second symbol in pic mode and it'll be a
841 // subtraction from the picbase. For 32-bit pic the addend is the difference
Eric Christopher04b8d3c2010-06-17 00:49:46 +0000842 // between the picbase and the next address. For 32-bit static the addend
843 // is zero.
Eric Christopherbc067372010-06-16 21:32:38 +0000844 if (Target.getSymB()) {
Eric Christopher1008d352010-06-22 23:51:47 +0000845 // If this is a subtraction then we're pcrel.
846 uint32_t FixupAddress =
847 Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
848 MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
Eric Christopherc9ada472010-06-15 22:59:05 +0000849 IsPCRel = 1;
Eric Christopher1008d352010-06-22 23:51:47 +0000850 FixedValue = (FixupAddress - Layout.getSymbolAddress(SD_B) +
851 Target.getConstant());
Chris Lattnerabf8f9c2010-08-16 16:35:20 +0000852 FixedValue += 1ULL << Log2Size;
Eric Christopherbc067372010-06-16 21:32:38 +0000853 } else {
854 FixedValue = 0;
855 }
Eric Christopherc9ada472010-06-15 22:59:05 +0000856
857 // struct relocation_info (8 bytes)
858 MachRelocationEntry MRE;
859 MRE.Word0 = Value;
860 MRE.Word1 = ((Index << 0) |
861 (IsPCRel << 24) |
862 (Log2Size << 25) |
863 (1 << 27) | // Extern
864 (RIT_TLV << 28)); // Type
865 Relocations[Fragment->getParent()].push_back(MRE);
866 }
867
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000868 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000869 const MCFragment *Fragment, const MCFixup &Fixup,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000870 MCValue Target, uint64_t &FixedValue) {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000871 if (Is64Bit) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000872 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000873 return;
874 }
875
Daniel Dunbar482ad802010-05-26 15:18:31 +0000876 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
877 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000878
Eric Christopherc9ada472010-06-15 22:59:05 +0000879 // If this is a 32-bit TLVP reloc it's handled a bit differently.
Daniel Dunbar23bea412010-09-17 15:21:50 +0000880 if (Target.getSymA() &&
881 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
Eric Christopherc9ada472010-06-15 22:59:05 +0000882 RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
883 return;
884 }
885
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000886 // If this is a difference or a defined symbol plus an offset, then we need
887 // a scattered relocation entry.
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000888 // Differences always require scattered relocations.
889 if (Target.getSymB())
890 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
891 Target, FixedValue);
892
893 // Get the symbol data, if any.
894 MCSymbolData *SD = 0;
895 if (Target.getSymA())
896 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
897
898 // If this is an internal relocation with an offset, it also needs a
899 // scattered relocation entry.
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000900 uint32_t Offset = Target.getConstant();
901 if (IsPCRel)
902 Offset += 1 << Log2Size;
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000903 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
904 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
905 Target, FixedValue);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000906
907 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000908 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000909 unsigned Index = 0;
910 unsigned IsExtern = 0;
911 unsigned Type = 0;
912
913 if (Target.isAbsolute()) { // constant
914 // SymbolNum of 0 indicates the absolute section.
915 //
916 // FIXME: Currently, these are never generated (see code below). I cannot
917 // find a case where they are actually emitted.
918 Type = RIT_Vanilla;
Michael J. Spencerb0f3b3e2010-08-10 16:00:49 +0000919 } else {
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000920 // Check whether we need an external or internal relocation.
921 if (doesSymbolRequireExternRelocation(SD)) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000922 IsExtern = 1;
923 Index = SD->getIndex();
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000924 // For external relocations, make sure to offset the fixup value to
925 // compensate for the addend of the symbol address, if it was
926 // undefined. This occurs with weak definitions, for example.
927 if (!SD->Symbol->isUndefined())
Kevin Enderbya6eeb6e2010-05-07 21:44:23 +0000928 FixedValue -= Layout.getSymbolAddress(SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000929 } else {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000930 // The index is the section ordinal (1-based).
931 Index = SD->getFragment()->getParent()->getOrdinal() + 1;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000932 }
933
934 Type = RIT_Vanilla;
935 }
936
937 // struct relocation_info (8 bytes)
938 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000939 MRE.Word0 = FixupOffset;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000940 MRE.Word1 = ((Index << 0) |
941 (IsPCRel << 24) |
942 (Log2Size << 25) |
943 (IsExtern << 27) |
944 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000945 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000946 }
947
948 void BindIndirectSymbols(MCAssembler &Asm) {
949 // This is the point where 'as' creates actual symbols for indirect symbols
950 // (in the following two passes). It would be easier for us to do this
951 // sooner when we see the attribute, but that makes getting the order in the
952 // symbol table much more complicated than it is worth.
953 //
954 // FIXME: Revisit this when the dust settles.
955
956 // Bind non lazy symbol pointers first.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000957 unsigned IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000958 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000959 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000960 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +0000961 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000962
963 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
964 continue;
965
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000966 // Initialize the section indirect symbol base, if necessary.
967 if (!IndirectSymBase.count(it->SectionData))
968 IndirectSymBase[it->SectionData] = IndirectIndex;
969
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000970 Asm.getOrCreateSymbolData(*it->Symbol);
971 }
972
973 // Then lazy symbol pointers and symbol stubs.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000974 IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000975 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000976 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000977 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +0000978 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000979
980 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
981 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
982 continue;
983
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000984 // Initialize the section indirect symbol base, if necessary.
985 if (!IndirectSymBase.count(it->SectionData))
986 IndirectSymBase[it->SectionData] = IndirectIndex;
987
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000988 // Set the symbol type to undefined lazy, but only on construction.
989 //
990 // FIXME: Do not hardcode.
991 bool Created;
992 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
993 if (Created)
994 Entry.setFlags(Entry.getFlags() | 0x0001);
995 }
996 }
997
998 /// ComputeSymbolTable - Compute the symbol table data
999 ///
1000 /// \param StringTable [out] - The string table data.
1001 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
1002 /// string table.
1003 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
1004 std::vector<MachSymbolData> &LocalSymbolData,
1005 std::vector<MachSymbolData> &ExternalSymbolData,
1006 std::vector<MachSymbolData> &UndefinedSymbolData) {
1007 // Build section lookup table.
1008 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
1009 unsigned Index = 1;
1010 for (MCAssembler::iterator it = Asm.begin(),
1011 ie = Asm.end(); it != ie; ++it, ++Index)
1012 SectionIndexMap[&it->getSection()] = Index;
1013 assert(Index <= 256 && "Too many sections!");
1014
1015 // Index 0 is always the empty string.
1016 StringMap<uint64_t> StringIndexMap;
1017 StringTable += '\x00';
1018
1019 // Build the symbol arrays and the string table, but only for non-local
1020 // symbols.
1021 //
1022 // The particular order that we collect the symbols and create the string
1023 // table, then sort the symbols is chosen to match 'as'. Even though it
1024 // doesn't matter for correctness, this is important for letting us diff .o
1025 // files.
1026 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1027 ie = Asm.symbol_end(); it != ie; ++it) {
1028 const MCSymbol &Symbol = it->getSymbol();
1029
1030 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +00001031 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001032 continue;
1033
1034 if (!it->isExternal() && !Symbol.isUndefined())
1035 continue;
1036
1037 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1038 if (!Entry) {
1039 Entry = StringTable.size();
1040 StringTable += Symbol.getName();
1041 StringTable += '\x00';
1042 }
1043
1044 MachSymbolData MSD;
1045 MSD.SymbolData = it;
1046 MSD.StringIndex = Entry;
1047
1048 if (Symbol.isUndefined()) {
1049 MSD.SectionIndex = 0;
1050 UndefinedSymbolData.push_back(MSD);
1051 } else if (Symbol.isAbsolute()) {
1052 MSD.SectionIndex = 0;
1053 ExternalSymbolData.push_back(MSD);
1054 } else {
1055 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1056 assert(MSD.SectionIndex && "Invalid section index!");
1057 ExternalSymbolData.push_back(MSD);
1058 }
1059 }
1060
1061 // Now add the data for local symbols.
1062 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1063 ie = Asm.symbol_end(); it != ie; ++it) {
1064 const MCSymbol &Symbol = it->getSymbol();
1065
1066 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +00001067 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001068 continue;
1069
1070 if (it->isExternal() || Symbol.isUndefined())
1071 continue;
1072
1073 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1074 if (!Entry) {
1075 Entry = StringTable.size();
1076 StringTable += Symbol.getName();
1077 StringTable += '\x00';
1078 }
1079
1080 MachSymbolData MSD;
1081 MSD.SymbolData = it;
1082 MSD.StringIndex = Entry;
1083
1084 if (Symbol.isAbsolute()) {
1085 MSD.SectionIndex = 0;
1086 LocalSymbolData.push_back(MSD);
1087 } else {
1088 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1089 assert(MSD.SectionIndex && "Invalid section index!");
1090 LocalSymbolData.push_back(MSD);
1091 }
1092 }
1093
1094 // External and undefined symbols are required to be in lexicographic order.
1095 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1096 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1097
1098 // Set the symbol indices.
1099 Index = 0;
1100 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1101 LocalSymbolData[i].SymbolData->setIndex(Index++);
1102 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1103 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1104 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1105 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1106
1107 // The string table is padded to a multiple of 4.
1108 while (StringTable.size() % 4)
1109 StringTable += '\x00';
1110 }
1111
Daniel Dunbar873decb2010-03-20 01:58:40 +00001112 void ExecutePostLayoutBinding(MCAssembler &Asm) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001113 // Create symbol data for any indirect symbols.
1114 BindIndirectSymbols(Asm);
1115
1116 // Compute symbol table information and bind symbol indices.
1117 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1118 UndefinedSymbolData);
1119 }
1120
Rafael Espindola70703872010-09-30 02:22:20 +00001121
1122 bool IsFixupFullyResolved(const MCAssembler &Asm,
1123 const MCValue Target,
1124 bool IsPCRel,
1125 const MCFragment *DF) const {
1126 // If we are using scattered symbols, determine whether this value is
1127 // actually resolved; scattering may cause atoms to move.
1128 if (Asm.getBackend().hasScatteredSymbols()) {
1129 if (Asm.getBackend().hasReliableSymbolDifference()) {
1130 // If this is a PCrel relocation, find the base atom (identified by its
1131 // symbol) that the fixup value is relative to.
1132 const MCSymbolData *BaseSymbol = 0;
1133 if (IsPCRel) {
1134 BaseSymbol = DF->getAtom();
1135 if (!BaseSymbol)
1136 return false;
1137 }
1138
1139 return isScatteredFixupFullyResolved(Asm, Target, BaseSymbol);
1140 } else {
1141 const MCSection *BaseSection = 0;
1142 if (IsPCRel)
1143 BaseSection = &DF->getParent()->getSection();
1144
1145 return isScatteredFixupFullyResolvedSimple(Asm, Target, BaseSection);
1146 }
1147 }
1148 return true;
1149 }
1150
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001151 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001152 unsigned NumSections = Asm.size();
1153
1154 // The section data starts after the header, the segment load command (and
1155 // section headers) and the symbol table.
1156 unsigned NumLoadCommands = 1;
1157 uint64_t LoadCommandsSize = Is64Bit ?
1158 SegmentLoadCommand64Size + NumSections * Section64Size :
1159 SegmentLoadCommand32Size + NumSections * Section32Size;
1160
1161 // Add the symbol table load command sizes, if used.
1162 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1163 UndefinedSymbolData.size();
1164 if (NumSymbols) {
1165 NumLoadCommands += 2;
1166 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
1167 }
1168
1169 // Compute the total size of the section data, as well as its file size and
1170 // vm size.
1171 uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
1172 + LoadCommandsSize;
1173 uint64_t SectionDataSize = 0;
1174 uint64_t SectionDataFileSize = 0;
1175 uint64_t VMSize = 0;
1176 for (MCAssembler::const_iterator it = Asm.begin(),
1177 ie = Asm.end(); it != ie; ++it) {
1178 const MCSectionData &SD = *it;
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001179 uint64_t Address = Layout.getSectionAddress(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +00001180 uint64_t Size = Layout.getSectionSize(&SD);
1181 uint64_t FileSize = Layout.getSectionFileSize(&SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001182
Daniel Dunbar5d428512010-03-25 02:00:07 +00001183 VMSize = std::max(VMSize, Address + Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001184
1185 if (Asm.getBackend().isVirtualSection(SD.getSection()))
1186 continue;
1187
Daniel Dunbar5d428512010-03-25 02:00:07 +00001188 SectionDataSize = std::max(SectionDataSize, Address + Size);
1189 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001190 }
1191
1192 // The section data is padded to 4 bytes.
1193 //
1194 // FIXME: Is this machine dependent?
1195 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1196 SectionDataFileSize += SectionDataPadding;
1197
1198 // Write the prolog, starting with the header and load command...
1199 WriteHeader(NumLoadCommands, LoadCommandsSize,
1200 Asm.getSubsectionsViaSymbols());
1201 WriteSegmentLoadCommand(NumSections, VMSize,
1202 SectionDataStart, SectionDataSize);
1203
1204 // ... and then the section headers.
1205 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1206 for (MCAssembler::const_iterator it = Asm.begin(),
1207 ie = Asm.end(); it != ie; ++it) {
1208 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1209 unsigned NumRelocs = Relocs.size();
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001210 uint64_t SectionStart = SectionDataStart + Layout.getSectionAddress(it);
1211 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001212 RelocTableEnd += NumRelocs * RelocationInfoSize;
1213 }
1214
1215 // Write the symbol table load command, if used.
1216 if (NumSymbols) {
1217 unsigned FirstLocalSymbol = 0;
1218 unsigned NumLocalSymbols = LocalSymbolData.size();
1219 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1220 unsigned NumExternalSymbols = ExternalSymbolData.size();
1221 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1222 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1223 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1224 unsigned NumSymTabSymbols =
1225 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1226 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1227 uint64_t IndirectSymbolOffset = 0;
1228
1229 // If used, the indirect symbols are written after the section data.
1230 if (NumIndirectSymbols)
1231 IndirectSymbolOffset = RelocTableEnd;
1232
1233 // The symbol table is written after the indirect symbol data.
1234 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1235
1236 // The string table is written after symbol table.
1237 uint64_t StringTableOffset =
1238 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
1239 Nlist32Size);
1240 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1241 StringTableOffset, StringTable.size());
1242
1243 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1244 FirstExternalSymbol, NumExternalSymbols,
1245 FirstUndefinedSymbol, NumUndefinedSymbols,
1246 IndirectSymbolOffset, NumIndirectSymbols);
1247 }
1248
1249 // Write the actual section data.
1250 for (MCAssembler::const_iterator it = Asm.begin(),
1251 ie = Asm.end(); it != ie; ++it)
Daniel Dunbar432cd5f2010-03-25 02:00:02 +00001252 Asm.WriteSectionData(it, Layout, Writer);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001253
1254 // Write the extra padding.
1255 WriteZeros(SectionDataPadding);
1256
1257 // Write the relocation entries.
1258 for (MCAssembler::const_iterator it = Asm.begin(),
1259 ie = Asm.end(); it != ie; ++it) {
1260 // Write the section relocation entries, in reverse order to match 'as'
1261 // (approximately, the exact algorithm is more complicated than this).
1262 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1263 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1264 Write32(Relocs[e - i - 1].Word0);
1265 Write32(Relocs[e - i - 1].Word1);
1266 }
1267 }
1268
1269 // Write the symbol table data, if used.
1270 if (NumSymbols) {
1271 // Write the indirect symbol entries.
1272 for (MCAssembler::const_indirect_symbol_iterator
1273 it = Asm.indirect_symbol_begin(),
1274 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1275 // Indirect symbols in the non lazy symbol pointer section have some
1276 // special handling.
1277 const MCSectionMachO &Section =
1278 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1279 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1280 // If this symbol is defined and internal, mark it as such.
1281 if (it->Symbol->isDefined() &&
1282 !Asm.getSymbolData(*it->Symbol).isExternal()) {
1283 uint32_t Flags = ISF_Local;
1284 if (it->Symbol->isAbsolute())
1285 Flags |= ISF_Absolute;
1286 Write32(Flags);
1287 continue;
1288 }
1289 }
1290
1291 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1292 }
1293
1294 // FIXME: Check that offsets match computed ones.
1295
1296 // Write the symbol table entries.
1297 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001298 WriteNlist(LocalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001299 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001300 WriteNlist(ExternalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001301 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001302 WriteNlist(UndefinedSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001303
1304 // Write the string table.
1305 OS << StringTable.str();
1306 }
1307 }
1308};
1309
1310}
1311
1312MachObjectWriter::MachObjectWriter(raw_ostream &OS,
1313 bool Is64Bit,
1314 bool IsLittleEndian)
1315 : MCObjectWriter(OS, IsLittleEndian)
1316{
1317 Impl = new MachObjectWriterImpl(this, Is64Bit);
1318}
1319
1320MachObjectWriter::~MachObjectWriter() {
1321 delete (MachObjectWriterImpl*) Impl;
1322}
1323
1324void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1325 ((MachObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1326}
1327
1328void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001329 const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +00001330 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +00001331 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001332 uint64_t &FixedValue) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001333 ((MachObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001334 Target, FixedValue);
1335}
1336
Rafael Espindola70703872010-09-30 02:22:20 +00001337bool MachObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1338 const MCValue Target,
1339 bool IsPCRel,
1340 const MCFragment *DF) const {
1341 return ((MachObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1342 IsPCRel, DF);
1343}
1344
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001345void MachObjectWriter::WriteObject(const MCAssembler &Asm,
1346 const MCAsmLayout &Layout) {
1347 ((MachObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001348}