blob: 4c5be44e11e77004559719df51512b1f95125d16 [file] [log] [blame]
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001//===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/MC/MachObjectWriter.h"
11#include "llvm/ADT/StringMap.h"
12#include "llvm/ADT/Twine.h"
13#include "llvm/MC/MCAssembler.h"
Daniel Dunbar207e06e2010-03-24 03:43:40 +000014#include "llvm/MC/MCAsmLayout.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000015#include "llvm/MC/MCExpr.h"
16#include "llvm/MC/MCObjectWriter.h"
17#include "llvm/MC/MCSectionMachO.h"
18#include "llvm/MC/MCSymbol.h"
Kevin Enderbya6eeb6e2010-05-07 21:44:23 +000019#include "llvm/MC/MCMachOSymbolFlags.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000020#include "llvm/MC/MCValue.h"
21#include "llvm/Support/ErrorHandling.h"
22#include "llvm/Support/MachO.h"
23#include "llvm/Target/TargetAsmBackend.h"
24
25// FIXME: Gross.
26#include "../Target/X86/X86FixupKinds.h"
27
28#include <vector>
29using namespace llvm;
30
31static unsigned getFixupKindLog2Size(unsigned Kind) {
32 switch (Kind) {
33 default: llvm_unreachable("invalid fixup kind!");
34 case X86::reloc_pcrel_1byte:
35 case FK_Data_1: return 0;
Chris Lattnerda3051a2010-07-07 22:35:13 +000036 case X86::reloc_pcrel_2byte:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000037 case FK_Data_2: return 1;
38 case X86::reloc_pcrel_4byte:
39 case X86::reloc_riprel_4byte:
Daniel Dunbar602b40f2010-03-19 18:07:55 +000040 case X86::reloc_riprel_4byte_movq_load:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000041 case FK_Data_4: return 2;
42 case FK_Data_8: return 3;
43 }
44}
45
46static bool isFixupKindPCRel(unsigned Kind) {
47 switch (Kind) {
48 default:
49 return false;
50 case X86::reloc_pcrel_1byte:
Chris Lattnerda3051a2010-07-07 22:35:13 +000051 case X86::reloc_pcrel_2byte:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000052 case X86::reloc_pcrel_4byte:
53 case X86::reloc_riprel_4byte:
Daniel Dunbar602b40f2010-03-19 18:07:55 +000054 case X86::reloc_riprel_4byte_movq_load:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000055 return true;
56 }
57}
58
Daniel Dunbar602b40f2010-03-19 18:07:55 +000059static bool isFixupKindRIPRel(unsigned Kind) {
60 return Kind == X86::reloc_riprel_4byte ||
61 Kind == X86::reloc_riprel_4byte_movq_load;
62}
63
Daniel Dunbare9460ec2010-05-10 23:15:13 +000064static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
65 // Undefined symbols are always extern.
66 if (SD->Symbol->isUndefined())
67 return true;
68
69 // References to weak definitions require external relocation entries; the
70 // definition may not always be the one in the same object file.
71 if (SD->getFlags() & SF_WeakDefinition)
72 return true;
73
74 // Otherwise, we can use an internal relocation.
75 return false;
76}
77
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000078namespace {
79
80class MachObjectWriterImpl {
81 // See <mach-o/loader.h>.
82 enum {
83 Header_Magic32 = 0xFEEDFACE,
84 Header_Magic64 = 0xFEEDFACF
85 };
86
87 enum {
88 Header32Size = 28,
89 Header64Size = 32,
90 SegmentLoadCommand32Size = 56,
91 SegmentLoadCommand64Size = 72,
92 Section32Size = 68,
93 Section64Size = 80,
94 SymtabLoadCommandSize = 24,
95 DysymtabLoadCommandSize = 80,
96 Nlist32Size = 12,
97 Nlist64Size = 16,
98 RelocationInfoSize = 8
99 };
100
101 enum HeaderFileType {
102 HFT_Object = 0x1
103 };
104
105 enum HeaderFlags {
106 HF_SubsectionsViaSymbols = 0x2000
107 };
108
109 enum LoadCommandType {
110 LCT_Segment = 0x1,
111 LCT_Symtab = 0x2,
112 LCT_Dysymtab = 0xb,
113 LCT_Segment64 = 0x19
114 };
115
116 // See <mach-o/nlist.h>.
117 enum SymbolTypeType {
118 STT_Undefined = 0x00,
119 STT_Absolute = 0x02,
120 STT_Section = 0x0e
121 };
122
123 enum SymbolTypeFlags {
124 // If any of these bits are set, then the entry is a stab entry number (see
125 // <mach-o/stab.h>. Otherwise the other masks apply.
126 STF_StabsEntryMask = 0xe0,
127
128 STF_TypeMask = 0x0e,
129 STF_External = 0x01,
130 STF_PrivateExtern = 0x10
131 };
132
133 /// IndirectSymbolFlags - Flags for encoding special values in the indirect
134 /// symbol entry.
135 enum IndirectSymbolFlags {
136 ISF_Local = 0x80000000,
137 ISF_Absolute = 0x40000000
138 };
139
140 /// RelocationFlags - Special flags for addresses.
141 enum RelocationFlags {
142 RF_Scattered = 0x80000000
143 };
144
145 enum RelocationInfoType {
146 RIT_Vanilla = 0,
147 RIT_Pair = 1,
148 RIT_Difference = 2,
149 RIT_PreboundLazyPointer = 3,
Eric Christopher96ac5152010-05-26 00:02:12 +0000150 RIT_LocalDifference = 4,
151 RIT_TLV = 5
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000152 };
153
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000154 /// X86_64 uses its own relocation types.
155 enum RelocationInfoTypeX86_64 {
156 RIT_X86_64_Unsigned = 0,
157 RIT_X86_64_Signed = 1,
158 RIT_X86_64_Branch = 2,
159 RIT_X86_64_GOTLoad = 3,
160 RIT_X86_64_GOT = 4,
161 RIT_X86_64_Subtractor = 5,
162 RIT_X86_64_Signed1 = 6,
163 RIT_X86_64_Signed2 = 7,
Eric Christopher96ac5152010-05-26 00:02:12 +0000164 RIT_X86_64_Signed4 = 8,
165 RIT_X86_64_TLV = 9
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000166 };
167
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000168 /// MachSymbolData - Helper struct for containing some precomputed information
169 /// on symbols.
170 struct MachSymbolData {
171 MCSymbolData *SymbolData;
172 uint64_t StringIndex;
173 uint8_t SectionIndex;
174
175 // Support lexicographic sorting.
176 bool operator<(const MachSymbolData &RHS) const {
Benjamin Kramerc37791e2010-05-20 14:14:22 +0000177 return SymbolData->getSymbol().getName() <
178 RHS.SymbolData->getSymbol().getName();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000179 }
180 };
181
182 /// @name Relocation Data
183 /// @{
184
185 struct MachRelocationEntry {
186 uint32_t Word0;
187 uint32_t Word1;
188 };
189
190 llvm::DenseMap<const MCSectionData*,
191 std::vector<MachRelocationEntry> > Relocations;
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000192 llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000193
194 /// @}
195 /// @name Symbol Table Data
196 /// @{
197
198 SmallString<256> StringTable;
199 std::vector<MachSymbolData> LocalSymbolData;
200 std::vector<MachSymbolData> ExternalSymbolData;
201 std::vector<MachSymbolData> UndefinedSymbolData;
202
203 /// @}
204
205 MachObjectWriter *Writer;
206
207 raw_ostream &OS;
208
209 unsigned Is64Bit : 1;
210
211public:
212 MachObjectWriterImpl(MachObjectWriter *_Writer, bool _Is64Bit)
213 : Writer(_Writer), OS(Writer->getStream()), Is64Bit(_Is64Bit) {
214 }
215
216 void Write8(uint8_t Value) { Writer->Write8(Value); }
217 void Write16(uint16_t Value) { Writer->Write16(Value); }
218 void Write32(uint32_t Value) { Writer->Write32(Value); }
219 void Write64(uint64_t Value) { Writer->Write64(Value); }
220 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
221 void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
222 Writer->WriteBytes(Str, ZeroFillSize);
223 }
224
225 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
226 bool SubsectionsViaSymbols) {
227 uint32_t Flags = 0;
228
229 if (SubsectionsViaSymbols)
230 Flags |= HF_SubsectionsViaSymbols;
231
232 // struct mach_header (28 bytes) or
233 // struct mach_header_64 (32 bytes)
234
235 uint64_t Start = OS.tell();
236 (void) Start;
237
238 Write32(Is64Bit ? Header_Magic64 : Header_Magic32);
239
240 // FIXME: Support cputype.
241 Write32(Is64Bit ? MachO::CPUTypeX86_64 : MachO::CPUTypeI386);
242 // FIXME: Support cpusubtype.
243 Write32(MachO::CPUSubType_I386_ALL);
244 Write32(HFT_Object);
245 Write32(NumLoadCommands); // Object files have a single load command, the
246 // segment.
247 Write32(LoadCommandsSize);
248 Write32(Flags);
249 if (Is64Bit)
250 Write32(0); // reserved
251
252 assert(OS.tell() - Start == Is64Bit ? Header64Size : Header32Size);
253 }
254
255 /// WriteSegmentLoadCommand - Write a segment load command.
256 ///
257 /// \arg NumSections - The number of sections in this segment.
258 /// \arg SectionDataSize - The total size of the sections.
259 void WriteSegmentLoadCommand(unsigned NumSections,
260 uint64_t VMSize,
261 uint64_t SectionDataStartOffset,
262 uint64_t SectionDataSize) {
263 // struct segment_command (56 bytes) or
264 // struct segment_command_64 (72 bytes)
265
266 uint64_t Start = OS.tell();
267 (void) Start;
268
269 unsigned SegmentLoadCommandSize = Is64Bit ? SegmentLoadCommand64Size :
270 SegmentLoadCommand32Size;
271 Write32(Is64Bit ? LCT_Segment64 : LCT_Segment);
272 Write32(SegmentLoadCommandSize +
273 NumSections * (Is64Bit ? Section64Size : Section32Size));
274
275 WriteBytes("", 16);
276 if (Is64Bit) {
277 Write64(0); // vmaddr
278 Write64(VMSize); // vmsize
279 Write64(SectionDataStartOffset); // file offset
280 Write64(SectionDataSize); // file size
281 } else {
282 Write32(0); // vmaddr
283 Write32(VMSize); // vmsize
284 Write32(SectionDataStartOffset); // file offset
285 Write32(SectionDataSize); // file size
286 }
287 Write32(0x7); // maxprot
288 Write32(0x7); // initprot
289 Write32(NumSections);
290 Write32(0); // flags
291
292 assert(OS.tell() - Start == SegmentLoadCommandSize);
293 }
294
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000295 void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
296 const MCSectionData &SD, uint64_t FileOffset,
297 uint64_t RelocationsStart, unsigned NumRelocations) {
Daniel Dunbar5d428512010-03-25 02:00:07 +0000298 uint64_t SectionSize = Layout.getSectionSize(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +0000299
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000300 // The offset is unused for virtual sections.
301 if (Asm.getBackend().isVirtualSection(SD.getSection())) {
Daniel Dunbarb026d642010-03-25 07:10:05 +0000302 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000303 FileOffset = 0;
304 }
305
306 // struct section (68 bytes) or
307 // struct section_64 (80 bytes)
308
309 uint64_t Start = OS.tell();
310 (void) Start;
311
Daniel Dunbar56279f42010-05-18 17:28:20 +0000312 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000313 WriteBytes(Section.getSectionName(), 16);
314 WriteBytes(Section.getSegmentName(), 16);
315 if (Is64Bit) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000316 Write64(Layout.getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000317 Write64(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000318 } else {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000319 Write32(Layout.getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000320 Write32(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000321 }
322 Write32(FileOffset);
323
324 unsigned Flags = Section.getTypeAndAttributes();
325 if (SD.hasInstructions())
326 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
327
328 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
329 Write32(Log2_32(SD.getAlignment()));
330 Write32(NumRelocations ? RelocationsStart : 0);
331 Write32(NumRelocations);
332 Write32(Flags);
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000333 Write32(IndirectSymBase.lookup(&SD)); // reserved1
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000334 Write32(Section.getStubSize()); // reserved2
335 if (Is64Bit)
336 Write32(0); // reserved3
337
338 assert(OS.tell() - Start == Is64Bit ? Section64Size : Section32Size);
339 }
340
341 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
342 uint32_t StringTableOffset,
343 uint32_t StringTableSize) {
344 // struct symtab_command (24 bytes)
345
346 uint64_t Start = OS.tell();
347 (void) Start;
348
349 Write32(LCT_Symtab);
350 Write32(SymtabLoadCommandSize);
351 Write32(SymbolOffset);
352 Write32(NumSymbols);
353 Write32(StringTableOffset);
354 Write32(StringTableSize);
355
356 assert(OS.tell() - Start == SymtabLoadCommandSize);
357 }
358
359 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
360 uint32_t NumLocalSymbols,
361 uint32_t FirstExternalSymbol,
362 uint32_t NumExternalSymbols,
363 uint32_t FirstUndefinedSymbol,
364 uint32_t NumUndefinedSymbols,
365 uint32_t IndirectSymbolOffset,
366 uint32_t NumIndirectSymbols) {
367 // struct dysymtab_command (80 bytes)
368
369 uint64_t Start = OS.tell();
370 (void) Start;
371
372 Write32(LCT_Dysymtab);
373 Write32(DysymtabLoadCommandSize);
374 Write32(FirstLocalSymbol);
375 Write32(NumLocalSymbols);
376 Write32(FirstExternalSymbol);
377 Write32(NumExternalSymbols);
378 Write32(FirstUndefinedSymbol);
379 Write32(NumUndefinedSymbols);
380 Write32(0); // tocoff
381 Write32(0); // ntoc
382 Write32(0); // modtaboff
383 Write32(0); // nmodtab
384 Write32(0); // extrefsymoff
385 Write32(0); // nextrefsyms
386 Write32(IndirectSymbolOffset);
387 Write32(NumIndirectSymbols);
388 Write32(0); // extreloff
389 Write32(0); // nextrel
390 Write32(0); // locreloff
391 Write32(0); // nlocrel
392
393 assert(OS.tell() - Start == DysymtabLoadCommandSize);
394 }
395
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000396 void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000397 MCSymbolData &Data = *MSD.SymbolData;
398 const MCSymbol &Symbol = Data.getSymbol();
399 uint8_t Type = 0;
400 uint16_t Flags = Data.getFlags();
401 uint32_t Address = 0;
402
403 // Set the N_TYPE bits. See <mach-o/nlist.h>.
404 //
405 // FIXME: Are the prebound or indirect fields possible here?
406 if (Symbol.isUndefined())
407 Type = STT_Undefined;
408 else if (Symbol.isAbsolute())
409 Type = STT_Absolute;
410 else
411 Type = STT_Section;
412
413 // FIXME: Set STAB bits.
414
415 if (Data.isPrivateExtern())
416 Type |= STF_PrivateExtern;
417
418 // Set external bit.
419 if (Data.isExternal() || Symbol.isUndefined())
420 Type |= STF_External;
421
422 // Compute the symbol address.
423 if (Symbol.isDefined()) {
424 if (Symbol.isAbsolute()) {
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000425 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000426 } else {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000427 Address = Layout.getSymbolAddress(&Data);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000428 }
429 } else if (Data.isCommon()) {
430 // Common symbols are encoded with the size in the address
431 // field, and their alignment in the flags.
432 Address = Data.getCommonSize();
433
434 // Common alignment is packed into the 'desc' bits.
435 if (unsigned Align = Data.getCommonAlignment()) {
436 unsigned Log2Size = Log2_32(Align);
437 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
438 if (Log2Size > 15)
Chris Lattner75361b62010-04-07 22:58:41 +0000439 report_fatal_error("invalid 'common' alignment '" +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000440 Twine(Align) + "'");
441 // FIXME: Keep this mask with the SymbolFlags enumeration.
442 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
443 }
444 }
445
446 // struct nlist (12 bytes)
447
448 Write32(MSD.StringIndex);
449 Write8(Type);
450 Write8(MSD.SectionIndex);
451
452 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
453 // value.
454 Write16(Flags);
455 if (Is64Bit)
456 Write64(Address);
457 else
458 Write32(Address);
459 }
460
Daniel Dunbar35b06572010-03-22 23:16:43 +0000461 // FIXME: We really need to improve the relocation validation. Basically, we
462 // want to implement a separate computation which evaluates the relocation
463 // entry as the linker would, and verifies that the resultant fixup value is
464 // exactly what the encoder wanted. This will catch several classes of
465 // problems:
466 //
467 // - Relocation entry bugs, the two algorithms are unlikely to have the same
468 // exact bug.
469 //
470 // - Relaxation issues, where we forget to relax something.
471 //
472 // - Input errors, where something cannot be correctly encoded. 'as' allows
473 // these through in many cases.
474
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000475 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000476 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000477 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000478 uint64_t &FixedValue) {
Daniel Dunbar482ad802010-05-26 15:18:31 +0000479 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
480 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
481 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000482
483 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000484 uint32_t FixupOffset =
485 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
486 uint32_t FixupAddress =
487 Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000488 int64_t Value = 0;
489 unsigned Index = 0;
490 unsigned IsExtern = 0;
491 unsigned Type = 0;
492
493 Value = Target.getConstant();
494
495 if (IsPCRel) {
496 // Compensate for the relocation offset, Darwin x86_64 relocations only
497 // have the addend and appear to have attempted to define it to be the
498 // actual expression addend without the PCrel bias. However, instructions
499 // with data following the relocation are not accomodated for (see comment
500 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
Benjamin Kramer454c4ce2010-04-08 15:25:57 +0000501 Value += 1LL << Log2Size;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000502 }
503
504 if (Target.isAbsolute()) { // constant
505 // SymbolNum of 0 indicates the absolute section.
506 Type = RIT_X86_64_Unsigned;
507 Index = 0;
508
509 // FIXME: I believe this is broken, I don't think the linker can
510 // understand it. I think it would require a local relocation, but I'm not
511 // sure if that would work either. The official way to get an absolute
512 // PCrel relocation is to use an absolute symbol (which we don't support
513 // yet).
514 if (IsPCRel) {
515 IsExtern = 1;
516 Type = RIT_X86_64_Branch;
517 }
518 } else if (Target.getSymB()) { // A - B + constant
519 const MCSymbol *A = &Target.getSymA()->getSymbol();
520 MCSymbolData &A_SD = Asm.getSymbolData(*A);
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000521 const MCSymbolData *A_Base = Asm.getAtom(Layout, &A_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000522
523 const MCSymbol *B = &Target.getSymB()->getSymbol();
524 MCSymbolData &B_SD = Asm.getSymbolData(*B);
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000525 const MCSymbolData *B_Base = Asm.getAtom(Layout, &B_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000526
527 // Neither symbol can be modified.
528 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
529 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000530 report_fatal_error("unsupported relocation of modified symbol");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000531
532 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
533 // implement most of these correctly.
534 if (IsPCRel)
Chris Lattner75361b62010-04-07 22:58:41 +0000535 report_fatal_error("unsupported pc-relative relocation of difference");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000536
537 // We don't currently support any situation where one or both of the
538 // symbols would require a local relocation. This is almost certainly
539 // unused and may not be possible to encode correctly.
540 if (!A_Base || !B_Base)
Chris Lattner75361b62010-04-07 22:58:41 +0000541 report_fatal_error("unsupported local relocations in difference");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000542
543 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
544 // a single SIGNED relocation); reject it for now.
545 if (A_Base == B_Base)
Chris Lattner75361b62010-04-07 22:58:41 +0000546 report_fatal_error("unsupported relocation with identical base");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000547
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000548 Value += Layout.getSymbolAddress(&A_SD) - Layout.getSymbolAddress(A_Base);
549 Value -= Layout.getSymbolAddress(&B_SD) - Layout.getSymbolAddress(B_Base);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000550
551 Index = A_Base->getIndex();
552 IsExtern = 1;
553 Type = RIT_X86_64_Unsigned;
554
555 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000556 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000557 MRE.Word1 = ((Index << 0) |
558 (IsPCRel << 24) |
559 (Log2Size << 25) |
560 (IsExtern << 27) |
561 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000562 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000563
564 Index = B_Base->getIndex();
565 IsExtern = 1;
566 Type = RIT_X86_64_Subtractor;
567 } else {
568 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
569 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000570 const MCSymbolData *Base = Asm.getAtom(Layout, &SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000571
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000572 // Relocations inside debug sections always use local relocations when
573 // possible. This seems to be done because the debugger doesn't fully
574 // understand x86_64 relocation entries, and expects to find values that
575 // have already been fixed up.
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000576 if (Symbol->isInSection()) {
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000577 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
578 Fragment->getParent()->getSection());
579 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
580 Base = 0;
581 }
582
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000583 // x86_64 almost always uses external relocations, except when there is no
584 // symbol to use as a base address (a local symbol with no preceeding
585 // non-local symbol).
586 if (Base) {
587 Index = Base->getIndex();
588 IsExtern = 1;
589
590 // Add the local offset, if needed.
591 if (Base != &SD)
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000592 Value += Layout.getSymbolAddress(&SD) - Layout.getSymbolAddress(Base);
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000593 } else if (Symbol->isInSection()) {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000594 // The index is the section ordinal (1-based).
595 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000596 IsExtern = 0;
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000597 Value += Layout.getSymbolAddress(&SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000598
599 if (IsPCRel)
Daniel Dunbardb4c7e62010-05-11 23:53:11 +0000600 Value -= FixupAddress + (1 << Log2Size);
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000601 } else {
602 report_fatal_error("unsupported relocation of undefined symbol '" +
603 Symbol->getName() + "'");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000604 }
605
606 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
607 if (IsPCRel) {
608 if (IsRIPRel) {
609 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
610 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
611 // rewrite the movq to an leaq at link time if the symbol ends up in
612 // the same linkage unit.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000613 if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000614 Type = RIT_X86_64_GOTLoad;
615 else
616 Type = RIT_X86_64_GOT;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000617 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
Eric Christopher96ac5152010-05-26 00:02:12 +0000618 Type = RIT_X86_64_TLV;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000619 } else if (Modifier != MCSymbolRefExpr::VK_None) {
620 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000621 } else {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000622 Type = RIT_X86_64_Signed;
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000623
624 // The Darwin x86_64 relocation format has a problem where it cannot
625 // encode an address (L<foo> + <constant>) which is outside the atom
626 // containing L<foo>. Generally, this shouldn't occur but it does
627 // happen when we have a RIPrel instruction with data following the
628 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
629 // adjustment Darwin x86_64 uses, the offset is still negative and
630 // the linker has no way to recognize this.
631 //
632 // To work around this, Darwin uses several special relocation types
633 // to indicate the offsets. However, the specification or
634 // implementation of these seems to also be incomplete; they should
635 // adjust the addend as well based on the actual encoded instruction
636 // (the additional bias), but instead appear to just look at the
637 // final offset.
638 switch (-(Target.getConstant() + (1LL << Log2Size))) {
639 case 1: Type = RIT_X86_64_Signed1; break;
640 case 2: Type = RIT_X86_64_Signed2; break;
641 case 4: Type = RIT_X86_64_Signed4; break;
642 }
643 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000644 } else {
645 if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000646 report_fatal_error("unsupported symbol modifier in branch "
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000647 "relocation");
648
649 Type = RIT_X86_64_Branch;
650 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000651 } else {
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000652 if (Modifier == MCSymbolRefExpr::VK_GOT) {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000653 Type = RIT_X86_64_GOT;
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000654 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
655 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
656 // which case all we do is set the PCrel bit in the relocation entry;
657 // this is used with exception handling, for example. The source is
658 // required to include any necessary offset directly.
659 Type = RIT_X86_64_GOT;
660 IsPCRel = 1;
Eric Christopher96ac5152010-05-26 00:02:12 +0000661 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
662 report_fatal_error("TLVP symbol modifier should have been rip-rel");
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000663 } else if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000664 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000665 else
666 Type = RIT_X86_64_Unsigned;
667 }
668 }
669
670 // x86_64 always writes custom values into the fixups.
671 FixedValue = Value;
672
673 // struct relocation_info (8 bytes)
674 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000675 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000676 MRE.Word1 = ((Index << 0) |
677 (IsPCRel << 24) |
678 (Log2Size << 25) |
679 (IsExtern << 27) |
680 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000681 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000682 }
683
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000684 void RecordScatteredRelocation(const MCAssembler &Asm,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000685 const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000686 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000687 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000688 uint64_t &FixedValue) {
Daniel Dunbar482ad802010-05-26 15:18:31 +0000689 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
690 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
691 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000692 unsigned Type = RIT_Vanilla;
693
694 // See <reloc.h>.
695 const MCSymbol *A = &Target.getSymA()->getSymbol();
696 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
697
698 if (!A_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000699 report_fatal_error("symbol '" + A->getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000700 "' can not be undefined in a subtraction expression");
701
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000702 uint32_t Value = Layout.getSymbolAddress(A_SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000703 uint32_t Value2 = 0;
704
705 if (const MCSymbolRefExpr *B = Target.getSymB()) {
706 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
707
708 if (!B_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000709 report_fatal_error("symbol '" + B->getSymbol().getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000710 "' can not be undefined in a subtraction expression");
711
712 // Select the appropriate difference relocation type.
713 //
714 // Note that there is no longer any semantic difference between these two
715 // relocation types from the linkers point of view, this is done solely
716 // for pedantic compatibility with 'as'.
717 Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000718 Value2 = Layout.getSymbolAddress(B_SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000719 }
720
721 // Relocations are written out in reverse order, so the PAIR comes first.
722 if (Type == RIT_Difference || Type == RIT_LocalDifference) {
723 MachRelocationEntry MRE;
724 MRE.Word0 = ((0 << 0) |
725 (RIT_Pair << 24) |
726 (Log2Size << 28) |
727 (IsPCRel << 30) |
728 RF_Scattered);
729 MRE.Word1 = Value2;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000730 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000731 }
732
733 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000734 MRE.Word0 = ((FixupOffset << 0) |
735 (Type << 24) |
736 (Log2Size << 28) |
737 (IsPCRel << 30) |
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000738 RF_Scattered);
739 MRE.Word1 = Value;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000740 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000741 }
742
Eric Christopherc9ada472010-06-15 22:59:05 +0000743 void RecordTLVPRelocation(const MCAssembler &Asm,
Eric Christophere48dbf82010-06-16 00:26:36 +0000744 const MCAsmLayout &Layout,
745 const MCFragment *Fragment,
746 const MCFixup &Fixup, MCValue Target,
747 uint64_t &FixedValue) {
Eric Christopherc9ada472010-06-15 22:59:05 +0000748 assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
749 !Is64Bit &&
750 "Should only be called with a 32-bit TLVP relocation!");
751
Eric Christopherc9ada472010-06-15 22:59:05 +0000752 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
753 uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
754 unsigned IsPCRel = 0;
755
756 // Get the symbol data.
757 MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
758 unsigned Index = SD_A->getIndex();
759
Eric Christopherbc067372010-06-16 21:32:38 +0000760 // We're only going to have a second symbol in pic mode and it'll be a
761 // subtraction from the picbase. For 32-bit pic the addend is the difference
Eric Christopher04b8d3c2010-06-17 00:49:46 +0000762 // between the picbase and the next address. For 32-bit static the addend
763 // is zero.
Eric Christopherbc067372010-06-16 21:32:38 +0000764 if (Target.getSymB()) {
Eric Christopher1008d352010-06-22 23:51:47 +0000765 // If this is a subtraction then we're pcrel.
766 uint32_t FixupAddress =
767 Layout.getFragmentAddress(Fragment) + Fixup.getOffset();
768 MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
Eric Christopherc9ada472010-06-15 22:59:05 +0000769 IsPCRel = 1;
Eric Christopher1008d352010-06-22 23:51:47 +0000770 FixedValue = (FixupAddress - Layout.getSymbolAddress(SD_B) +
771 Target.getConstant());
Chris Lattnerabf8f9c2010-08-16 16:35:20 +0000772 FixedValue += 1ULL << Log2Size;
Eric Christopherbc067372010-06-16 21:32:38 +0000773 } else {
774 FixedValue = 0;
775 }
Eric Christopherc9ada472010-06-15 22:59:05 +0000776
777 // struct relocation_info (8 bytes)
778 MachRelocationEntry MRE;
779 MRE.Word0 = Value;
780 MRE.Word1 = ((Index << 0) |
781 (IsPCRel << 24) |
782 (Log2Size << 25) |
783 (1 << 27) | // Extern
784 (RIT_TLV << 28)); // Type
785 Relocations[Fragment->getParent()].push_back(MRE);
786 }
787
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000788 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000789 const MCFragment *Fragment, const MCFixup &Fixup,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000790 MCValue Target, uint64_t &FixedValue) {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000791 if (Is64Bit) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000792 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000793 return;
794 }
795
Daniel Dunbar482ad802010-05-26 15:18:31 +0000796 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
797 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000798
Eric Christopherc9ada472010-06-15 22:59:05 +0000799 // If this is a 32-bit TLVP reloc it's handled a bit differently.
Daniel Dunbar23bea412010-09-17 15:21:50 +0000800 if (Target.getSymA() &&
801 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
Eric Christopherc9ada472010-06-15 22:59:05 +0000802 RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
803 return;
804 }
805
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000806 // If this is a difference or a defined symbol plus an offset, then we need
807 // a scattered relocation entry.
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000808 // Differences always require scattered relocations.
809 if (Target.getSymB())
810 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
811 Target, FixedValue);
812
813 // Get the symbol data, if any.
814 MCSymbolData *SD = 0;
815 if (Target.getSymA())
816 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
817
818 // If this is an internal relocation with an offset, it also needs a
819 // scattered relocation entry.
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000820 uint32_t Offset = Target.getConstant();
821 if (IsPCRel)
822 Offset += 1 << Log2Size;
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000823 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
824 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
825 Target, FixedValue);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000826
827 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000828 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000829 unsigned Index = 0;
830 unsigned IsExtern = 0;
831 unsigned Type = 0;
832
833 if (Target.isAbsolute()) { // constant
834 // SymbolNum of 0 indicates the absolute section.
835 //
836 // FIXME: Currently, these are never generated (see code below). I cannot
837 // find a case where they are actually emitted.
838 Type = RIT_Vanilla;
Michael J. Spencerb0f3b3e2010-08-10 16:00:49 +0000839 } else {
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000840 // Check whether we need an external or internal relocation.
841 if (doesSymbolRequireExternRelocation(SD)) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000842 IsExtern = 1;
843 Index = SD->getIndex();
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000844 // For external relocations, make sure to offset the fixup value to
845 // compensate for the addend of the symbol address, if it was
846 // undefined. This occurs with weak definitions, for example.
847 if (!SD->Symbol->isUndefined())
Kevin Enderbya6eeb6e2010-05-07 21:44:23 +0000848 FixedValue -= Layout.getSymbolAddress(SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000849 } 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 Dunbar2df4ceb2010-03-19 10:43:15 +0000852 }
853
854 Type = RIT_Vanilla;
855 }
856
857 // struct relocation_info (8 bytes)
858 MachRelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000859 MRE.Word0 = FixupOffset;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000860 MRE.Word1 = ((Index << 0) |
861 (IsPCRel << 24) |
862 (Log2Size << 25) |
863 (IsExtern << 27) |
864 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000865 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000866 }
867
868 void BindIndirectSymbols(MCAssembler &Asm) {
869 // This is the point where 'as' creates actual symbols for indirect symbols
870 // (in the following two passes). It would be easier for us to do this
871 // sooner when we see the attribute, but that makes getting the order in the
872 // symbol table much more complicated than it is worth.
873 //
874 // FIXME: Revisit this when the dust settles.
875
876 // Bind non lazy symbol pointers first.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000877 unsigned IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000878 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000879 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000880 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +0000881 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000882
883 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
884 continue;
885
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000886 // Initialize the section indirect symbol base, if necessary.
887 if (!IndirectSymBase.count(it->SectionData))
888 IndirectSymBase[it->SectionData] = IndirectIndex;
889
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000890 Asm.getOrCreateSymbolData(*it->Symbol);
891 }
892
893 // Then lazy symbol pointers and symbol stubs.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000894 IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000895 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000896 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000897 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +0000898 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000899
900 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
901 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
902 continue;
903
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000904 // Initialize the section indirect symbol base, if necessary.
905 if (!IndirectSymBase.count(it->SectionData))
906 IndirectSymBase[it->SectionData] = IndirectIndex;
907
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000908 // Set the symbol type to undefined lazy, but only on construction.
909 //
910 // FIXME: Do not hardcode.
911 bool Created;
912 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
913 if (Created)
914 Entry.setFlags(Entry.getFlags() | 0x0001);
915 }
916 }
917
918 /// ComputeSymbolTable - Compute the symbol table data
919 ///
920 /// \param StringTable [out] - The string table data.
921 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
922 /// string table.
923 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
924 std::vector<MachSymbolData> &LocalSymbolData,
925 std::vector<MachSymbolData> &ExternalSymbolData,
926 std::vector<MachSymbolData> &UndefinedSymbolData) {
927 // Build section lookup table.
928 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
929 unsigned Index = 1;
930 for (MCAssembler::iterator it = Asm.begin(),
931 ie = Asm.end(); it != ie; ++it, ++Index)
932 SectionIndexMap[&it->getSection()] = Index;
933 assert(Index <= 256 && "Too many sections!");
934
935 // Index 0 is always the empty string.
936 StringMap<uint64_t> StringIndexMap;
937 StringTable += '\x00';
938
939 // Build the symbol arrays and the string table, but only for non-local
940 // symbols.
941 //
942 // The particular order that we collect the symbols and create the string
943 // table, then sort the symbols is chosen to match 'as'. Even though it
944 // doesn't matter for correctness, this is important for letting us diff .o
945 // files.
946 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
947 ie = Asm.symbol_end(); it != ie; ++it) {
948 const MCSymbol &Symbol = it->getSymbol();
949
950 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +0000951 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000952 continue;
953
954 if (!it->isExternal() && !Symbol.isUndefined())
955 continue;
956
957 uint64_t &Entry = StringIndexMap[Symbol.getName()];
958 if (!Entry) {
959 Entry = StringTable.size();
960 StringTable += Symbol.getName();
961 StringTable += '\x00';
962 }
963
964 MachSymbolData MSD;
965 MSD.SymbolData = it;
966 MSD.StringIndex = Entry;
967
968 if (Symbol.isUndefined()) {
969 MSD.SectionIndex = 0;
970 UndefinedSymbolData.push_back(MSD);
971 } else if (Symbol.isAbsolute()) {
972 MSD.SectionIndex = 0;
973 ExternalSymbolData.push_back(MSD);
974 } else {
975 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
976 assert(MSD.SectionIndex && "Invalid section index!");
977 ExternalSymbolData.push_back(MSD);
978 }
979 }
980
981 // Now add the data for local symbols.
982 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
983 ie = Asm.symbol_end(); it != ie; ++it) {
984 const MCSymbol &Symbol = it->getSymbol();
985
986 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +0000987 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000988 continue;
989
990 if (it->isExternal() || Symbol.isUndefined())
991 continue;
992
993 uint64_t &Entry = StringIndexMap[Symbol.getName()];
994 if (!Entry) {
995 Entry = StringTable.size();
996 StringTable += Symbol.getName();
997 StringTable += '\x00';
998 }
999
1000 MachSymbolData MSD;
1001 MSD.SymbolData = it;
1002 MSD.StringIndex = Entry;
1003
1004 if (Symbol.isAbsolute()) {
1005 MSD.SectionIndex = 0;
1006 LocalSymbolData.push_back(MSD);
1007 } else {
1008 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1009 assert(MSD.SectionIndex && "Invalid section index!");
1010 LocalSymbolData.push_back(MSD);
1011 }
1012 }
1013
1014 // External and undefined symbols are required to be in lexicographic order.
1015 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1016 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1017
1018 // Set the symbol indices.
1019 Index = 0;
1020 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1021 LocalSymbolData[i].SymbolData->setIndex(Index++);
1022 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1023 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1024 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1025 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1026
1027 // The string table is padded to a multiple of 4.
1028 while (StringTable.size() % 4)
1029 StringTable += '\x00';
1030 }
1031
Daniel Dunbar873decb2010-03-20 01:58:40 +00001032 void ExecutePostLayoutBinding(MCAssembler &Asm) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001033 // Create symbol data for any indirect symbols.
1034 BindIndirectSymbols(Asm);
1035
1036 // Compute symbol table information and bind symbol indices.
1037 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1038 UndefinedSymbolData);
1039 }
1040
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001041 void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001042 unsigned NumSections = Asm.size();
1043
1044 // The section data starts after the header, the segment load command (and
1045 // section headers) and the symbol table.
1046 unsigned NumLoadCommands = 1;
1047 uint64_t LoadCommandsSize = Is64Bit ?
1048 SegmentLoadCommand64Size + NumSections * Section64Size :
1049 SegmentLoadCommand32Size + NumSections * Section32Size;
1050
1051 // Add the symbol table load command sizes, if used.
1052 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1053 UndefinedSymbolData.size();
1054 if (NumSymbols) {
1055 NumLoadCommands += 2;
1056 LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
1057 }
1058
1059 // Compute the total size of the section data, as well as its file size and
1060 // vm size.
1061 uint64_t SectionDataStart = (Is64Bit ? Header64Size : Header32Size)
1062 + LoadCommandsSize;
1063 uint64_t SectionDataSize = 0;
1064 uint64_t SectionDataFileSize = 0;
1065 uint64_t VMSize = 0;
1066 for (MCAssembler::const_iterator it = Asm.begin(),
1067 ie = Asm.end(); it != ie; ++it) {
1068 const MCSectionData &SD = *it;
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001069 uint64_t Address = Layout.getSectionAddress(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +00001070 uint64_t Size = Layout.getSectionSize(&SD);
1071 uint64_t FileSize = Layout.getSectionFileSize(&SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001072
Daniel Dunbar5d428512010-03-25 02:00:07 +00001073 VMSize = std::max(VMSize, Address + Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001074
1075 if (Asm.getBackend().isVirtualSection(SD.getSection()))
1076 continue;
1077
Daniel Dunbar5d428512010-03-25 02:00:07 +00001078 SectionDataSize = std::max(SectionDataSize, Address + Size);
1079 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001080 }
1081
1082 // The section data is padded to 4 bytes.
1083 //
1084 // FIXME: Is this machine dependent?
1085 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1086 SectionDataFileSize += SectionDataPadding;
1087
1088 // Write the prolog, starting with the header and load command...
1089 WriteHeader(NumLoadCommands, LoadCommandsSize,
1090 Asm.getSubsectionsViaSymbols());
1091 WriteSegmentLoadCommand(NumSections, VMSize,
1092 SectionDataStart, SectionDataSize);
1093
1094 // ... and then the section headers.
1095 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1096 for (MCAssembler::const_iterator it = Asm.begin(),
1097 ie = Asm.end(); it != ie; ++it) {
1098 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1099 unsigned NumRelocs = Relocs.size();
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001100 uint64_t SectionStart = SectionDataStart + Layout.getSectionAddress(it);
1101 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001102 RelocTableEnd += NumRelocs * RelocationInfoSize;
1103 }
1104
1105 // Write the symbol table load command, if used.
1106 if (NumSymbols) {
1107 unsigned FirstLocalSymbol = 0;
1108 unsigned NumLocalSymbols = LocalSymbolData.size();
1109 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1110 unsigned NumExternalSymbols = ExternalSymbolData.size();
1111 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1112 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1113 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1114 unsigned NumSymTabSymbols =
1115 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1116 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1117 uint64_t IndirectSymbolOffset = 0;
1118
1119 // If used, the indirect symbols are written after the section data.
1120 if (NumIndirectSymbols)
1121 IndirectSymbolOffset = RelocTableEnd;
1122
1123 // The symbol table is written after the indirect symbol data.
1124 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1125
1126 // The string table is written after symbol table.
1127 uint64_t StringTableOffset =
1128 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? Nlist64Size :
1129 Nlist32Size);
1130 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1131 StringTableOffset, StringTable.size());
1132
1133 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1134 FirstExternalSymbol, NumExternalSymbols,
1135 FirstUndefinedSymbol, NumUndefinedSymbols,
1136 IndirectSymbolOffset, NumIndirectSymbols);
1137 }
1138
1139 // Write the actual section data.
1140 for (MCAssembler::const_iterator it = Asm.begin(),
1141 ie = Asm.end(); it != ie; ++it)
Daniel Dunbar432cd5f2010-03-25 02:00:02 +00001142 Asm.WriteSectionData(it, Layout, Writer);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001143
1144 // Write the extra padding.
1145 WriteZeros(SectionDataPadding);
1146
1147 // Write the relocation entries.
1148 for (MCAssembler::const_iterator it = Asm.begin(),
1149 ie = Asm.end(); it != ie; ++it) {
1150 // Write the section relocation entries, in reverse order to match 'as'
1151 // (approximately, the exact algorithm is more complicated than this).
1152 std::vector<MachRelocationEntry> &Relocs = Relocations[it];
1153 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1154 Write32(Relocs[e - i - 1].Word0);
1155 Write32(Relocs[e - i - 1].Word1);
1156 }
1157 }
1158
1159 // Write the symbol table data, if used.
1160 if (NumSymbols) {
1161 // Write the indirect symbol entries.
1162 for (MCAssembler::const_indirect_symbol_iterator
1163 it = Asm.indirect_symbol_begin(),
1164 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1165 // Indirect symbols in the non lazy symbol pointer section have some
1166 // special handling.
1167 const MCSectionMachO &Section =
1168 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1169 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1170 // If this symbol is defined and internal, mark it as such.
1171 if (it->Symbol->isDefined() &&
1172 !Asm.getSymbolData(*it->Symbol).isExternal()) {
1173 uint32_t Flags = ISF_Local;
1174 if (it->Symbol->isAbsolute())
1175 Flags |= ISF_Absolute;
1176 Write32(Flags);
1177 continue;
1178 }
1179 }
1180
1181 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1182 }
1183
1184 // FIXME: Check that offsets match computed ones.
1185
1186 // Write the symbol table entries.
1187 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001188 WriteNlist(LocalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001189 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001190 WriteNlist(ExternalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001191 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001192 WriteNlist(UndefinedSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001193
1194 // Write the string table.
1195 OS << StringTable.str();
1196 }
1197 }
1198};
1199
1200}
1201
1202MachObjectWriter::MachObjectWriter(raw_ostream &OS,
1203 bool Is64Bit,
1204 bool IsLittleEndian)
1205 : MCObjectWriter(OS, IsLittleEndian)
1206{
1207 Impl = new MachObjectWriterImpl(this, Is64Bit);
1208}
1209
1210MachObjectWriter::~MachObjectWriter() {
1211 delete (MachObjectWriterImpl*) Impl;
1212}
1213
1214void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1215 ((MachObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1216}
1217
1218void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001219 const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +00001220 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +00001221 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001222 uint64_t &FixedValue) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001223 ((MachObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001224 Target, FixedValue);
1225}
1226
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001227void MachObjectWriter::WriteObject(const MCAssembler &Asm,
1228 const MCAsmLayout &Layout) {
1229 ((MachObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001230}