blob: 41c11fba1d07a1e84bfef1a6b1c8a17835a6bcb8 [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
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000010#include "llvm/ADT/StringMap.h"
11#include "llvm/ADT/Twine.h"
12#include "llvm/MC/MCAssembler.h"
Daniel Dunbar207e06e2010-03-24 03:43:40 +000013#include "llvm/MC/MCAsmLayout.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000014#include "llvm/MC/MCExpr.h"
15#include "llvm/MC/MCObjectWriter.h"
16#include "llvm/MC/MCSectionMachO.h"
17#include "llvm/MC/MCSymbol.h"
Kevin Enderbya6eeb6e2010-05-07 21:44:23 +000018#include "llvm/MC/MCMachOSymbolFlags.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000019#include "llvm/MC/MCValue.h"
20#include "llvm/Support/ErrorHandling.h"
21#include "llvm/Support/MachO.h"
22#include "llvm/Target/TargetAsmBackend.h"
23
24// FIXME: Gross.
25#include "../Target/X86/X86FixupKinds.h"
26
27#include <vector>
28using namespace llvm;
29
Rafael Espindolaa8c02c32010-09-30 03:11:42 +000030// FIXME: this has been copied from (or to) X86AsmBackend.cpp
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000031static 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:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +000041 case X86::reloc_signed_4byte:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000042 case FK_Data_4: return 2;
43 case FK_Data_8: return 3;
44 }
45}
46
47static bool isFixupKindPCRel(unsigned Kind) {
48 switch (Kind) {
49 default:
50 return false;
51 case X86::reloc_pcrel_1byte:
Chris Lattnerda3051a2010-07-07 22:35:13 +000052 case X86::reloc_pcrel_2byte:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000053 case X86::reloc_pcrel_4byte:
54 case X86::reloc_riprel_4byte:
Daniel Dunbar602b40f2010-03-19 18:07:55 +000055 case X86::reloc_riprel_4byte_movq_load:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000056 return true;
57 }
58}
59
Daniel Dunbar602b40f2010-03-19 18:07:55 +000060static bool isFixupKindRIPRel(unsigned Kind) {
61 return Kind == X86::reloc_riprel_4byte ||
62 Kind == X86::reloc_riprel_4byte_movq_load;
63}
64
Daniel Dunbare9460ec2010-05-10 23:15:13 +000065static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
66 // Undefined symbols are always extern.
67 if (SD->Symbol->isUndefined())
68 return true;
69
70 // References to weak definitions require external relocation entries; the
71 // definition may not always be the one in the same object file.
72 if (SD->getFlags() & SF_WeakDefinition)
73 return true;
74
75 // Otherwise, we can use an internal relocation.
76 return false;
77}
78
Rafael Espindola70703872010-09-30 02:22:20 +000079static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
80 const MCValue Target,
81 const MCSymbolData *BaseSymbol) {
82 // The effective fixup address is
83 // addr(atom(A)) + offset(A)
84 // - addr(atom(B)) - offset(B)
85 // - addr(BaseSymbol) + <fixup offset from base symbol>
86 // and the offsets are not relocatable, so the fixup is fully resolved when
87 // addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
88 //
89 // Note that "false" is almost always conservatively correct (it means we emit
90 // a relocation which is unnecessary), except when it would force us to emit a
91 // relocation which the target cannot encode.
92
93 const MCSymbolData *A_Base = 0, *B_Base = 0;
94 if (const MCSymbolRefExpr *A = Target.getSymA()) {
95 // Modified symbol references cannot be resolved.
96 if (A->getKind() != MCSymbolRefExpr::VK_None)
97 return false;
98
99 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
100 if (!A_Base)
101 return false;
102 }
103
104 if (const MCSymbolRefExpr *B = Target.getSymB()) {
105 // Modified symbol references cannot be resolved.
106 if (B->getKind() != MCSymbolRefExpr::VK_None)
107 return false;
108
109 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
110 if (!B_Base)
111 return false;
112 }
113
114 // If there is no base, A and B have to be the same atom for this fixup to be
115 // fully resolved.
116 if (!BaseSymbol)
117 return A_Base == B_Base;
118
119 // Otherwise, B must be missing and A must be the base.
120 return !B_Base && BaseSymbol == A_Base;
121}
122
123static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
124 const MCValue Target,
125 const MCSection *BaseSection) {
126 // The effective fixup address is
127 // addr(atom(A)) + offset(A)
128 // - addr(atom(B)) - offset(B)
129 // - addr(<base symbol>) + <fixup offset from base symbol>
130 // and the offsets are not relocatable, so the fixup is fully resolved when
131 // addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
132 //
133 // The simple (Darwin, except on x86_64) way of dealing with this was to
134 // assume that any reference to a temporary symbol *must* be a temporary
135 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
136 // relocation to a temporary symbol (in the same section) is fully
137 // resolved. This also works in conjunction with absolutized .set, which
138 // requires the compiler to use .set to absolutize the differences between
139 // symbols which the compiler knows to be assembly time constants, so we don't
140 // need to worry about considering symbol differences fully resolved.
141
142 // Non-relative fixups are only resolved if constant.
143 if (!BaseSection)
144 return Target.isAbsolute();
145
146 // Otherwise, relative fixups are only resolved if not a difference and the
147 // target is a temporary in the same section.
148 if (Target.isAbsolute() || Target.getSymB())
149 return false;
150
151 const MCSymbol *A = &Target.getSymA()->getSymbol();
152 if (!A->isTemporary() || !A->isInSection() ||
153 &A->getSection() != BaseSection)
154 return false;
155
156 return true;
157}
158
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000159namespace {
160
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000161class MachObjectWriter : public MCObjectWriter {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000162 // See <mach-o/loader.h>.
163 enum {
164 Header_Magic32 = 0xFEEDFACE,
165 Header_Magic64 = 0xFEEDFACF
166 };
167
168 enum {
169 Header32Size = 28,
170 Header64Size = 32,
171 SegmentLoadCommand32Size = 56,
172 SegmentLoadCommand64Size = 72,
173 Section32Size = 68,
174 Section64Size = 80,
175 SymtabLoadCommandSize = 24,
176 DysymtabLoadCommandSize = 80,
177 Nlist32Size = 12,
178 Nlist64Size = 16,
179 RelocationInfoSize = 8
180 };
181
182 enum HeaderFileType {
183 HFT_Object = 0x1
184 };
185
186 enum HeaderFlags {
187 HF_SubsectionsViaSymbols = 0x2000
188 };
189
190 enum LoadCommandType {
191 LCT_Segment = 0x1,
192 LCT_Symtab = 0x2,
193 LCT_Dysymtab = 0xb,
194 LCT_Segment64 = 0x19
195 };
196
197 // See <mach-o/nlist.h>.
198 enum SymbolTypeType {
199 STT_Undefined = 0x00,
200 STT_Absolute = 0x02,
201 STT_Section = 0x0e
202 };
203
204 enum SymbolTypeFlags {
205 // If any of these bits are set, then the entry is a stab entry number (see
206 // <mach-o/stab.h>. Otherwise the other masks apply.
207 STF_StabsEntryMask = 0xe0,
208
209 STF_TypeMask = 0x0e,
210 STF_External = 0x01,
211 STF_PrivateExtern = 0x10
212 };
213
214 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
215 /// symbol entry.
216 enum IndirectSymbolFlags {
217 ISF_Local = 0x80000000,
218 ISF_Absolute = 0x40000000
219 };
220
221 /// RelocationFlags - Special flags for addresses.
222 enum RelocationFlags {
223 RF_Scattered = 0x80000000
224 };
225
226 enum RelocationInfoType {
227 RIT_Vanilla = 0,
228 RIT_Pair = 1,
229 RIT_Difference = 2,
230 RIT_PreboundLazyPointer = 3,
Eric Christopher96ac5152010-05-26 00:02:12 +0000231 RIT_LocalDifference = 4,
232 RIT_TLV = 5
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000233 };
234
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000235 /// X86_64 uses its own relocation types.
236 enum RelocationInfoTypeX86_64 {
237 RIT_X86_64_Unsigned = 0,
238 RIT_X86_64_Signed = 1,
239 RIT_X86_64_Branch = 2,
240 RIT_X86_64_GOTLoad = 3,
241 RIT_X86_64_GOT = 4,
242 RIT_X86_64_Subtractor = 5,
243 RIT_X86_64_Signed1 = 6,
244 RIT_X86_64_Signed2 = 7,
Eric Christopher96ac5152010-05-26 00:02:12 +0000245 RIT_X86_64_Signed4 = 8,
246 RIT_X86_64_TLV = 9
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000247 };
248
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000249 /// MachSymbolData - Helper struct for containing some precomputed information
250 /// on symbols.
251 struct MachSymbolData {
252 MCSymbolData *SymbolData;
253 uint64_t StringIndex;
254 uint8_t SectionIndex;
255
256 // Support lexicographic sorting.
257 bool operator<(const MachSymbolData &RHS) const {
Benjamin Kramerc37791e2010-05-20 14:14:22 +0000258 return SymbolData->getSymbol().getName() <
259 RHS.SymbolData->getSymbol().getName();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000260 }
261 };
262
263 /// @name Relocation Data
264 /// @{
265
266 struct MachRelocationEntry {
267 uint32_t Word0;
268 uint32_t Word1;
269 };
270
271 llvm::DenseMap<const MCSectionData*,
272 std::vector<MachRelocationEntry> > Relocations;
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000273 llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000274
275 /// @}
276 /// @name Symbol Table Data
277 /// @{
278
279 SmallString<256> StringTable;
280 std::vector<MachSymbolData> LocalSymbolData;
281 std::vector<MachSymbolData> ExternalSymbolData;
282 std::vector<MachSymbolData> UndefinedSymbolData;
283
284 /// @}
285
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000286 unsigned Is64Bit : 1;
287
Jim Grosbachc9d14392010-11-05 18:48:58 +0000288 uint32_t CPUType;
289 uint32_t CPUSubtype;
290
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000291public:
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000292 MachObjectWriter(raw_ostream &_OS,
293 bool _Is64Bit, uint32_t _CPUType, uint32_t _CPUSubtype,
294 bool _IsLittleEndian)
295 : MCObjectWriter(_OS, _IsLittleEndian),
296 Is64Bit(_Is64Bit), CPUType(_CPUType), CPUSubtype(_CPUSubtype) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000297 }
298
299 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
300 bool SubsectionsViaSymbols) {
301 uint32_t Flags = 0;
302
303 if (SubsectionsViaSymbols)
304 Flags |= HF_SubsectionsViaSymbols;
305
306 // struct mach_header (28 bytes) or
307 // struct mach_header_64 (32 bytes)
308
309 uint64_t Start = OS.tell();
310 (void) Start;
311
312 Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
313
Jim Grosbachc9d14392010-11-05 18:48:58 +0000314 Write32(CPUType);
315 Write32(CPUSubtype);
316
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000317 Write32(HFT_Object);
318 Write32(NumLoadCommands); // Object files have a single load command, the
319 // segment.
320 Write32(LoadCommandsSize);
321 Write32(Flags);
322 if (Is64Bit)
323 Write32(0); // reserved
324
325 assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
326 }
327
328 /// WriteSegmentLoadCommand - Write a segment load command.
329 ///
330 /// \arg NumSections - The number of sections in this segment.
331 /// \arg SectionDataSize - The total size of the sections.
332 void WriteSegmentLoadCommand(unsigned NumSections,
333 uint64_t VMSize,
334 uint64_t SectionDataStartOffset,
335 uint64_t SectionDataSize) {
336 // struct segment_command (56 bytes) or
337 // struct segment_command_64 (72 bytes)
338
339 uint64_t Start = OS.tell();
340 (void) Start;
341
342 unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
343 SegmentLoadCommand32Size;
344 Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
345 Write32(SegmentLoadCommandSize +
346 NumSections * (Is64Bit ? Section64Size : Section32Size));
347
348 WriteBytes("", 16);
349 if (Is64Bit) {
350 Write64(0); // vmaddr
351 Write64(VMSize); // vmsize
352 Write64(SectionDataStartOffset); // file offset
353 Write64(SectionDataSize); // file size
354 } else {
355 Write32(0); // vmaddr
356 Write32(VMSize); // vmsize
357 Write32(SectionDataStartOffset); // file offset
358 Write32(SectionDataSize); // file size
359 }
360 Write32(0x7); // maxprot
361 Write32(0x7); // initprot
362 Write32(NumSections);
363 Write32(0); // flags
364
365 assert(OS.tell() - Start == SegmentLoadCommandSize);
366 }
367
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000368 void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
369 const MCSectionData &SD, uint64_t FileOffset,
370 uint64_t RelocationsStart, unsigned NumRelocations) {
Daniel Dunbar5d428512010-03-25 02:00:07 +0000371 uint64_t SectionSize = Layout.getSectionSize(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +0000372
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000373 // The offset is unused for virtual sections.
374 if (Asm.getBackend().isVirtualSection(SD.getSection())) {
Daniel Dunbarb026d642010-03-25 07:10:05 +0000375 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000376 FileOffset = 0;
377 }
378
379 // struct section (68 bytes) or
380 // struct section_64 (80 bytes)
381
382 uint64_t Start = OS.tell();
383 (void) Start;
384
Daniel Dunbar56279f42010-05-18 17:28:20 +0000385 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000386 WriteBytes(Section.getSectionName(), 16);
387 WriteBytes(Section.getSegmentName(), 16);
388 if (Is64Bit) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000389 Write64(Layout.getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000390 Write64(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000391 } else {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000392 Write32(Layout.getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000393 Write32(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000394 }
395 Write32(FileOffset);
396
397 unsigned Flags = Section.getTypeAndAttributes();
398 if (SD.hasInstructions())
399 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
400
401 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
402 Write32(Log2_32(SD.getAlignment()));
403 Write32(NumRelocations ? RelocationsStart : 0);
404 Write32(NumRelocations);
405 Write32(Flags);
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000406 Write32(IndirectSymBase.lookup(&SD)); // reserved1
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000407 Write32(Section.getStubSize()); // reserved2
408 if (Is64Bit)
409 Write32(0); // reserved3
410
411 assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
412 }
413
414 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
415 uint32_t StringTableOffset,
416 uint32_t StringTableSize) {
417 // struct symtab_command (24 bytes)
418
419 uint64_t Start = OS.tell();
420 (void) Start;
421
422 Write32(LCT_Symtab);
423 Write32(SymtabLoadCommandSize);
424 Write32(SymbolOffset);
425 Write32(NumSymbols);
426 Write32(StringTableOffset);
427 Write32(StringTableSize);
428
429 assert(OS.tell() - Start == SymtabLoadCommandSize);
430 }
431
432 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
433 uint32_t NumLocalSymbols,
434 uint32_t FirstExternalSymbol,
435 uint32_t NumExternalSymbols,
436 uint32_t FirstUndefinedSymbol,
437 uint32_t NumUndefinedSymbols,
438 uint32_t IndirectSymbolOffset,
439 uint32_t NumIndirectSymbols) {
440 // struct dysymtab_command (80 bytes)
441
442 uint64_t Start = OS.tell();
443 (void) Start;
444
445 Write32(LCT_Dysymtab);
446 Write32(DysymtabLoadCommandSize);
447 Write32(FirstLocalSymbol);
448 Write32(NumLocalSymbols);
449 Write32(FirstExternalSymbol);
450 Write32(NumExternalSymbols);
451 Write32(FirstUndefinedSymbol);
452 Write32(NumUndefinedSymbols);
453 Write32(0); // tocoff
454 Write32(0); // ntoc
455 Write32(0); // modtaboff
456 Write32(0); // nmodtab
457 Write32(0); // extrefsymoff
458 Write32(0); // nextrefsyms
459 Write32(IndirectSymbolOffset);
460 Write32(NumIndirectSymbols);
461 Write32(0); // extreloff
462 Write32(0); // nextrel
463 Write32(0); // locreloff
464 Write32(0); // nlocrel
465
466 assert(OS.tell() - Start == DysymtabLoadCommandSize);
467 }
468
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000469 void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000470 MCSymbolData &Data = *MSD.SymbolData;
471 const MCSymbol &Symbol = Data.getSymbol();
472 uint8_t Type = 0;
473 uint16_t Flags = Data.getFlags();
474 uint32_t Address = 0;
475
476 // Set the N_TYPE bits. See <mach-o/nlist.h>.
477 //
478 // FIXME: Are the prebound or indirect fields possible here?
479 if (Symbol.isUndefined())
480 Type = STT_Undefined;
481 else if (Symbol.isAbsolute())
482 Type = STT_Absolute;
483 else
484 Type = STT_Section;
485
486 // FIXME: Set STAB bits.
487
488 if (Data.isPrivateExtern())
489 Type |= STF_PrivateExtern;
490
491 // Set external bit.
492 if (Data.isExternal() || Symbol.isUndefined())
493 Type |= STF_External;
494
495 // Compute the symbol address.
496 if (Symbol.isDefined()) {
497 if (Symbol.isAbsolute()) {
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000498 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000499 } else {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000500 Address = Layout.getSymbolAddress(&Data);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000501 }
502 } else if (Data.isCommon()) {
503 // Common symbols are encoded with the size in the address
504 // field, and their alignment in the flags.
505 Address = Data.getCommonSize();
506
507 // Common alignment is packed into the 'desc' bits.
508 if (unsigned Align = Data.getCommonAlignment()) {
509 unsigned Log2Size = Log2_32(Align);
510 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
511 if (Log2Size > 15)
Chris Lattner75361b62010-04-07 22:58:41 +0000512 report_fatal_error("invalid 'common' alignment '" +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000513 Twine(Align) + "'");
514 // FIXME: Keep this mask with the SymbolFlags enumeration.
515 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
516 }
517 }
518
519 // struct nlist (12 bytes)
520
521 Write32(MSD.StringIndex);
522 Write8(Type);
523 Write8(MSD.SectionIndex);
524
525 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
526 // value.
527 Write16(Flags);
528 if (Is64Bit)
529 Write64(Address);
530 else
531 Write32(Address);
532 }
533
Daniel Dunbar35b06572010-03-22 23:16:43 +0000534 // FIXME: We really need to improve the relocation validation. Basically, we
535 // want to implement a separate computation which evaluates the relocation
536 // entry as the linker would, and verifies that the resultant fixup value is
537 // exactly what the encoder wanted. This will catch several classes of
538 // problems:
539 //
540 // - Relocation entry bugs, the two algorithms are unlikely to have the same
541 // exact bug.
542 //
543 // - Relaxation issues, where we forget to relax something.
544 //
545 // - Input errors, where something cannot be correctly encoded. 'as' allows
546 // these through in many cases.
547
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000548 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000549 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000550 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000551 uint64_t &FixedValue) {
Daniel Dunbar482ad802010-05-26 15:18:31 +0000552 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
553 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
554 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000555
556 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000557 uint32_t FixupOffset =
558 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
559 uint32_t FixupAddress =
560 Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000561 int64_t Value = 0;
562 unsigned Index = 0;
563 unsigned IsExtern = 0;
564 unsigned Type = 0;
565
566 Value = Target.getConstant();
567
568 if (IsPCRel) {
569 // Compensate for the relocation offset, Darwin x86_64 relocations only
570 // have the addend and appear to have attempted to define it to be the
571 // actual expression addend without the PCrel bias. However, instructions
572 // with data following the relocation are not accomodated for (see comment
573 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
Benjamin Kramer454c4ce2010-04-08 15:25:57 +0000574 Value += 1LL << Log2Size;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000575 }
576
577 if (Target.isAbsolute()) { // constant
578 // SymbolNum of 0 indicates the absolute section.
579 Type = RIT_X86_64_Unsigned;
580 Index = 0;
581
582 // FIXME: I believe this is broken, I don't think the linker can
583 // understand it. I think it would require a local relocation, but I'm not
584 // sure if that would work either. The official way to get an absolute
585 // PCrel relocation is to use an absolute symbol (which we don't support
586 // yet).
587 if (IsPCRel) {
588 IsExtern = 1;
589 Type = RIT_X86_64_Branch;
590 }
591 } else if (Target.getSymB()) { // A - B + constant
592 const MCSymbol *A = &Target.getSymA()->getSymbol();
593 MCSymbolData &A_SD = Asm.getSymbolData(*A);
Rafael Espindolab8141102010-09-27 18:13:03 +0000594 const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000595
596 const MCSymbol *B = &Target.getSymB()->getSymbol();
597 MCSymbolData &B_SD = Asm.getSymbolData(*B);
Rafael Espindolab8141102010-09-27 18:13:03 +0000598 const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000599
600 // Neither symbol can be modified.
601 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
602 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000603 report_fatal_error("unsupported relocation of modified symbol");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000604
605 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
606 // implement most of these correctly.
607 if (IsPCRel)
Chris Lattner75361b62010-04-07 22:58:41 +0000608 report_fatal_error("unsupported pc-relative relocation of difference");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000609
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000610 // The support for the situation where one or both of the symbols would
611 // require a local relocation is handled just like if the symbols were
612 // external. This is certainly used in the case of debug sections where
613 // the section has only temporary symbols and thus the symbols don't have
614 // base symbols. This is encoded using the section ordinal and
615 // non-extern relocation entries.
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000616
617 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000618 // a single SIGNED relocation); reject it for now. Except the case where
619 // both symbols don't have a base, equal but both NULL.
620 if (A_Base == B_Base && A_Base)
Chris Lattner75361b62010-04-07 22:58:41 +0000621 report_fatal_error("unsupported relocation with identical base");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000622
Jim Grosbach3c384922010-11-11 20:16:23 +0000623 Value += Layout.getSymbolAddress(&A_SD) -
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000624 (A_Base == NULL ? 0 : Layout.getSymbolAddress(A_Base));
625 Value -= Layout.getSymbolAddress(&B_SD) -
626 (B_Base == NULL ? 0 : Layout.getSymbolAddress(B_Base));
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000627
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000628 if (A_Base) {
629 Index = A_Base->getIndex();
630 IsExtern = 1;
631 }
632 else {
633 Index = A_SD.getFragment()->getParent()->getOrdinal() + 1;
634 IsExtern = 0;
635 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000636 Type = RIT_X86_64_Unsigned;
637
638 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000639 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000640 MRE.Word1 = ((Index << 0) |
641 (IsPCRel << 24) |
642 (Log2Size << 25) |
643 (IsExtern << 27) |
644 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000645 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000646
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000647 if (B_Base) {
648 Index = B_Base->getIndex();
649 IsExtern = 1;
650 }
651 else {
652 Index = B_SD.getFragment()->getParent()->getOrdinal() + 1;
653 IsExtern = 0;
654 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000655 Type = RIT_X86_64_Subtractor;
656 } else {
657 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
658 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
Rafael Espindolab8141102010-09-27 18:13:03 +0000659 const MCSymbolData *Base = Asm.getAtom(&SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000660
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000661 // Relocations inside debug sections always use local relocations when
662 // possible. This seems to be done because the debugger doesn't fully
663 // understand x86_64 relocation entries, and expects to find values that
664 // have already been fixed up.
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000665 if (Symbol->isInSection()) {
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000666 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
667 Fragment->getParent()->getSection());
668 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
669 Base = 0;
670 }
671
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000672 // x86_64 almost always uses external relocations, except when there is no
673 // symbol to use as a base address (a local symbol with no preceeding
674 // non-local symbol).
675 if (Base) {
676 Index = Base->getIndex();
677 IsExtern = 1;
678
679 // Add the local offset, if needed.
680 if (Base != &SD)
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000681 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000682 } else if (Symbol->isInSection()) {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000683 // The index is the section ordinal (1-based).
684 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000685 IsExtern = 0;
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000686 Value += Layout.getSymbolAddress(&SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000687
688 if (IsPCRel)
Daniel Dunbardb4c7e62010-05-11 23:53:11 +0000689 Value -= FixupAddress + (1 << Log2Size);
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000690 } else {
691 report_fatal_error("unsupported relocation of undefined symbol '" +
692 Symbol->getName() + "'");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000693 }
694
695 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
696 if (IsPCRel) {
697 if (IsRIPRel) {
698 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
699 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
700 // rewrite the movq to an leaq at link time if the symbol ends up in
701 // the same linkage unit.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000702 if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000703 Type = RIT_X86_64_GOTLoad;
704 else
705 Type = RIT_X86_64_GOT;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000706 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
Eric Christopher96ac5152010-05-26 00:02:12 +0000707 Type = RIT_X86_64_TLV;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000708 } else if (Modifier != MCSymbolRefExpr::VK_None) {
709 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000710 } else {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000711 Type = RIT_X86_64_Signed;
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000712
713 // The Darwin x86_64 relocation format has a problem where it cannot
714 // encode an address (L<foo> + <constant>) which is outside the atom
715 // containing L<foo>. Generally, this shouldn't occur but it does
716 // happen when we have a RIPrel instruction with data following the
717 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
718 // adjustment Darwin x86_64 uses, the offset is still negative and
719 // the linker has no way to recognize this.
720 //
721 // To work around this, Darwin uses several special relocation types
722 // to indicate the offsets. However, the specification or
723 // implementation of these seems to also be incomplete; they should
724 // adjust the addend as well based on the actual encoded instruction
725 // (the additional bias), but instead appear to just look at the
726 // final offset.
727 switch (-(Target.getConstant() + (1LL << Log2Size))) {
728 case 1: Type = RIT_X86_64_Signed1; break;
729 case 2: Type = RIT_X86_64_Signed2; break;
730 case 4: Type = RIT_X86_64_Signed4; break;
731 }
732 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000733 } else {
734 if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000735 report_fatal_error("unsupported symbol modifier in branch "
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000736 "relocation");
737
738 Type = RIT_X86_64_Branch;
739 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000740 } else {
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000741 if (Modifier == MCSymbolRefExpr::VK_GOT) {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000742 Type = RIT_X86_64_GOT;
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000743 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
744 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
745 // which case all we do is set the PCrel bit in the relocation entry;
746 // this is used with exception handling, for example. The source is
747 // required to include any necessary offset directly.
748 Type = RIT_X86_64_GOT;
749 IsPCRel = 1;
Eric Christopher96ac5152010-05-26 00:02:12 +0000750 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
751 report_fatal_error("TLVP symbol modifier should have been rip-rel");
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000752 } else if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000753 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000754 else
755 Type = RIT_X86_64_Unsigned;
756 }
757 }
758
759 // x86_64 always writes custom values into the fixups.
760 FixedValue = Value;
761
762 // struct relocation_info (8 bytes)
763 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000764 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000765 MRE.Word1 = ((Index << 0) |
766 (IsPCRel << 24) |
767 (Log2Size << 25) |
768 (IsExtern << 27) |
769 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000770 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000771 }
772
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000773 void RecordScatteredRelocation(const MCAssembler &Asm,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000774 const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000775 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000776 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000777 uint64_t &FixedValue) {
Daniel Dunbar482ad802010-05-26 15:18:31 +0000778 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
779 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
780 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000781 unsigned Type = RIT_Vanilla;
782
783 // See <reloc.h>.
784 const MCSymbol *A = &Target.getSymA()->getSymbol();
785 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
786
787 if (!A_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000788 report_fatal_error("symbol '" + A->getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000789 "' can not be undefined in a subtraction expression");
790
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000791 uint32_t Value = Layout.getSymbolAddress(A_SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000792 uint32_t Value2 = 0;
793
794 if (const MCSymbolRefExpr *B = Target.getSymB()) {
795 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
796
797 if (!B_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000798 report_fatal_error("symbol '" + B->getSymbol().getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000799 "' can not be undefined in a subtraction expression");
800
801 // Select the appropriate difference relocation type.
802 //
803 // Note that there is no longer any semantic difference between these two
804 // relocation types from the linkers point of view, this is done solely
805 // for pedantic compatibility with 'as'.
806 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000807 Value2 = Layout.getSymbolAddress(B_SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000808 }
809
810 // Relocations are written out in reverse order, so the PAIR comes first.
811 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
812 MachRelocationEntry MRE;
813 MRE.Word0 = ((0 << 0) |
814 (RIT_Pair << 24) |
815 (Log2Size << 28) |
816 (IsPCRel << 30) |
817 RF_Scattered);
818 MRE.Word1 = Value2;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000819 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000820 }
821
822 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000823 MRE.Word0 = ((FixupOffset << 0) |
824 (Type << 24) |
825 (Log2Size << 28) |
826 (IsPCRel << 30) |
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000827 RF_Scattered);
828 MRE.Word1 = Value;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000829 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000830 }
831
Eric Christopherc9ada472010-06-15 22:59:05 +0000832 void RecordTLVPRelocation(const MCAssembler &Asm,
Eric Christophere48dbf82010-06-16 00:26:36 +0000833 const MCAsmLayout &Layout,
834 const MCFragment *Fragment,
835 const MCFixup &Fixup, MCValue Target,
836 uint64_t &FixedValue) {
Eric Christopherc9ada472010-06-15 22:59:05 +0000837 assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
838 !Is64Bit &&
839 "Should only be called with a 32-bit TLVP relocation!");
840
Eric Christopherc9ada472010-06-15 22:59:05 +0000841 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
842 uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
843 unsigned IsPCRel = 0;
844
845 // Get the symbol data.
846 MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
847 unsigned Index = SD_A->getIndex();
848
Eric Christopherbc067372010-06-16 21:32:38 +0000849 // We're only going to have a second symbol in pic mode and it'll be a
850 // subtraction from the picbase. For 32-bit pic the addend is the difference
Eric Christopher04b8d3c2010-06-17 00:49:46 +0000851 // between the picbase and the next address. For 32-bit static the addend
852 // is zero.
Eric Christopherbc067372010-06-16 21:32:38 +0000853 if (Target.getSymB()) {
Eric Christopher1008d352010-06-22 23:51:47 +0000854 // If this is a subtraction then we're pcrel.
855 uint32_t FixupAddress =
856 Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
857 MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
Eric Christopherc9ada472010-06-15 22:59:05 +0000858 IsPCRel = 1;
Eric Christopher1008d352010-06-22 23:51:47 +0000859 FixedValue = (FixupAddress - Layout.getSymbolAddress(SD_B) +
860 Target.getConstant());
Chris Lattnerabf8f9c2010-08-16 16:35:20 +0000861 FixedValue += 1ULL << Log2Size;
Eric Christopherbc067372010-06-16 21:32:38 +0000862 } else {
863 FixedValue = 0;
864 }
Jim Grosbach3c384922010-11-11 20:16:23 +0000865
Eric Christopherc9ada472010-06-15 22:59:05 +0000866 // struct relocation_info (8 bytes)
867 MachRelocationEntry MRE;
868 MRE.Word0 = Value;
869 MRE.Word1 = ((Index << 0) |
870 (IsPCRel << 24) |
871 (Log2Size << 25) |
872 (1 << 27) | // Extern
873 (RIT_TLV << 28)); // Type
874 Relocations[Fragment->getParent()].push_back(MRE);
875 }
Jim Grosbach3c384922010-11-11 20:16:23 +0000876
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000877 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000878 const MCFragment *Fragment, const MCFixup &Fixup,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000879 MCValue Target, uint64_t &FixedValue) {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000880 if (Is64Bit) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000881 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000882 return;
883 }
884
Daniel Dunbar482ad802010-05-26 15:18:31 +0000885 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
886 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000887
Eric Christopherc9ada472010-06-15 22:59:05 +0000888 // If this is a 32-bit TLVP reloc it's handled a bit differently.
Daniel Dunbar23bea412010-09-17 15:21:50 +0000889 if (Target.getSymA() &&
890 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
Eric Christopherc9ada472010-06-15 22:59:05 +0000891 RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
892 return;
893 }
Jim Grosbach3c384922010-11-11 20:16:23 +0000894
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000895 // If this is a difference or a defined symbol plus an offset, then we need
896 // a scattered relocation entry.
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000897 // Differences always require scattered relocations.
898 if (Target.getSymB())
899 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
900 Target, FixedValue);
901
902 // Get the symbol data, if any.
903 MCSymbolData *SD = 0;
904 if (Target.getSymA())
905 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
906
907 // If this is an internal relocation with an offset, it also needs a
908 // scattered relocation entry.
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000909 uint32_t Offset = Target.getConstant();
910 if (IsPCRel)
911 Offset += 1 << Log2Size;
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000912 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
913 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
914 Target, FixedValue);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000915
916 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000917 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000918 unsigned Index = 0;
919 unsigned IsExtern = 0;
920 unsigned Type = 0;
921
922 if (Target.isAbsolute()) { // constant
923 // SymbolNum of 0 indicates the absolute section.
924 //
925 // FIXME: Currently, these are never generated (see code below). I cannot
926 // find a case where they are actually emitted.
927 Type = RIT_Vanilla;
Michael J. Spencerb0f3b3e2010-08-10 16:00:49 +0000928 } else {
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000929 // Check whether we need an external or internal relocation.
930 if (doesSymbolRequireExternRelocation(SD)) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000931 IsExtern = 1;
932 Index = SD->getIndex();
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000933 // For external relocations, make sure to offset the fixup value to
934 // compensate for the addend of the symbol address, if it was
935 // undefined. This occurs with weak definitions, for example.
936 if (!SD->Symbol->isUndefined())
Kevin Enderbya6eeb6e2010-05-07 21:44:23 +0000937 FixedValue -= Layout.getSymbolAddress(SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000938 } else {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000939 // The index is the section ordinal (1-based).
940 Index = SD->getFragment()->getParent()->getOrdinal() + 1;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000941 }
942
943 Type = RIT_Vanilla;
944 }
945
946 // struct relocation_info (8 bytes)
947 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000948 MRE.Word0 = FixupOffset;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000949 MRE.Word1 = ((Index << 0) |
950 (IsPCRel << 24) |
951 (Log2Size << 25) |
952 (IsExtern << 27) |
953 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000954 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000955 }
956
957 void BindIndirectSymbols(MCAssembler &Asm) {
958 // This is the point where 'as' creates actual symbols for indirect symbols
959 // (in the following two passes). It would be easier for us to do this
960 // sooner when we see the attribute, but that makes getting the order in the
961 // symbol table much more complicated than it is worth.
962 //
963 // FIXME: Revisit this when the dust settles.
964
965 // Bind non lazy symbol pointers first.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000966 unsigned IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000967 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000968 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000969 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +0000970 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000971
972 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
973 continue;
974
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000975 // Initialize the section indirect symbol base, if necessary.
976 if (!IndirectSymBase.count(it->SectionData))
977 IndirectSymBase[it->SectionData] = IndirectIndex;
Jim Grosbach3c384922010-11-11 20:16:23 +0000978
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000979 Asm.getOrCreateSymbolData(*it->Symbol);
980 }
981
982 // Then lazy symbol pointers and symbol stubs.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000983 IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000984 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000985 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000986 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +0000987 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000988
989 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
990 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
991 continue;
992
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000993 // Initialize the section indirect symbol base, if necessary.
994 if (!IndirectSymBase.count(it->SectionData))
995 IndirectSymBase[it->SectionData] = IndirectIndex;
996
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000997 // Set the symbol type to undefined lazy, but only on construction.
998 //
999 // FIXME: Do not hardcode.
1000 bool Created;
1001 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
1002 if (Created)
1003 Entry.setFlags(Entry.getFlags() | 0x0001);
1004 }
1005 }
1006
1007 /// ComputeSymbolTable - Compute the symbol table data
1008 ///
1009 /// \param StringTable [out] - The string table data.
1010 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
1011 /// string table.
1012 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
1013 std::vector<MachSymbolData> &LocalSymbolData,
1014 std::vector<MachSymbolData> &ExternalSymbolData,
1015 std::vector<MachSymbolData> &UndefinedSymbolData) {
1016 // Build section lookup table.
1017 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
1018 unsigned Index = 1;
1019 for (MCAssembler::iterator it = Asm.begin(),
1020 ie = Asm.end(); it != ie; ++it, ++Index)
1021 SectionIndexMap[&it->getSection()] = Index;
1022 assert(Index <= 256 && "Too many sections!");
1023
1024 // Index 0 is always the empty string.
1025 StringMap<uint64_t> StringIndexMap;
1026 StringTable += '\x00';
1027
1028 // Build the symbol arrays and the string table, but only for non-local
1029 // symbols.
1030 //
1031 // The particular order that we collect the symbols and create the string
1032 // table, then sort the symbols is chosen to match 'as'. Even though it
1033 // doesn't matter for correctness, this is important for letting us diff .o
1034 // files.
1035 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1036 ie = Asm.symbol_end(); it != ie; ++it) {
1037 const MCSymbol &Symbol = it->getSymbol();
1038
1039 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +00001040 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001041 continue;
1042
1043 if (!it->isExternal() && !Symbol.isUndefined())
1044 continue;
1045
1046 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1047 if (!Entry) {
1048 Entry = StringTable.size();
1049 StringTable += Symbol.getName();
1050 StringTable += '\x00';
1051 }
1052
1053 MachSymbolData MSD;
1054 MSD.SymbolData = it;
1055 MSD.StringIndex = Entry;
1056
1057 if (Symbol.isUndefined()) {
1058 MSD.SectionIndex = 0;
1059 UndefinedSymbolData.push_back(MSD);
1060 } else if (Symbol.isAbsolute()) {
1061 MSD.SectionIndex = 0;
1062 ExternalSymbolData.push_back(MSD);
1063 } else {
1064 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1065 assert(MSD.SectionIndex && "Invalid section index!");
1066 ExternalSymbolData.push_back(MSD);
1067 }
1068 }
1069
1070 // Now add the data for local symbols.
1071 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1072 ie = Asm.symbol_end(); it != ie; ++it) {
1073 const MCSymbol &Symbol = it->getSymbol();
1074
1075 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +00001076 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001077 continue;
1078
1079 if (it->isExternal() || Symbol.isUndefined())
1080 continue;
1081
1082 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1083 if (!Entry) {
1084 Entry = StringTable.size();
1085 StringTable += Symbol.getName();
1086 StringTable += '\x00';
1087 }
1088
1089 MachSymbolData MSD;
1090 MSD.SymbolData = it;
1091 MSD.StringIndex = Entry;
1092
1093 if (Symbol.isAbsolute()) {
1094 MSD.SectionIndex = 0;
1095 LocalSymbolData.push_back(MSD);
1096 } else {
1097 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1098 assert(MSD.SectionIndex && "Invalid section index!");
1099 LocalSymbolData.push_back(MSD);
1100 }
1101 }
1102
1103 // External and undefined symbols are required to be in lexicographic order.
1104 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1105 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1106
1107 // Set the symbol indices.
1108 Index = 0;
1109 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1110 LocalSymbolData[i].SymbolData->setIndex(Index++);
1111 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1112 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1113 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1114 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1115
1116 // The string table is padded to a multiple of 4.
1117 while (StringTable.size() % 4)
1118 StringTable += '\x00';
1119 }
1120
Daniel Dunbar873decb2010-03-20 01:58:40 +00001121 void ExecutePostLayoutBinding(MCAssembler &Asm) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001122 // Create symbol data for any indirect symbols.
1123 BindIndirectSymbols(Asm);
1124
1125 // Compute symbol table information and bind symbol indices.
1126 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1127 UndefinedSymbolData);
1128 }
1129
Rafael Espindola70703872010-09-30 02:22:20 +00001130
1131 bool IsFixupFullyResolved(const MCAssembler &Asm,
1132 const MCValue Target,
1133 bool IsPCRel,
1134 const MCFragment *DF) const {
1135 // If we are using scattered symbols, determine whether this value is
1136 // actually resolved; scattering may cause atoms to move.
1137 if (Asm.getBackend().hasScatteredSymbols()) {
1138 if (Asm.getBackend().hasReliableSymbolDifference()) {
1139 // If this is a PCrel relocation, find the base atom (identified by its
1140 // symbol) that the fixup value is relative to.
1141 const MCSymbolData *BaseSymbol = 0;
1142 if (IsPCRel) {
1143 BaseSymbol = DF->getAtom();
1144 if (!BaseSymbol)
1145 return false;
1146 }
1147
1148 return isScatteredFixupFullyResolved(Asm, Target, BaseSymbol);
1149 } else {
1150 const MCSection *BaseSection = 0;
1151 if (IsPCRel)
1152 BaseSection = &DF->getParent()->getSection();
1153
1154 return isScatteredFixupFullyResolvedSimple(Asm, Target, BaseSection);
1155 }
1156 }
1157 return true;
1158 }
1159
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001160 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001161 unsigned NumSections = Asm.size();
1162
1163 // The section data starts after the header, the segment load command (and
1164 // section headers) and the symbol table.
1165 unsigned NumLoadCommands = 1;
1166 uint64_t LoadCommandsSize = Is64Bit ?
1167 SegmentLoadCommand64Size + NumSections * Section64Size :
1168 SegmentLoadCommand32Size + NumSections * Section32Size;
1169
1170 // Add the symbol table load command sizes, if used.
1171 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1172 UndefinedSymbolData.size();
1173 if (NumSymbols) {
1174 NumLoadCommands += 2;
1175 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
1176 }
1177
1178 // Compute the total size of the section data, as well as its file size and
1179 // vm size.
1180 uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
1181 + LoadCommandsSize;
1182 uint64_t SectionDataSize = 0;
1183 uint64_t SectionDataFileSize = 0;
1184 uint64_t VMSize = 0;
1185 for (MCAssembler::const_iterator it = Asm.begin(),
1186 ie = Asm.end(); it != ie; ++it) {
1187 const MCSectionData &SD = *it;
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001188 uint64_t Address = Layout.getSectionAddress(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +00001189 uint64_t Size = Layout.getSectionSize(&SD);
1190 uint64_t FileSize = Layout.getSectionFileSize(&SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001191
Daniel Dunbar5d428512010-03-25 02:00:07 +00001192 VMSize = std::max(VMSize, Address + Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001193
1194 if (Asm.getBackend().isVirtualSection(SD.getSection()))
1195 continue;
1196
Daniel Dunbar5d428512010-03-25 02:00:07 +00001197 SectionDataSize = std::max(SectionDataSize, Address + Size);
1198 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001199 }
1200
1201 // The section data is padded to 4 bytes.
1202 //
1203 // FIXME: Is this machine dependent?
1204 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1205 SectionDataFileSize += SectionDataPadding;
1206
1207 // Write the prolog, starting with the header and load command...
1208 WriteHeader(NumLoadCommands, LoadCommandsSize,
1209 Asm.getSubsectionsViaSymbols());
1210 WriteSegmentLoadCommand(NumSections, VMSize,
1211 SectionDataStart, SectionDataSize);
1212
1213 // ... and then the section headers.
1214 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1215 for (MCAssembler::const_iterator it = Asm.begin(),
1216 ie = Asm.end(); it != ie; ++it) {
1217 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1218 unsigned NumRelocs = Relocs.size();
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001219 uint64_t SectionStart = SectionDataStart + Layout.getSectionAddress(it);
1220 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001221 RelocTableEnd += NumRelocs * RelocationInfoSize;
1222 }
1223
1224 // Write the symbol table load command, if used.
1225 if (NumSymbols) {
1226 unsigned FirstLocalSymbol = 0;
1227 unsigned NumLocalSymbols = LocalSymbolData.size();
1228 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1229 unsigned NumExternalSymbols = ExternalSymbolData.size();
1230 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1231 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1232 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1233 unsigned NumSymTabSymbols =
1234 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1235 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1236 uint64_t IndirectSymbolOffset = 0;
1237
1238 // If used, the indirect symbols are written after the section data.
1239 if (NumIndirectSymbols)
1240 IndirectSymbolOffset = RelocTableEnd;
1241
1242 // The symbol table is written after the indirect symbol data.
1243 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1244
1245 // The string table is written after symbol table.
1246 uint64_t StringTableOffset =
1247 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
1248 Nlist32Size);
1249 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1250 StringTableOffset, StringTable.size());
1251
1252 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1253 FirstExternalSymbol, NumExternalSymbols,
1254 FirstUndefinedSymbol, NumUndefinedSymbols,
1255 IndirectSymbolOffset, NumIndirectSymbols);
1256 }
1257
1258 // Write the actual section data.
1259 for (MCAssembler::const_iterator it = Asm.begin(),
1260 ie = Asm.end(); it != ie; ++it)
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001261 Asm.WriteSectionData(it, Layout, this);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001262
1263 // Write the extra padding.
1264 WriteZeros(SectionDataPadding);
1265
1266 // Write the relocation entries.
1267 for (MCAssembler::const_iterator it = Asm.begin(),
1268 ie = Asm.end(); it != ie; ++it) {
1269 // Write the section relocation entries, in reverse order to match 'as'
1270 // (approximately, the exact algorithm is more complicated than this).
1271 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1272 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1273 Write32(Relocs[e - i - 1].Word0);
1274 Write32(Relocs[e - i - 1].Word1);
1275 }
1276 }
1277
1278 // Write the symbol table data, if used.
1279 if (NumSymbols) {
1280 // Write the indirect symbol entries.
1281 for (MCAssembler::const_indirect_symbol_iterator
1282 it = Asm.indirect_symbol_begin(),
1283 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1284 // Indirect symbols in the non lazy symbol pointer section have some
1285 // special handling.
1286 const MCSectionMachO &Section =
1287 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1288 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1289 // If this symbol is defined and internal, mark it as such.
1290 if (it->Symbol->isDefined() &&
1291 !Asm.getSymbolData(*it->Symbol).isExternal()) {
1292 uint32_t Flags = ISF_Local;
1293 if (it->Symbol->isAbsolute())
1294 Flags |= ISF_Absolute;
1295 Write32(Flags);
1296 continue;
1297 }
1298 }
1299
1300 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1301 }
1302
1303 // FIXME: Check that offsets match computed ones.
1304
1305 // Write the symbol table entries.
1306 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001307 WriteNlist(LocalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001308 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001309 WriteNlist(ExternalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001310 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001311 WriteNlist(UndefinedSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001312
1313 // Write the string table.
1314 OS << StringTable.str();
1315 }
1316 }
1317};
1318
1319}
1320
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001321MCObjectWriter *llvm::createMachObjectWriter(raw_ostream &OS, bool is64Bit,
1322 uint32_t CPUType,
1323 uint32_t CPUSubtype,
1324 bool IsLittleEndian) {
1325 return new MachObjectWriter(OS, is64Bit, CPUType, CPUSubtype, IsLittleEndian);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001326}