blob: 5a6066c6ee4dbae4ab30af848b51d38c34a44238 [file] [log] [blame]
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001//===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/MC/MachObjectWriter.h"
11#include "llvm/ADT/StringMap.h"
12#include "llvm/ADT/Twine.h"
13#include "llvm/MC/MCAssembler.h"
Daniel Dunbar207e06e2010-03-24 03:43:40 +000014#include "llvm/MC/MCAsmLayout.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000015#include "llvm/MC/MCExpr.h"
16#include "llvm/MC/MCObjectWriter.h"
17#include "llvm/MC/MCSectionMachO.h"
18#include "llvm/MC/MCSymbol.h"
Kevin Enderbya6eeb6e2010-05-07 21:44:23 +000019#include "llvm/MC/MCMachOSymbolFlags.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000020#include "llvm/MC/MCValue.h"
21#include "llvm/Support/ErrorHandling.h"
22#include "llvm/Support/MachO.h"
23#include "llvm/Target/TargetAsmBackend.h"
24
25// FIXME: Gross.
26#include "../Target/X86/X86FixupKinds.h"
27
28#include <vector>
29using namespace llvm;
30
31static unsigned getFixupKindLog2Size(unsigned Kind) {
32 switch (Kind) {
33 default: llvm_unreachable("invalid fixup kind!");
34 case X86::reloc_pcrel_1byte:
35 case FK_Data_1: return 0;
36 case FK_Data_2: return 1;
37 case X86::reloc_pcrel_4byte:
38 case X86::reloc_riprel_4byte:
Daniel Dunbar602b40f2010-03-19 18:07:55 +000039 case X86::reloc_riprel_4byte_movq_load:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000040 case FK_Data_4: return 2;
41 case FK_Data_8: return 3;
42 }
43}
44
45static bool isFixupKindPCRel(unsigned Kind) {
46 switch (Kind) {
47 default:
48 return false;
49 case X86::reloc_pcrel_1byte:
50 case X86::reloc_pcrel_4byte:
51 case X86::reloc_riprel_4byte:
Daniel Dunbar602b40f2010-03-19 18:07:55 +000052 case X86::reloc_riprel_4byte_movq_load:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000053 return true;
54 }
55}
56
Daniel Dunbar602b40f2010-03-19 18:07:55 +000057static bool isFixupKindRIPRel(unsigned Kind) {
58 return Kind == X86::reloc_riprel_4byte ||
59 Kind == X86::reloc_riprel_4byte_movq_load;
60}
61
Daniel Dunbare9460ec2010-05-10 23:15:13 +000062static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
63 // Undefined symbols are always extern.
64 if (SD->Symbol->isUndefined())
65 return true;
66
67 // References to weak definitions require external relocation entries; the
68 // definition may not always be the one in the same object file.
69 if (SD->getFlags() & SF_WeakDefinition)
70 return true;
71
72 // Otherwise, we can use an internal relocation.
73 return false;
74}
75
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000076namespace {
77
78class MachObjectWriterImpl {
79 // See <mach-o/loader.h>.
80 enum {
81 Header_Magic32 = 0xFEEDFACE,
82 Header_Magic64 = 0xFEEDFACF
83 };
84
85 enum {
86 Header32Size = 28,
87 Header64Size = 32,
88 SegmentLoadCommand32Size = 56,
89 SegmentLoadCommand64Size = 72,
90 Section32Size = 68,
91 Section64Size = 80,
92 SymtabLoadCommandSize = 24,
93 DysymtabLoadCommandSize = 80,
94 Nlist32Size = 12,
95 Nlist64Size = 16,
96 RelocationInfoSize = 8
97 };
98
99 enum HeaderFileType {
100 HFT_Object = 0x1
101 };
102
103 enum HeaderFlags {
104 HF_SubsectionsViaSymbols = 0x2000
105 };
106
107 enum LoadCommandType {
108 LCT_Segment = 0x1,
109 LCT_Symtab = 0x2,
110 LCT_Dysymtab = 0xb,
111 LCT_Segment64 = 0x19
112 };
113
114 // See <mach-o/nlist.h>.
115 enum SymbolTypeType {
116 STT_Undefined = 0x00,
117 STT_Absolute = 0x02,
118 STT_Section = 0x0e
119 };
120
121 enum SymbolTypeFlags {
122 // If any of these bits are set, then the entry is a stab entry number (see
123 // <mach-o/stab.h>. Otherwise the other masks apply.
124 STF_StabsEntryMask = 0xe0,
125
126 STF_TypeMask = 0x0e,
127 STF_External = 0x01,
128 STF_PrivateExtern = 0x10
129 };
130
131 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
132 /// symbol entry.
133 enum IndirectSymbolFlags {
134 ISF_Local = 0x80000000,
135 ISF_Absolute = 0x40000000
136 };
137
138 /// RelocationFlags - Special flags for addresses.
139 enum RelocationFlags {
140 RF_Scattered = 0x80000000
141 };
142
143 enum RelocationInfoType {
144 RIT_Vanilla = 0,
145 RIT_Pair = 1,
146 RIT_Difference = 2,
147 RIT_PreboundLazyPointer = 3,
Eric Christopher96ac5152010-05-26 00:02:12 +0000148 RIT_LocalDifference = 4,
149 RIT_TLV = 5
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000150 };
151
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000152 /// X86_64 uses its own relocation types.
153 enum RelocationInfoTypeX86_64 {
154 RIT_X86_64_Unsigned = 0,
155 RIT_X86_64_Signed = 1,
156 RIT_X86_64_Branch = 2,
157 RIT_X86_64_GOTLoad = 3,
158 RIT_X86_64_GOT = 4,
159 RIT_X86_64_Subtractor = 5,
160 RIT_X86_64_Signed1 = 6,
161 RIT_X86_64_Signed2 = 7,
Eric Christopher96ac5152010-05-26 00:02:12 +0000162 RIT_X86_64_Signed4 = 8,
163 RIT_X86_64_TLV = 9
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000164 };
165
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000166 /// MachSymbolData - Helper struct for containing some precomputed information
167 /// on symbols.
168 struct MachSymbolData {
169 MCSymbolData *SymbolData;
170 uint64_t StringIndex;
171 uint8_t SectionIndex;
172
173 // Support lexicographic sorting.
174 bool operator<(const MachSymbolData &RHS) const {
Benjamin Kramerc37791e2010-05-20 14:14:22 +0000175 return SymbolData->getSymbol().getName() <
176 RHS.SymbolData->getSymbol().getName();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000177 }
178 };
179
180 /// @name Relocation Data
181 /// @{
182
183 struct MachRelocationEntry {
184 uint32_t Word0;
185 uint32_t Word1;
186 };
187
188 llvm::DenseMap<const MCSectionData*,
189 std::vector<MachRelocationEntry> > Relocations;
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000190 llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000191
192 /// @}
193 /// @name Symbol Table Data
194 /// @{
195
196 SmallString<256> StringTable;
197 std::vector<MachSymbolData> LocalSymbolData;
198 std::vector<MachSymbolData> ExternalSymbolData;
199 std::vector<MachSymbolData> UndefinedSymbolData;
200
201 /// @}
202
203 MachObjectWriter *Writer;
204
205 raw_ostream &OS;
206
207 unsigned Is64Bit : 1;
208
209public:
210 MachObjectWriterImpl(MachObjectWriter *_Writer, bool _Is64Bit)
211 : Writer(_Writer), OS(Writer->getStream()), Is64Bit(_Is64Bit) {
212 }
213
214 void Write8(uint8_t Value) { Writer->Write8(Value); }
215 void Write16(uint16_t Value) { Writer->Write16(Value); }
216 void Write32(uint32_t Value) { Writer->Write32(Value); }
217 void Write64(uint64_t Value) { Writer->Write64(Value); }
218 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
219 void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
220 Writer->WriteBytes(Str, ZeroFillSize);
221 }
222
223 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
224 bool SubsectionsViaSymbols) {
225 uint32_t Flags = 0;
226
227 if (SubsectionsViaSymbols)
228 Flags |= HF_SubsectionsViaSymbols;
229
230 // struct mach_header (28 bytes) or
231 // struct mach_header_64 (32 bytes)
232
233 uint64_t Start = OS.tell();
234 (void) Start;
235
236 Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
237
238 // FIXME: Support cputype.
239 Write32(Is64Bit ? MachO::CPUTypeX86_64 : MachO::CPUTypeI386);
240 // FIXME: Support cpusubtype.
241 Write32(MachO::CPUSubType_I386_ALL);
242 Write32(HFT_Object);
243 Write32(NumLoadCommands); // Object files have a single load command, the
244 // segment.
245 Write32(LoadCommandsSize);
246 Write32(Flags);
247 if (Is64Bit)
248 Write32(0); // reserved
249
250 assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
251 }
252
253 /// WriteSegmentLoadCommand - Write a segment load command.
254 ///
255 /// \arg NumSections - The number of sections in this segment.
256 /// \arg SectionDataSize - The total size of the sections.
257 void WriteSegmentLoadCommand(unsigned NumSections,
258 uint64_t VMSize,
259 uint64_t SectionDataStartOffset,
260 uint64_t SectionDataSize) {
261 // struct segment_command (56 bytes) or
262 // struct segment_command_64 (72 bytes)
263
264 uint64_t Start = OS.tell();
265 (void) Start;
266
267 unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
268 SegmentLoadCommand32Size;
269 Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
270 Write32(SegmentLoadCommandSize +
271 NumSections * (Is64Bit ? Section64Size : Section32Size));
272
273 WriteBytes("", 16);
274 if (Is64Bit) {
275 Write64(0); // vmaddr
276 Write64(VMSize); // vmsize
277 Write64(SectionDataStartOffset); // file offset
278 Write64(SectionDataSize); // file size
279 } else {
280 Write32(0); // vmaddr
281 Write32(VMSize); // vmsize
282 Write32(SectionDataStartOffset); // file offset
283 Write32(SectionDataSize); // file size
284 }
285 Write32(0x7); // maxprot
286 Write32(0x7); // initprot
287 Write32(NumSections);
288 Write32(0); // flags
289
290 assert(OS.tell() - Start == SegmentLoadCommandSize);
291 }
292
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000293 void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
294 const MCSectionData &SD, uint64_t FileOffset,
295 uint64_t RelocationsStart, unsigned NumRelocations) {
Daniel Dunbar5d428512010-03-25 02:00:07 +0000296 uint64_t SectionSize = Layout.getSectionSize(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +0000297
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000298 // The offset is unused for virtual sections.
299 if (Asm.getBackend().isVirtualSection(SD.getSection())) {
Daniel Dunbarb026d642010-03-25 07:10:05 +0000300 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000301 FileOffset = 0;
302 }
303
304 // struct section (68 bytes) or
305 // struct section_64 (80 bytes)
306
307 uint64_t Start = OS.tell();
308 (void) Start;
309
Daniel Dunbar56279f42010-05-18 17:28:20 +0000310 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000311 WriteBytes(Section.getSectionName(), 16);
312 WriteBytes(Section.getSegmentName(), 16);
313 if (Is64Bit) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000314 Write64(Layout.getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000315 Write64(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000316 } else {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000317 Write32(Layout.getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000318 Write32(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000319 }
320 Write32(FileOffset);
321
322 unsigned Flags = Section.getTypeAndAttributes();
323 if (SD.hasInstructions())
324 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
325
326 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
327 Write32(Log2_32(SD.getAlignment()));
328 Write32(NumRelocations ? RelocationsStart : 0);
329 Write32(NumRelocations);
330 Write32(Flags);
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000331 Write32(IndirectSymBase.lookup(&SD)); // reserved1
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000332 Write32(Section.getStubSize()); // reserved2
333 if (Is64Bit)
334 Write32(0); // reserved3
335
336 assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
337 }
338
339 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
340 uint32_t StringTableOffset,
341 uint32_t StringTableSize) {
342 // struct symtab_command (24 bytes)
343
344 uint64_t Start = OS.tell();
345 (void) Start;
346
347 Write32(LCT_Symtab);
348 Write32(SymtabLoadCommandSize);
349 Write32(SymbolOffset);
350 Write32(NumSymbols);
351 Write32(StringTableOffset);
352 Write32(StringTableSize);
353
354 assert(OS.tell() - Start == SymtabLoadCommandSize);
355 }
356
357 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
358 uint32_t NumLocalSymbols,
359 uint32_t FirstExternalSymbol,
360 uint32_t NumExternalSymbols,
361 uint32_t FirstUndefinedSymbol,
362 uint32_t NumUndefinedSymbols,
363 uint32_t IndirectSymbolOffset,
364 uint32_t NumIndirectSymbols) {
365 // struct dysymtab_command (80 bytes)
366
367 uint64_t Start = OS.tell();
368 (void) Start;
369
370 Write32(LCT_Dysymtab);
371 Write32(DysymtabLoadCommandSize);
372 Write32(FirstLocalSymbol);
373 Write32(NumLocalSymbols);
374 Write32(FirstExternalSymbol);
375 Write32(NumExternalSymbols);
376 Write32(FirstUndefinedSymbol);
377 Write32(NumUndefinedSymbols);
378 Write32(0); // tocoff
379 Write32(0); // ntoc
380 Write32(0); // modtaboff
381 Write32(0); // nmodtab
382 Write32(0); // extrefsymoff
383 Write32(0); // nextrefsyms
384 Write32(IndirectSymbolOffset);
385 Write32(NumIndirectSymbols);
386 Write32(0); // extreloff
387 Write32(0); // nextrel
388 Write32(0); // locreloff
389 Write32(0); // nlocrel
390
391 assert(OS.tell() - Start == DysymtabLoadCommandSize);
392 }
393
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000394 void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000395 MCSymbolData &Data = *MSD.SymbolData;
396 const MCSymbol &Symbol = Data.getSymbol();
397 uint8_t Type = 0;
398 uint16_t Flags = Data.getFlags();
399 uint32_t Address = 0;
400
401 // Set the N_TYPE bits. See <mach-o/nlist.h>.
402 //
403 // FIXME: Are the prebound or indirect fields possible here?
404 if (Symbol.isUndefined())
405 Type = STT_Undefined;
406 else if (Symbol.isAbsolute())
407 Type = STT_Absolute;
408 else
409 Type = STT_Section;
410
411 // FIXME: Set STAB bits.
412
413 if (Data.isPrivateExtern())
414 Type |= STF_PrivateExtern;
415
416 // Set external bit.
417 if (Data.isExternal() || Symbol.isUndefined())
418 Type |= STF_External;
419
420 // Compute the symbol address.
421 if (Symbol.isDefined()) {
422 if (Symbol.isAbsolute()) {
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000423 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000424 } else {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000425 Address = Layout.getSymbolAddress(&Data);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000426 }
427 } else if (Data.isCommon()) {
428 // Common symbols are encoded with the size in the address
429 // field, and their alignment in the flags.
430 Address = Data.getCommonSize();
431
432 // Common alignment is packed into the 'desc' bits.
433 if (unsigned Align = Data.getCommonAlignment()) {
434 unsigned Log2Size = Log2_32(Align);
435 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
436 if (Log2Size > 15)
Chris Lattner75361b62010-04-07 22:58:41 +0000437 report_fatal_error("invalid 'common' alignment '" +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000438 Twine(Align) + "'");
439 // FIXME: Keep this mask with the SymbolFlags enumeration.
440 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
441 }
442 }
443
444 // struct nlist (12 bytes)
445
446 Write32(MSD.StringIndex);
447 Write8(Type);
448 Write8(MSD.SectionIndex);
449
450 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
451 // value.
452 Write16(Flags);
453 if (Is64Bit)
454 Write64(Address);
455 else
456 Write32(Address);
457 }
458
Daniel Dunbar35b06572010-03-22 23:16:43 +0000459 // FIXME: We really need to improve the relocation validation. Basically, we
460 // want to implement a separate computation which evaluates the relocation
461 // entry as the linker would, and verifies that the resultant fixup value is
462 // exactly what the encoder wanted. This will catch several classes of
463 // problems:
464 //
465 // - Relocation entry bugs, the two algorithms are unlikely to have the same
466 // exact bug.
467 //
468 // - Relaxation issues, where we forget to relax something.
469 //
470 // - Input errors, where something cannot be correctly encoded. 'as' allows
471 // these through in many cases.
472
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000473 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000474 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000475 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000476 uint64_t &FixedValue) {
Daniel Dunbar482ad802010-05-26 15:18:31 +0000477 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
478 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
479 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000480
481 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000482 uint32_t FixupOffset =
483 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
484 uint32_t FixupAddress =
485 Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000486 int64_t Value = 0;
487 unsigned Index = 0;
488 unsigned IsExtern = 0;
489 unsigned Type = 0;
490
491 Value = Target.getConstant();
492
493 if (IsPCRel) {
494 // Compensate for the relocation offset, Darwin x86_64 relocations only
495 // have the addend and appear to have attempted to define it to be the
496 // actual expression addend without the PCrel bias. However, instructions
497 // with data following the relocation are not accomodated for (see comment
498 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
Benjamin Kramer454c4ce2010-04-08 15:25:57 +0000499 Value += 1LL << Log2Size;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000500 }
501
502 if (Target.isAbsolute()) { // constant
503 // SymbolNum of 0 indicates the absolute section.
504 Type = RIT_X86_64_Unsigned;
505 Index = 0;
506
507 // FIXME: I believe this is broken, I don't think the linker can
508 // understand it. I think it would require a local relocation, but I'm not
509 // sure if that would work either. The official way to get an absolute
510 // PCrel relocation is to use an absolute symbol (which we don't support
511 // yet).
512 if (IsPCRel) {
513 IsExtern = 1;
514 Type = RIT_X86_64_Branch;
515 }
516 } else if (Target.getSymB()) { // A - B + constant
517 const MCSymbol *A = &Target.getSymA()->getSymbol();
518 MCSymbolData &A_SD = Asm.getSymbolData(*A);
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000519 const MCSymbolData *A_Base = Asm.getAtom(Layout, &A_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000520
521 const MCSymbol *B = &Target.getSymB()->getSymbol();
522 MCSymbolData &B_SD = Asm.getSymbolData(*B);
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000523 const MCSymbolData *B_Base = Asm.getAtom(Layout, &B_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000524
525 // Neither symbol can be modified.
526 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
527 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000528 report_fatal_error("unsupported relocation of modified symbol");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000529
530 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
531 // implement most of these correctly.
532 if (IsPCRel)
Chris Lattner75361b62010-04-07 22:58:41 +0000533 report_fatal_error("unsupported pc-relative relocation of difference");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000534
535 // We don't currently support any situation where one or both of the
536 // symbols would require a local relocation. This is almost certainly
537 // unused and may not be possible to encode correctly.
538 if (!A_Base || !B_Base)
Chris Lattner75361b62010-04-07 22:58:41 +0000539 report_fatal_error("unsupported local relocations in difference");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000540
541 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
542 // a single SIGNED relocation); reject it for now.
543 if (A_Base == B_Base)
Chris Lattner75361b62010-04-07 22:58:41 +0000544 report_fatal_error("unsupported relocation with identical base");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000545
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000546 Value += Layout.getSymbolAddress(&A_SD) - Layout.getSymbolAddress(A_Base);
547 Value -= Layout.getSymbolAddress(&B_SD) - Layout.getSymbolAddress(B_Base);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000548
549 Index = A_Base->getIndex();
550 IsExtern = 1;
551 Type = RIT_X86_64_Unsigned;
552
553 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000554 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000555 MRE.Word1 = ((Index << 0) |
556 (IsPCRel << 24) |
557 (Log2Size << 25) |
558 (IsExtern << 27) |
559 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000560 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000561
562 Index = B_Base->getIndex();
563 IsExtern = 1;
564 Type = RIT_X86_64_Subtractor;
565 } else {
566 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
567 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000568 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000569
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000570 // Relocations inside debug sections always use local relocations when
571 // possible. This seems to be done because the debugger doesn't fully
572 // understand x86_64 relocation entries, and expects to find values that
573 // have already been fixed up.
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000574 if (Symbol->isInSection()) {
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000575 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
576 Fragment->getParent()->getSection());
577 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
578 Base = 0;
579 }
580
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000581 // x86_64 almost always uses external relocations, except when there is no
582 // symbol to use as a base address (a local symbol with no preceeding
583 // non-local symbol).
584 if (Base) {
585 Index = Base->getIndex();
586 IsExtern = 1;
587
588 // Add the local offset, if needed.
589 if (Base != &SD)
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000590 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000591 } else if (Symbol->isInSection()) {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000592 // The index is the section ordinal (1-based).
593 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000594 IsExtern = 0;
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000595 Value += Layout.getSymbolAddress(&SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000596
597 if (IsPCRel)
Daniel Dunbardb4c7e62010-05-11 23:53:11 +0000598 Value -= FixupAddress + (1 << Log2Size);
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000599 } else {
600 report_fatal_error("unsupported relocation of undefined symbol '" +
601 Symbol->getName() + "'");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000602 }
603
604 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
605 if (IsPCRel) {
606 if (IsRIPRel) {
607 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
608 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
609 // rewrite the movq to an leaq at link time if the symbol ends up in
610 // the same linkage unit.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000611 if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000612 Type = RIT_X86_64_GOTLoad;
613 else
614 Type = RIT_X86_64_GOT;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000615 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
Eric Christopher96ac5152010-05-26 00:02:12 +0000616 Type = RIT_X86_64_TLV;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000617 } else if (Modifier != MCSymbolRefExpr::VK_None) {
618 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000619 } else {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000620 Type = RIT_X86_64_Signed;
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000621
622 // The Darwin x86_64 relocation format has a problem where it cannot
623 // encode an address (L<foo> + <constant>) which is outside the atom
624 // containing L<foo>. Generally, this shouldn't occur but it does
625 // happen when we have a RIPrel instruction with data following the
626 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
627 // adjustment Darwin x86_64 uses, the offset is still negative and
628 // the linker has no way to recognize this.
629 //
630 // To work around this, Darwin uses several special relocation types
631 // to indicate the offsets. However, the specification or
632 // implementation of these seems to also be incomplete; they should
633 // adjust the addend as well based on the actual encoded instruction
634 // (the additional bias), but instead appear to just look at the
635 // final offset.
636 switch (-(Target.getConstant() + (1LL << Log2Size))) {
637 case 1: Type = RIT_X86_64_Signed1; break;
638 case 2: Type = RIT_X86_64_Signed2; break;
639 case 4: Type = RIT_X86_64_Signed4; break;
640 }
641 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000642 } else {
643 if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000644 report_fatal_error("unsupported symbol modifier in branch "
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000645 "relocation");
646
647 Type = RIT_X86_64_Branch;
648 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000649 } else {
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000650 if (Modifier == MCSymbolRefExpr::VK_GOT) {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000651 Type = RIT_X86_64_GOT;
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000652 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
653 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
654 // which case all we do is set the PCrel bit in the relocation entry;
655 // this is used with exception handling, for example. The source is
656 // required to include any necessary offset directly.
657 Type = RIT_X86_64_GOT;
658 IsPCRel = 1;
Eric Christopher96ac5152010-05-26 00:02:12 +0000659 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
660 report_fatal_error("TLVP symbol modifier should have been rip-rel");
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000661 } else if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000662 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000663 else
664 Type = RIT_X86_64_Unsigned;
665 }
666 }
667
668 // x86_64 always writes custom values into the fixups.
669 FixedValue = Value;
670
671 // struct relocation_info (8 bytes)
672 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000673 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000674 MRE.Word1 = ((Index << 0) |
675 (IsPCRel << 24) |
676 (Log2Size << 25) |
677 (IsExtern << 27) |
678 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000679 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000680 }
681
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000682 void RecordScatteredRelocation(const MCAssembler &Asm,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000683 const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000684 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000685 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000686 uint64_t &FixedValue) {
Daniel Dunbar482ad802010-05-26 15:18:31 +0000687 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
688 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
689 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000690 unsigned Type = RIT_Vanilla;
691
692 // See <reloc.h>.
693 const MCSymbol *A = &Target.getSymA()->getSymbol();
694 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
695
696 if (!A_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000697 report_fatal_error("symbol '" + A->getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000698 "' can not be undefined in a subtraction expression");
699
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000700 uint32_t Value = Layout.getSymbolAddress(A_SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000701 uint32_t Value2 = 0;
702
703 if (const MCSymbolRefExpr *B = Target.getSymB()) {
704 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
705
706 if (!B_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000707 report_fatal_error("symbol '" + B->getSymbol().getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000708 "' can not be undefined in a subtraction expression");
709
710 // Select the appropriate difference relocation type.
711 //
712 // Note that there is no longer any semantic difference between these two
713 // relocation types from the linkers point of view, this is done solely
714 // for pedantic compatibility with 'as'.
715 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000716 Value2 = Layout.getSymbolAddress(B_SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000717 }
718
719 // Relocations are written out in reverse order, so the PAIR comes first.
720 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
721 MachRelocationEntry MRE;
722 MRE.Word0 = ((0 << 0) |
723 (RIT_Pair << 24) |
724 (Log2Size << 28) |
725 (IsPCRel << 30) |
726 RF_Scattered);
727 MRE.Word1 = Value2;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000728 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000729 }
730
731 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000732 MRE.Word0 = ((FixupOffset << 0) |
733 (Type << 24) |
734 (Log2Size << 28) |
735 (IsPCRel << 30) |
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000736 RF_Scattered);
737 MRE.Word1 = Value;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000738 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000739 }
740
Eric Christopherc9ada472010-06-15 22:59:05 +0000741 void RecordTLVPRelocation(const MCAssembler &Asm,
Eric Christophere48dbf82010-06-16 00:26:36 +0000742 const MCAsmLayout &Layout,
743 const MCFragment *Fragment,
744 const MCFixup &Fixup, MCValue Target,
745 uint64_t &FixedValue) {
Eric Christopherc9ada472010-06-15 22:59:05 +0000746 assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
747 !Is64Bit &&
748 "Should only be called with a 32-bit TLVP relocation!");
749
Eric Christopherc9ada472010-06-15 22:59:05 +0000750 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
751 uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
752 unsigned IsPCRel = 0;
753
754 // Get the symbol data.
755 MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
756 unsigned Index = SD_A->getIndex();
757
Eric Christopherbc067372010-06-16 21:32:38 +0000758 // We're only going to have a second symbol in pic mode and it'll be a
759 // subtraction from the picbase. For 32-bit pic the addend is the difference
Eric Christopher04b8d3c2010-06-17 00:49:46 +0000760 // between the picbase and the next address. For 32-bit static the addend
761 // is zero.
Eric Christopherbc067372010-06-16 21:32:38 +0000762 if (Target.getSymB()) {
Eric Christopher1008d352010-06-22 23:51:47 +0000763 // If this is a subtraction then we're pcrel.
764 uint32_t FixupAddress =
765 Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
766 MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
Eric Christopherc9ada472010-06-15 22:59:05 +0000767 IsPCRel = 1;
Eric Christopher1008d352010-06-22 23:51:47 +0000768 FixedValue = (FixupAddress - Layout.getSymbolAddress(SD_B) +
769 Target.getConstant());
770 FixedValue += 1 << Log2Size;
Eric Christopherbc067372010-06-16 21:32:38 +0000771 } else {
772 FixedValue = 0;
773 }
Eric Christopherc9ada472010-06-15 22:59:05 +0000774
775 // struct relocation_info (8 bytes)
776 MachRelocationEntry MRE;
777 MRE.Word0 = Value;
778 MRE.Word1 = ((Index << 0) |
779 (IsPCRel << 24) |
780 (Log2Size << 25) |
781 (1 << 27) | // Extern
782 (RIT_TLV << 28)); // Type
783 Relocations[Fragment->getParent()].push_back(MRE);
784 }
785
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000786 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000787 const MCFragment *Fragment, const MCFixup &Fixup,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000788 MCValue Target, uint64_t &FixedValue) {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000789 if (Is64Bit) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000790 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000791 return;
792 }
793
Daniel Dunbar482ad802010-05-26 15:18:31 +0000794 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
795 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000796
Eric Christopherc9ada472010-06-15 22:59:05 +0000797 // If this is a 32-bit TLVP reloc it's handled a bit differently.
798 if (Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
799 RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
800 return;
801 }
802
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000803 // If this is a difference or a defined symbol plus an offset, then we need
804 // a scattered relocation entry.
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000805 // Differences always require scattered relocations.
806 if (Target.getSymB())
807 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
808 Target, FixedValue);
809
810 // Get the symbol data, if any.
811 MCSymbolData *SD = 0;
812 if (Target.getSymA())
813 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
814
815 // If this is an internal relocation with an offset, it also needs a
816 // scattered relocation entry.
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000817 uint32_t Offset = Target.getConstant();
818 if (IsPCRel)
819 Offset += 1 << Log2Size;
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000820 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
821 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
822 Target, FixedValue);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000823
824 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000825 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000826 uint32_t Value = 0;
827 unsigned Index = 0;
828 unsigned IsExtern = 0;
829 unsigned Type = 0;
830
831 if (Target.isAbsolute()) { // constant
832 // SymbolNum of 0 indicates the absolute section.
833 //
834 // FIXME: Currently, these are never generated (see code below). I cannot
835 // find a case where they are actually emitted.
836 Type = RIT_Vanilla;
837 Value = 0;
838 } else {
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000839 // Check whether we need an external or internal relocation.
840 if (doesSymbolRequireExternRelocation(SD)) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000841 IsExtern = 1;
842 Index = SD->getIndex();
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000843 // For external relocations, make sure to offset the fixup value to
844 // compensate for the addend of the symbol address, if it was
845 // undefined. This occurs with weak definitions, for example.
846 if (!SD->Symbol->isUndefined())
Kevin Enderbya6eeb6e2010-05-07 21:44:23 +0000847 FixedValue -= Layout.getSymbolAddress(SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000848 Value = 0;
849 } else {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000850 // The index is the section ordinal (1-based).
851 Index = SD->getFragment()->getParent()->getOrdinal() + 1;
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000852 Value = Layout.getSymbolAddress(SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000853 }
854
855 Type = RIT_Vanilla;
856 }
857
858 // struct relocation_info (8 bytes)
859 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000860 MRE.Word0 = FixupOffset;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000861 MRE.Word1 = ((Index << 0) |
862 (IsPCRel << 24) |
863 (Log2Size << 25) |
864 (IsExtern << 27) |
865 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000866 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000867 }
868
869 void BindIndirectSymbols(MCAssembler &Asm) {
870 // This is the point where 'as' creates actual symbols for indirect symbols
871 // (in the following two passes). It would be easier for us to do this
872 // sooner when we see the attribute, but that makes getting the order in the
873 // symbol table much more complicated than it is worth.
874 //
875 // FIXME: Revisit this when the dust settles.
876
877 // Bind non lazy symbol pointers first.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000878 unsigned IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000879 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000880 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000881 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +0000882 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000883
884 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
885 continue;
886
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000887 // Initialize the section indirect symbol base, if necessary.
888 if (!IndirectSymBase.count(it->SectionData))
889 IndirectSymBase[it->SectionData] = IndirectIndex;
890
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000891 Asm.getOrCreateSymbolData(*it->Symbol);
892 }
893
894 // Then lazy symbol pointers and symbol stubs.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000895 IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000896 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000897 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000898 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +0000899 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000900
901 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
902 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
903 continue;
904
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000905 // Initialize the section indirect symbol base, if necessary.
906 if (!IndirectSymBase.count(it->SectionData))
907 IndirectSymBase[it->SectionData] = IndirectIndex;
908
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000909 // Set the symbol type to undefined lazy, but only on construction.
910 //
911 // FIXME: Do not hardcode.
912 bool Created;
913 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
914 if (Created)
915 Entry.setFlags(Entry.getFlags() | 0x0001);
916 }
917 }
918
919 /// ComputeSymbolTable - Compute the symbol table data
920 ///
921 /// \param StringTable [out] - The string table data.
922 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
923 /// string table.
924 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
925 std::vector<MachSymbolData> &LocalSymbolData,
926 std::vector<MachSymbolData> &ExternalSymbolData,
927 std::vector<MachSymbolData> &UndefinedSymbolData) {
928 // Build section lookup table.
929 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
930 unsigned Index = 1;
931 for (MCAssembler::iterator it = Asm.begin(),
932 ie = Asm.end(); it != ie; ++it, ++Index)
933 SectionIndexMap[&it->getSection()] = Index;
934 assert(Index <= 256 && "Too many sections!");
935
936 // Index 0 is always the empty string.
937 StringMap<uint64_t> StringIndexMap;
938 StringTable += '\x00';
939
940 // Build the symbol arrays and the string table, but only for non-local
941 // symbols.
942 //
943 // The particular order that we collect the symbols and create the string
944 // table, then sort the symbols is chosen to match 'as'. Even though it
945 // doesn't matter for correctness, this is important for letting us diff .o
946 // files.
947 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
948 ie = Asm.symbol_end(); it != ie; ++it) {
949 const MCSymbol &Symbol = it->getSymbol();
950
951 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +0000952 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000953 continue;
954
955 if (!it->isExternal() && !Symbol.isUndefined())
956 continue;
957
958 uint64_t &Entry = StringIndexMap[Symbol.getName()];
959 if (!Entry) {
960 Entry = StringTable.size();
961 StringTable += Symbol.getName();
962 StringTable += '\x00';
963 }
964
965 MachSymbolData MSD;
966 MSD.SymbolData = it;
967 MSD.StringIndex = Entry;
968
969 if (Symbol.isUndefined()) {
970 MSD.SectionIndex = 0;
971 UndefinedSymbolData.push_back(MSD);
972 } else if (Symbol.isAbsolute()) {
973 MSD.SectionIndex = 0;
974 ExternalSymbolData.push_back(MSD);
975 } else {
976 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
977 assert(MSD.SectionIndex && "Invalid section index!");
978 ExternalSymbolData.push_back(MSD);
979 }
980 }
981
982 // Now add the data for local symbols.
983 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
984 ie = Asm.symbol_end(); it != ie; ++it) {
985 const MCSymbol &Symbol = it->getSymbol();
986
987 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +0000988 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000989 continue;
990
991 if (it->isExternal() || Symbol.isUndefined())
992 continue;
993
994 uint64_t &Entry = StringIndexMap[Symbol.getName()];
995 if (!Entry) {
996 Entry = StringTable.size();
997 StringTable += Symbol.getName();
998 StringTable += '\x00';
999 }
1000
1001 MachSymbolData MSD;
1002 MSD.SymbolData = it;
1003 MSD.StringIndex = Entry;
1004
1005 if (Symbol.isAbsolute()) {
1006 MSD.SectionIndex = 0;
1007 LocalSymbolData.push_back(MSD);
1008 } else {
1009 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1010 assert(MSD.SectionIndex && "Invalid section index!");
1011 LocalSymbolData.push_back(MSD);
1012 }
1013 }
1014
1015 // External and undefined symbols are required to be in lexicographic order.
1016 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1017 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1018
1019 // Set the symbol indices.
1020 Index = 0;
1021 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1022 LocalSymbolData[i].SymbolData->setIndex(Index++);
1023 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1024 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1025 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1026 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1027
1028 // The string table is padded to a multiple of 4.
1029 while (StringTable.size() % 4)
1030 StringTable += '\x00';
1031 }
1032
Daniel Dunbar873decb2010-03-20 01:58:40 +00001033 void ExecutePostLayoutBinding(MCAssembler &Asm) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001034 // Create symbol data for any indirect symbols.
1035 BindIndirectSymbols(Asm);
1036
1037 // Compute symbol table information and bind symbol indices.
1038 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1039 UndefinedSymbolData);
1040 }
1041
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001042 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001043 unsigned NumSections = Asm.size();
1044
1045 // The section data starts after the header, the segment load command (and
1046 // section headers) and the symbol table.
1047 unsigned NumLoadCommands = 1;
1048 uint64_t LoadCommandsSize = Is64Bit ?
1049 SegmentLoadCommand64Size + NumSections * Section64Size :
1050 SegmentLoadCommand32Size + NumSections * Section32Size;
1051
1052 // Add the symbol table load command sizes, if used.
1053 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1054 UndefinedSymbolData.size();
1055 if (NumSymbols) {
1056 NumLoadCommands += 2;
1057 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
1058 }
1059
1060 // Compute the total size of the section data, as well as its file size and
1061 // vm size.
1062 uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
1063 + LoadCommandsSize;
1064 uint64_t SectionDataSize = 0;
1065 uint64_t SectionDataFileSize = 0;
1066 uint64_t VMSize = 0;
1067 for (MCAssembler::const_iterator it = Asm.begin(),
1068 ie = Asm.end(); it != ie; ++it) {
1069 const MCSectionData &SD = *it;
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001070 uint64_t Address = Layout.getSectionAddress(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +00001071 uint64_t Size = Layout.getSectionSize(&SD);
1072 uint64_t FileSize = Layout.getSectionFileSize(&SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001073
Daniel Dunbar5d428512010-03-25 02:00:07 +00001074 VMSize = std::max(VMSize, Address + Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001075
1076 if (Asm.getBackend().isVirtualSection(SD.getSection()))
1077 continue;
1078
Daniel Dunbar5d428512010-03-25 02:00:07 +00001079 SectionDataSize = std::max(SectionDataSize, Address + Size);
1080 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001081 }
1082
1083 // The section data is padded to 4 bytes.
1084 //
1085 // FIXME: Is this machine dependent?
1086 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1087 SectionDataFileSize += SectionDataPadding;
1088
1089 // Write the prolog, starting with the header and load command...
1090 WriteHeader(NumLoadCommands, LoadCommandsSize,
1091 Asm.getSubsectionsViaSymbols());
1092 WriteSegmentLoadCommand(NumSections, VMSize,
1093 SectionDataStart, SectionDataSize);
1094
1095 // ... and then the section headers.
1096 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1097 for (MCAssembler::const_iterator it = Asm.begin(),
1098 ie = Asm.end(); it != ie; ++it) {
1099 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1100 unsigned NumRelocs = Relocs.size();
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001101 uint64_t SectionStart = SectionDataStart + Layout.getSectionAddress(it);
1102 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001103 RelocTableEnd += NumRelocs * RelocationInfoSize;
1104 }
1105
1106 // Write the symbol table load command, if used.
1107 if (NumSymbols) {
1108 unsigned FirstLocalSymbol = 0;
1109 unsigned NumLocalSymbols = LocalSymbolData.size();
1110 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1111 unsigned NumExternalSymbols = ExternalSymbolData.size();
1112 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1113 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1114 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1115 unsigned NumSymTabSymbols =
1116 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1117 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1118 uint64_t IndirectSymbolOffset = 0;
1119
1120 // If used, the indirect symbols are written after the section data.
1121 if (NumIndirectSymbols)
1122 IndirectSymbolOffset = RelocTableEnd;
1123
1124 // The symbol table is written after the indirect symbol data.
1125 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1126
1127 // The string table is written after symbol table.
1128 uint64_t StringTableOffset =
1129 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
1130 Nlist32Size);
1131 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1132 StringTableOffset, StringTable.size());
1133
1134 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1135 FirstExternalSymbol, NumExternalSymbols,
1136 FirstUndefinedSymbol, NumUndefinedSymbols,
1137 IndirectSymbolOffset, NumIndirectSymbols);
1138 }
1139
1140 // Write the actual section data.
1141 for (MCAssembler::const_iterator it = Asm.begin(),
1142 ie = Asm.end(); it != ie; ++it)
Daniel Dunbar432cd5f2010-03-25 02:00:02 +00001143 Asm.WriteSectionData(it, Layout, Writer);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001144
1145 // Write the extra padding.
1146 WriteZeros(SectionDataPadding);
1147
1148 // Write the relocation entries.
1149 for (MCAssembler::const_iterator it = Asm.begin(),
1150 ie = Asm.end(); it != ie; ++it) {
1151 // Write the section relocation entries, in reverse order to match 'as'
1152 // (approximately, the exact algorithm is more complicated than this).
1153 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1154 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1155 Write32(Relocs[e - i - 1].Word0);
1156 Write32(Relocs[e - i - 1].Word1);
1157 }
1158 }
1159
1160 // Write the symbol table data, if used.
1161 if (NumSymbols) {
1162 // Write the indirect symbol entries.
1163 for (MCAssembler::const_indirect_symbol_iterator
1164 it = Asm.indirect_symbol_begin(),
1165 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1166 // Indirect symbols in the non lazy symbol pointer section have some
1167 // special handling.
1168 const MCSectionMachO &Section =
1169 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1170 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1171 // If this symbol is defined and internal, mark it as such.
1172 if (it->Symbol->isDefined() &&
1173 !Asm.getSymbolData(*it->Symbol).isExternal()) {
1174 uint32_t Flags = ISF_Local;
1175 if (it->Symbol->isAbsolute())
1176 Flags |= ISF_Absolute;
1177 Write32(Flags);
1178 continue;
1179 }
1180 }
1181
1182 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1183 }
1184
1185 // FIXME: Check that offsets match computed ones.
1186
1187 // Write the symbol table entries.
1188 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001189 WriteNlist(LocalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001190 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001191 WriteNlist(ExternalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001192 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001193 WriteNlist(UndefinedSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001194
1195 // Write the string table.
1196 OS << StringTable.str();
1197 }
1198 }
1199};
1200
1201}
1202
1203MachObjectWriter::MachObjectWriter(raw_ostream &OS,
1204 bool Is64Bit,
1205 bool IsLittleEndian)
1206 : MCObjectWriter(OS, IsLittleEndian)
1207{
1208 Impl = new MachObjectWriterImpl(this, Is64Bit);
1209}
1210
1211MachObjectWriter::~MachObjectWriter() {
1212 delete (MachObjectWriterImpl*) Impl;
1213}
1214
1215void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1216 ((MachObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1217}
1218
1219void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001220 const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +00001221 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +00001222 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001223 uint64_t &FixedValue) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001224 ((MachObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001225 Target, FixedValue);
1226}
1227
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001228void MachObjectWriter::WriteObject(const MCAssembler &Asm,
1229 const MCAsmLayout &Layout) {
1230 ((MachObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001231}