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