blob: fa3b4dce688ebefc3798c3fb1bdb9abf2c37bf6c [file] [log] [blame]
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001//===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000010#include "llvm/ADT/StringMap.h"
11#include "llvm/ADT/Twine.h"
12#include "llvm/MC/MCAssembler.h"
Daniel Dunbar207e06e2010-03-24 03:43:40 +000013#include "llvm/MC/MCAsmLayout.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000014#include "llvm/MC/MCExpr.h"
15#include "llvm/MC/MCObjectWriter.h"
16#include "llvm/MC/MCSectionMachO.h"
17#include "llvm/MC/MCSymbol.h"
Kevin Enderbya6eeb6e2010-05-07 21:44:23 +000018#include "llvm/MC/MCMachOSymbolFlags.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000019#include "llvm/MC/MCValue.h"
Daniel Dunbar821ecd72010-11-27 04:19:38 +000020#include "llvm/Object/MachOFormat.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000021#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000022#include "llvm/Target/TargetAsmBackend.h"
23
24// FIXME: Gross.
25#include "../Target/X86/X86FixupKinds.h"
26
27#include <vector>
28using namespace llvm;
Daniel Dunbar821ecd72010-11-27 04:19:38 +000029using namespace llvm::object;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000030
Rafael Espindolaa8c02c32010-09-30 03:11:42 +000031// FIXME: this has been copied from (or to) X86AsmBackend.cpp
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000032static unsigned getFixupKindLog2Size(unsigned Kind) {
33 switch (Kind) {
Jim Grosbachdff84b02010-12-02 00:28:45 +000034 // FIXME: Until ARM has it's own relocation stuff spun off, it comes
35 // through here and we don't want it to puke all over. Any reasonable
36 // values will only come when ARM relocation support gets added, at which
37 // point this will be X86 only again and the llvm_unreachable can be
38 // re-enabled.
39 default: return 0;// llvm_unreachable("invalid fixup kind!");
Rafael Espindolae04ed7e2010-11-28 14:17:56 +000040 case FK_PCRel_1:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000041 case FK_Data_1: return 0;
Rafael Espindolae04ed7e2010-11-28 14:17:56 +000042 case FK_PCRel_2:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000043 case FK_Data_2: return 1;
Rafael Espindolae04ed7e2010-11-28 14:17:56 +000044 case FK_PCRel_4:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000045 case X86::reloc_riprel_4byte:
Daniel Dunbar602b40f2010-03-19 18:07:55 +000046 case X86::reloc_riprel_4byte_movq_load:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +000047 case X86::reloc_signed_4byte:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000048 case FK_Data_4: return 2;
49 case FK_Data_8: return 3;
50 }
51}
52
53static bool isFixupKindPCRel(unsigned Kind) {
54 switch (Kind) {
55 default:
56 return false;
Rafael Espindolae04ed7e2010-11-28 14:17:56 +000057 case FK_PCRel_1:
58 case FK_PCRel_2:
59 case FK_PCRel_4:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000060 case X86::reloc_riprel_4byte:
Daniel Dunbar602b40f2010-03-19 18:07:55 +000061 case X86::reloc_riprel_4byte_movq_load:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000062 return true;
63 }
64}
65
Daniel Dunbar602b40f2010-03-19 18:07:55 +000066static bool isFixupKindRIPRel(unsigned Kind) {
67 return Kind == X86::reloc_riprel_4byte ||
68 Kind == X86::reloc_riprel_4byte_movq_load;
69}
70
Daniel Dunbare9460ec2010-05-10 23:15:13 +000071static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
72 // Undefined symbols are always extern.
73 if (SD->Symbol->isUndefined())
74 return true;
75
76 // References to weak definitions require external relocation entries; the
77 // definition may not always be the one in the same object file.
78 if (SD->getFlags() & SF_WeakDefinition)
79 return true;
80
81 // Otherwise, we can use an internal relocation.
82 return false;
83}
84
Rafael Espindola70703872010-09-30 02:22:20 +000085static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
86 const MCValue Target,
87 const MCSymbolData *BaseSymbol) {
88 // The effective fixup address is
89 // addr(atom(A)) + offset(A)
90 // - addr(atom(B)) - offset(B)
91 // - addr(BaseSymbol) + <fixup offset from base symbol>
92 // and the offsets are not relocatable, so the fixup is fully resolved when
93 // addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
94 //
95 // Note that "false" is almost always conservatively correct (it means we emit
96 // a relocation which is unnecessary), except when it would force us to emit a
97 // relocation which the target cannot encode.
98
99 const MCSymbolData *A_Base = 0, *B_Base = 0;
100 if (const MCSymbolRefExpr *A = Target.getSymA()) {
101 // Modified symbol references cannot be resolved.
102 if (A->getKind() != MCSymbolRefExpr::VK_None)
103 return false;
104
105 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
106 if (!A_Base)
107 return false;
108 }
109
110 if (const MCSymbolRefExpr *B = Target.getSymB()) {
111 // Modified symbol references cannot be resolved.
112 if (B->getKind() != MCSymbolRefExpr::VK_None)
113 return false;
114
115 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
116 if (!B_Base)
117 return false;
118 }
119
120 // If there is no base, A and B have to be the same atom for this fixup to be
121 // fully resolved.
122 if (!BaseSymbol)
123 return A_Base == B_Base;
124
125 // Otherwise, B must be missing and A must be the base.
126 return !B_Base && BaseSymbol == A_Base;
127}
128
129static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
130 const MCValue Target,
131 const MCSection *BaseSection) {
132 // The effective fixup address is
133 // addr(atom(A)) + offset(A)
134 // - addr(atom(B)) - offset(B)
135 // - addr(<base symbol>) + <fixup offset from base symbol>
136 // and the offsets are not relocatable, so the fixup is fully resolved when
137 // addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
138 //
139 // The simple (Darwin, except on x86_64) way of dealing with this was to
140 // assume that any reference to a temporary symbol *must* be a temporary
141 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
142 // relocation to a temporary symbol (in the same section) is fully
143 // resolved. This also works in conjunction with absolutized .set, which
144 // requires the compiler to use .set to absolutize the differences between
145 // symbols which the compiler knows to be assembly time constants, so we don't
146 // need to worry about considering symbol differences fully resolved.
147
148 // Non-relative fixups are only resolved if constant.
149 if (!BaseSection)
150 return Target.isAbsolute();
151
152 // Otherwise, relative fixups are only resolved if not a difference and the
153 // target is a temporary in the same section.
154 if (Target.isAbsolute() || Target.getSymB())
155 return false;
156
157 const MCSymbol *A = &Target.getSymA()->getSymbol();
158 if (!A->isTemporary() || !A->isInSection() ||
159 &A->getSection() != BaseSection)
160 return false;
161
162 return true;
163}
164
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000165namespace {
166
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000167class MachObjectWriter : public MCObjectWriter {
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
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000185 llvm::DenseMap<const MCSectionData*,
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000186 std::vector<macho::RelocationEntry> > Relocations;
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000187 llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000188
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
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000200 SectionAddrMap SectionAddress;
201 uint64_t getSectionAddress(const MCSectionData* SD) const {
202 return SectionAddress.lookup(SD);
203 }
204 uint64_t getSymbolAddress(const MCSymbolData* SD,
205 const MCAsmLayout &Layout) const {
206 return getSectionAddress(SD->getFragment()->getParent()) +
207 Layout.getSymbolOffset(SD);
208 }
209 uint64_t getFragmentAddress(const MCFragment *Fragment,
210 const MCAsmLayout &Layout) const {
211 return getSectionAddress(Fragment->getParent()) +
212 Layout.getFragmentOffset(Fragment);
213 }
214
215 uint64_t getPaddingSize(const MCSectionData *SD,
216 const MCAsmLayout &Layout) const {
217 uint64_t EndAddr = getSectionAddress(SD) + Layout.getSectionAddressSize(SD);
218 unsigned Next = SD->getLayoutOrder() + 1;
219 if (Next >= Layout.getSectionOrder().size())
220 return 0;
221
222 const MCSectionData &NextSD = *Layout.getSectionOrder()[Next];
223 if (NextSD.getSection().isVirtualSection())
224 return 0;
225 return OffsetToAlignment(EndAddr, NextSD.getAlignment());
226 }
227
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000228 unsigned Is64Bit : 1;
229
Jim Grosbachc9d14392010-11-05 18:48:58 +0000230 uint32_t CPUType;
231 uint32_t CPUSubtype;
232
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000233public:
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000234 MachObjectWriter(raw_ostream &_OS,
235 bool _Is64Bit, uint32_t _CPUType, uint32_t _CPUSubtype,
236 bool _IsLittleEndian)
237 : MCObjectWriter(_OS, _IsLittleEndian),
238 Is64Bit(_Is64Bit), CPUType(_CPUType), CPUSubtype(_CPUSubtype) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000239 }
240
241 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
242 bool SubsectionsViaSymbols) {
243 uint32_t Flags = 0;
244
245 if (SubsectionsViaSymbols)
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000246 Flags |= macho::HF_SubsectionsViaSymbols;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000247
248 // struct mach_header (28 bytes) or
249 // struct mach_header_64 (32 bytes)
250
251 uint64_t Start = OS.tell();
252 (void) Start;
253
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000254 Write32(Is64Bit ? macho::HM_Object64 : macho::HM_Object32);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000255
Jim Grosbachc9d14392010-11-05 18:48:58 +0000256 Write32(CPUType);
257 Write32(CPUSubtype);
258
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000259 Write32(macho::HFT_Object);
Daniel Dunbar590956f2010-11-27 07:39:37 +0000260 Write32(NumLoadCommands);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000261 Write32(LoadCommandsSize);
262 Write32(Flags);
263 if (Is64Bit)
264 Write32(0); // reserved
265
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000266 assert(OS.tell() - Start == Is64Bit ?
267 macho::Header64Size : macho::Header32Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000268 }
269
270 /// WriteSegmentLoadCommand - Write a segment load command.
271 ///
272 /// \arg NumSections - The number of sections in this segment.
273 /// \arg SectionDataSize - The total size of the sections.
274 void WriteSegmentLoadCommand(unsigned NumSections,
275 uint64_t VMSize,
276 uint64_t SectionDataStartOffset,
277 uint64_t SectionDataSize) {
278 // struct segment_command (56 bytes) or
279 // struct segment_command_64 (72 bytes)
280
281 uint64_t Start = OS.tell();
282 (void) Start;
283
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000284 unsigned SegmentLoadCommandSize = Is64Bit ? macho::SegmentLoadCommand64Size:
285 macho::SegmentLoadCommand32Size;
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000286 Write32(Is64Bit ? macho::LCT_Segment64 : macho::LCT_Segment);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000287 Write32(SegmentLoadCommandSize +
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000288 NumSections * (Is64Bit ? macho::Section64Size :
289 macho::Section32Size));
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000290
291 WriteBytes("", 16);
292 if (Is64Bit) {
293 Write64(0); // vmaddr
294 Write64(VMSize); // vmsize
295 Write64(SectionDataStartOffset); // file offset
296 Write64(SectionDataSize); // file size
297 } else {
298 Write32(0); // vmaddr
299 Write32(VMSize); // vmsize
300 Write32(SectionDataStartOffset); // file offset
301 Write32(SectionDataSize); // file size
302 }
303 Write32(0x7); // maxprot
304 Write32(0x7); // initprot
305 Write32(NumSections);
306 Write32(0); // flags
307
308 assert(OS.tell() - Start == SegmentLoadCommandSize);
309 }
310
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000311 void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
312 const MCSectionData &SD, uint64_t FileOffset,
313 uint64_t RelocationsStart, unsigned NumRelocations) {
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000314 uint64_t SectionSize = Layout.getSectionAddressSize(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +0000315
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000316 // The offset is unused for virtual sections.
Rafael Espindolaf2dc4aa2010-11-17 20:03:54 +0000317 if (SD.getSection().isVirtualSection()) {
Daniel Dunbarb026d642010-03-25 07:10:05 +0000318 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000319 FileOffset = 0;
320 }
321
322 // struct section (68 bytes) or
323 // struct section_64 (80 bytes)
324
325 uint64_t Start = OS.tell();
326 (void) Start;
327
Daniel Dunbar56279f42010-05-18 17:28:20 +0000328 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000329 WriteBytes(Section.getSectionName(), 16);
330 WriteBytes(Section.getSegmentName(), 16);
331 if (Is64Bit) {
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000332 Write64(getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000333 Write64(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000334 } else {
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000335 Write32(getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000336 Write32(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000337 }
338 Write32(FileOffset);
339
340 unsigned Flags = Section.getTypeAndAttributes();
341 if (SD.hasInstructions())
342 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
343
344 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
345 Write32(Log2_32(SD.getAlignment()));
346 Write32(NumRelocations ? RelocationsStart : 0);
347 Write32(NumRelocations);
348 Write32(Flags);
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000349 Write32(IndirectSymBase.lookup(&SD)); // reserved1
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000350 Write32(Section.getStubSize()); // reserved2
351 if (Is64Bit)
352 Write32(0); // reserved3
353
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000354 assert(OS.tell() - Start == Is64Bit ? macho::Section64Size :
355 macho::Section32Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000356 }
357
358 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
359 uint32_t StringTableOffset,
360 uint32_t StringTableSize) {
361 // struct symtab_command (24 bytes)
362
363 uint64_t Start = OS.tell();
364 (void) Start;
365
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000366 Write32(macho::LCT_Symtab);
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000367 Write32(macho::SymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000368 Write32(SymbolOffset);
369 Write32(NumSymbols);
370 Write32(StringTableOffset);
371 Write32(StringTableSize);
372
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000373 assert(OS.tell() - Start == macho::SymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000374 }
375
376 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
377 uint32_t NumLocalSymbols,
378 uint32_t FirstExternalSymbol,
379 uint32_t NumExternalSymbols,
380 uint32_t FirstUndefinedSymbol,
381 uint32_t NumUndefinedSymbols,
382 uint32_t IndirectSymbolOffset,
383 uint32_t NumIndirectSymbols) {
384 // struct dysymtab_command (80 bytes)
385
386 uint64_t Start = OS.tell();
387 (void) Start;
388
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000389 Write32(macho::LCT_Dysymtab);
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000390 Write32(macho::DysymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000391 Write32(FirstLocalSymbol);
392 Write32(NumLocalSymbols);
393 Write32(FirstExternalSymbol);
394 Write32(NumExternalSymbols);
395 Write32(FirstUndefinedSymbol);
396 Write32(NumUndefinedSymbols);
397 Write32(0); // tocoff
398 Write32(0); // ntoc
399 Write32(0); // modtaboff
400 Write32(0); // nmodtab
401 Write32(0); // extrefsymoff
402 Write32(0); // nextrefsyms
403 Write32(IndirectSymbolOffset);
404 Write32(NumIndirectSymbols);
405 Write32(0); // extreloff
406 Write32(0); // nextrel
407 Write32(0); // locreloff
408 Write32(0); // nlocrel
409
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000410 assert(OS.tell() - Start == macho::DysymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000411 }
412
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000413 void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000414 MCSymbolData &Data = *MSD.SymbolData;
415 const MCSymbol &Symbol = Data.getSymbol();
416 uint8_t Type = 0;
417 uint16_t Flags = Data.getFlags();
418 uint32_t Address = 0;
419
420 // Set the N_TYPE bits. See <mach-o/nlist.h>.
421 //
422 // FIXME: Are the prebound or indirect fields possible here?
423 if (Symbol.isUndefined())
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000424 Type = macho::STT_Undefined;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000425 else if (Symbol.isAbsolute())
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000426 Type = macho::STT_Absolute;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000427 else
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000428 Type = macho::STT_Section;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000429
430 // FIXME: Set STAB bits.
431
432 if (Data.isPrivateExtern())
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000433 Type |= macho::STF_PrivateExtern;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000434
435 // Set external bit.
436 if (Data.isExternal() || Symbol.isUndefined())
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000437 Type |= macho::STF_External;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000438
439 // Compute the symbol address.
440 if (Symbol.isDefined()) {
441 if (Symbol.isAbsolute()) {
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000442 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000443 } else {
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000444 Address = getSymbolAddress(&Data, Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000445 }
446 } else if (Data.isCommon()) {
447 // Common symbols are encoded with the size in the address
448 // field, and their alignment in the flags.
449 Address = Data.getCommonSize();
450
451 // Common alignment is packed into the 'desc' bits.
452 if (unsigned Align = Data.getCommonAlignment()) {
453 unsigned Log2Size = Log2_32(Align);
454 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
455 if (Log2Size > 15)
Chris Lattner75361b62010-04-07 22:58:41 +0000456 report_fatal_error("invalid 'common' alignment '" +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000457 Twine(Align) + "'");
458 // FIXME: Keep this mask with the SymbolFlags enumeration.
459 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
460 }
461 }
462
463 // struct nlist (12 bytes)
464
465 Write32(MSD.StringIndex);
466 Write8(Type);
467 Write8(MSD.SectionIndex);
468
469 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
470 // value.
471 Write16(Flags);
472 if (Is64Bit)
473 Write64(Address);
474 else
475 Write32(Address);
476 }
477
Daniel Dunbar35b06572010-03-22 23:16:43 +0000478 // FIXME: We really need to improve the relocation validation. Basically, we
479 // want to implement a separate computation which evaluates the relocation
480 // entry as the linker would, and verifies that the resultant fixup value is
481 // exactly what the encoder wanted. This will catch several classes of
482 // problems:
483 //
484 // - Relocation entry bugs, the two algorithms are unlikely to have the same
485 // exact bug.
486 //
487 // - Relaxation issues, where we forget to relax something.
488 //
489 // - Input errors, where something cannot be correctly encoded. 'as' allows
490 // these through in many cases.
491
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000492 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000493 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000494 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000495 uint64_t &FixedValue) {
Daniel Dunbar482ad802010-05-26 15:18:31 +0000496 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
497 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
498 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000499
500 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000501 uint32_t FixupOffset =
502 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
503 uint32_t FixupAddress =
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000504 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000505 int64_t Value = 0;
506 unsigned Index = 0;
507 unsigned IsExtern = 0;
508 unsigned Type = 0;
509
510 Value = Target.getConstant();
511
512 if (IsPCRel) {
513 // Compensate for the relocation offset, Darwin x86_64 relocations only
514 // have the addend and appear to have attempted to define it to be the
515 // actual expression addend without the PCrel bias. However, instructions
516 // with data following the relocation are not accomodated for (see comment
517 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
Benjamin Kramer454c4ce2010-04-08 15:25:57 +0000518 Value += 1LL << Log2Size;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000519 }
520
521 if (Target.isAbsolute()) { // constant
522 // SymbolNum of 0 indicates the absolute section.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000523 Type = macho::RIT_X86_64_Unsigned;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000524 Index = 0;
525
526 // FIXME: I believe this is broken, I don't think the linker can
527 // understand it. I think it would require a local relocation, but I'm not
528 // sure if that would work either. The official way to get an absolute
529 // PCrel relocation is to use an absolute symbol (which we don't support
530 // yet).
531 if (IsPCRel) {
532 IsExtern = 1;
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000533 Type = macho::RIT_X86_64_Branch;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000534 }
535 } else if (Target.getSymB()) { // A - B + constant
536 const MCSymbol *A = &Target.getSymA()->getSymbol();
537 MCSymbolData &A_SD = Asm.getSymbolData(*A);
Rafael Espindolab8141102010-09-27 18:13:03 +0000538 const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000539
540 const MCSymbol *B = &Target.getSymB()->getSymbol();
541 MCSymbolData &B_SD = Asm.getSymbolData(*B);
Rafael Espindolab8141102010-09-27 18:13:03 +0000542 const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000543
544 // Neither symbol can be modified.
545 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
546 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000547 report_fatal_error("unsupported relocation of modified symbol");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000548
549 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
550 // implement most of these correctly.
551 if (IsPCRel)
Chris Lattner75361b62010-04-07 22:58:41 +0000552 report_fatal_error("unsupported pc-relative relocation of difference");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000553
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000554 // The support for the situation where one or both of the symbols would
555 // require a local relocation is handled just like if the symbols were
556 // external. This is certainly used in the case of debug sections where
557 // the section has only temporary symbols and thus the symbols don't have
558 // base symbols. This is encoded using the section ordinal and
559 // non-extern relocation entries.
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000560
561 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000562 // a single SIGNED relocation); reject it for now. Except the case where
563 // both symbols don't have a base, equal but both NULL.
564 if (A_Base == B_Base && A_Base)
Chris Lattner75361b62010-04-07 22:58:41 +0000565 report_fatal_error("unsupported relocation with identical base");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000566
Rafael Espindolaf10d2be2010-12-07 01:09:54 +0000567 Value += getSymbolAddress(&A_SD, Layout) -
568 (A_Base == NULL ? 0 : getSymbolAddress(A_Base, Layout));
569 Value -= getSymbolAddress(&B_SD, Layout) -
570 (B_Base == NULL ? 0 : getSymbolAddress(B_Base, Layout));
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000571
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000572 if (A_Base) {
573 Index = A_Base->getIndex();
574 IsExtern = 1;
575 }
576 else {
577 Index = A_SD.getFragment()->getParent()->getOrdinal() + 1;
578 IsExtern = 0;
579 }
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000580 Type = macho::RIT_X86_64_Unsigned;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000581
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000582 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000583 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000584 MRE.Word1 = ((Index << 0) |
585 (IsPCRel << 24) |
586 (Log2Size << 25) |
587 (IsExtern << 27) |
588 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000589 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000590
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000591 if (B_Base) {
592 Index = B_Base->getIndex();
593 IsExtern = 1;
594 }
595 else {
596 Index = B_SD.getFragment()->getParent()->getOrdinal() + 1;
597 IsExtern = 0;
598 }
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000599 Type = macho::RIT_X86_64_Subtractor;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000600 } else {
601 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
602 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
Rafael Espindolab8141102010-09-27 18:13:03 +0000603 const MCSymbolData *Base = Asm.getAtom(&SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000604
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000605 // Relocations inside debug sections always use local relocations when
606 // possible. This seems to be done because the debugger doesn't fully
607 // understand x86_64 relocation entries, and expects to find values that
608 // have already been fixed up.
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000609 if (Symbol->isInSection()) {
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000610 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
611 Fragment->getParent()->getSection());
612 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
613 Base = 0;
614 }
615
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000616 // x86_64 almost always uses external relocations, except when there is no
617 // symbol to use as a base address (a local symbol with no preceeding
618 // non-local symbol).
619 if (Base) {
620 Index = Base->getIndex();
621 IsExtern = 1;
622
623 // Add the local offset, if needed.
624 if (Base != &SD)
Rafael Espindola1dda29b2010-12-06 21:51:55 +0000625 Value += Layout.getSymbolOffset(&SD) - Layout.getSymbolOffset(Base);
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000626 } else if (Symbol->isInSection()) {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000627 // The index is the section ordinal (1-based).
628 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000629 IsExtern = 0;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000630 Value += getSymbolAddress(&SD, Layout);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000631
632 if (IsPCRel)
Daniel Dunbardb4c7e62010-05-11 23:53:11 +0000633 Value -= FixupAddress + (1 << Log2Size);
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000634 } else if (Symbol->isVariable()) {
635 const MCExpr *Value = Symbol->getVariableValue();
636 int64_t Res;
637 bool isAbs = Value->EvaluateAsAbsolute(Res, Layout, SectionAddress);
638 if (isAbs) {
639 FixedValue = Res;
640 return;
641 } else {
642 report_fatal_error("unsupported relocation of variable '" +
643 Symbol->getName() + "'");
644 }
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000645 } else {
646 report_fatal_error("unsupported relocation of undefined symbol '" +
647 Symbol->getName() + "'");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000648 }
649
650 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
651 if (IsPCRel) {
652 if (IsRIPRel) {
653 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
654 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
655 // rewrite the movq to an leaq at link time if the symbol ends up in
656 // the same linkage unit.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000657 if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000658 Type = macho::RIT_X86_64_GOTLoad;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000659 else
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000660 Type = macho::RIT_X86_64_GOT;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000661 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000662 Type = macho::RIT_X86_64_TLV;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000663 } else if (Modifier != MCSymbolRefExpr::VK_None) {
664 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000665 } else {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000666 Type = macho::RIT_X86_64_Signed;
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000667
668 // The Darwin x86_64 relocation format has a problem where it cannot
669 // encode an address (L<foo> + <constant>) which is outside the atom
670 // containing L<foo>. Generally, this shouldn't occur but it does
671 // happen when we have a RIPrel instruction with data following the
672 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
673 // adjustment Darwin x86_64 uses, the offset is still negative and
674 // the linker has no way to recognize this.
675 //
676 // To work around this, Darwin uses several special relocation types
677 // to indicate the offsets. However, the specification or
678 // implementation of these seems to also be incomplete; they should
679 // adjust the addend as well based on the actual encoded instruction
680 // (the additional bias), but instead appear to just look at the
681 // final offset.
682 switch (-(Target.getConstant() + (1LL << Log2Size))) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000683 case 1: Type = macho::RIT_X86_64_Signed1; break;
684 case 2: Type = macho::RIT_X86_64_Signed2; break;
685 case 4: Type = macho::RIT_X86_64_Signed4; break;
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000686 }
687 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000688 } else {
689 if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000690 report_fatal_error("unsupported symbol modifier in branch "
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000691 "relocation");
692
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000693 Type = macho::RIT_X86_64_Branch;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000694 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000695 } else {
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000696 if (Modifier == MCSymbolRefExpr::VK_GOT) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000697 Type = macho::RIT_X86_64_GOT;
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000698 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
699 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
700 // which case all we do is set the PCrel bit in the relocation entry;
701 // this is used with exception handling, for example. The source is
702 // required to include any necessary offset directly.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000703 Type = macho::RIT_X86_64_GOT;
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000704 IsPCRel = 1;
Eric Christopher96ac5152010-05-26 00:02:12 +0000705 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
706 report_fatal_error("TLVP symbol modifier should have been rip-rel");
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000707 } else if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000708 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000709 else
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000710 Type = macho::RIT_X86_64_Unsigned;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000711 }
712 }
713
714 // x86_64 always writes custom values into the fixups.
715 FixedValue = Value;
716
717 // struct relocation_info (8 bytes)
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000718 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000719 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000720 MRE.Word1 = ((Index << 0) |
721 (IsPCRel << 24) |
722 (Log2Size << 25) |
723 (IsExtern << 27) |
724 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000725 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000726 }
727
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000728 void RecordScatteredRelocation(const MCAssembler &Asm,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000729 const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000730 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000731 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000732 uint64_t &FixedValue) {
Daniel Dunbar482ad802010-05-26 15:18:31 +0000733 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
734 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
735 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000736 unsigned Type = macho::RIT_Vanilla;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000737
738 // See <reloc.h>.
739 const MCSymbol *A = &Target.getSymA()->getSymbol();
740 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
741
742 if (!A_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000743 report_fatal_error("symbol '" + A->getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000744 "' can not be undefined in a subtraction expression");
745
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000746 uint32_t Value = getSymbolAddress(A_SD, Layout);
747 uint64_t SecAddr = getSectionAddress(A_SD->getFragment()->getParent());
748 FixedValue += SecAddr;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000749 uint32_t Value2 = 0;
750
751 if (const MCSymbolRefExpr *B = Target.getSymB()) {
752 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
753
754 if (!B_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000755 report_fatal_error("symbol '" + B->getSymbol().getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000756 "' can not be undefined in a subtraction expression");
757
758 // Select the appropriate difference relocation type.
759 //
760 // Note that there is no longer any semantic difference between these two
761 // relocation types from the linkers point of view, this is done solely
762 // for pedantic compatibility with 'as'.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000763 Type = A_SD->isExternal() ? macho::RIT_Difference :
764 macho::RIT_LocalDifference;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000765 Value2 = getSymbolAddress(B_SD, Layout);
766 FixedValue -= getSectionAddress(B_SD->getFragment()->getParent());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000767 }
768
769 // Relocations are written out in reverse order, so the PAIR comes first.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000770 if (Type == macho::RIT_Difference || Type == macho::RIT_LocalDifference) {
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000771 macho::RelocationEntry MRE;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000772 MRE.Word0 = ((0 << 0) |
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000773 (macho::RIT_Pair << 24) |
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000774 (Log2Size << 28) |
775 (IsPCRel << 30) |
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000776 macho::RF_Scattered);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000777 MRE.Word1 = Value2;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000778 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000779 }
780
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000781 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000782 MRE.Word0 = ((FixupOffset << 0) |
783 (Type << 24) |
784 (Log2Size << 28) |
785 (IsPCRel << 30) |
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000786 macho::RF_Scattered);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000787 MRE.Word1 = Value;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000788 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000789 }
790
Eric Christopherc9ada472010-06-15 22:59:05 +0000791 void RecordTLVPRelocation(const MCAssembler &Asm,
Eric Christophere48dbf82010-06-16 00:26:36 +0000792 const MCAsmLayout &Layout,
793 const MCFragment *Fragment,
794 const MCFixup &Fixup, MCValue Target,
795 uint64_t &FixedValue) {
Eric Christopherc9ada472010-06-15 22:59:05 +0000796 assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
797 !Is64Bit &&
798 "Should only be called with a 32-bit TLVP relocation!");
799
Eric Christopherc9ada472010-06-15 22:59:05 +0000800 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
801 uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
802 unsigned IsPCRel = 0;
803
804 // Get the symbol data.
805 MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
806 unsigned Index = SD_A->getIndex();
807
Eric Christopherbc067372010-06-16 21:32:38 +0000808 // We're only going to have a second symbol in pic mode and it'll be a
809 // subtraction from the picbase. For 32-bit pic the addend is the difference
Eric Christopher04b8d3c2010-06-17 00:49:46 +0000810 // between the picbase and the next address. For 32-bit static the addend
811 // is zero.
Eric Christopherbc067372010-06-16 21:32:38 +0000812 if (Target.getSymB()) {
Eric Christopher1008d352010-06-22 23:51:47 +0000813 // If this is a subtraction then we're pcrel.
814 uint32_t FixupAddress =
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000815 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
Eric Christopher1008d352010-06-22 23:51:47 +0000816 MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
Eric Christopherc9ada472010-06-15 22:59:05 +0000817 IsPCRel = 1;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000818 FixedValue = (FixupAddress - getSymbolAddress(SD_B, Layout) +
Eric Christopher1008d352010-06-22 23:51:47 +0000819 Target.getConstant());
Chris Lattnerabf8f9c2010-08-16 16:35:20 +0000820 FixedValue += 1ULL << Log2Size;
Eric Christopherbc067372010-06-16 21:32:38 +0000821 } else {
822 FixedValue = 0;
823 }
Jim Grosbach3c384922010-11-11 20:16:23 +0000824
Eric Christopherc9ada472010-06-15 22:59:05 +0000825 // struct relocation_info (8 bytes)
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000826 macho::RelocationEntry MRE;
Eric Christopherc9ada472010-06-15 22:59:05 +0000827 MRE.Word0 = Value;
828 MRE.Word1 = ((Index << 0) |
829 (IsPCRel << 24) |
830 (Log2Size << 25) |
831 (1 << 27) | // Extern
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000832 (macho::RIT_TLV << 28)); // Type
Eric Christopherc9ada472010-06-15 22:59:05 +0000833 Relocations[Fragment->getParent()].push_back(MRE);
834 }
Jim Grosbach3c384922010-11-11 20:16:23 +0000835
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000836 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000837 const MCFragment *Fragment, const MCFixup &Fixup,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000838 MCValue Target, uint64_t &FixedValue) {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000839 if (Is64Bit) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000840 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000841 return;
842 }
843
Daniel Dunbar482ad802010-05-26 15:18:31 +0000844 unsigned IsPCRel = isFixupKindPCRel(Fixup.getKind());
845 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000846
Eric Christopherc9ada472010-06-15 22:59:05 +0000847 // If this is a 32-bit TLVP reloc it's handled a bit differently.
Daniel Dunbar23bea412010-09-17 15:21:50 +0000848 if (Target.getSymA() &&
849 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
Eric Christopherc9ada472010-06-15 22:59:05 +0000850 RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
851 return;
852 }
Jim Grosbach3c384922010-11-11 20:16:23 +0000853
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000854 // If this is a difference or a defined symbol plus an offset, then we need
855 // a scattered relocation entry.
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000856 // Differences always require scattered relocations.
857 if (Target.getSymB())
858 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
859 Target, FixedValue);
860
861 // Get the symbol data, if any.
862 MCSymbolData *SD = 0;
863 if (Target.getSymA())
864 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
865
866 // If this is an internal relocation with an offset, it also needs a
867 // scattered relocation entry.
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000868 uint32_t Offset = Target.getConstant();
869 if (IsPCRel)
870 Offset += 1 << Log2Size;
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000871 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
872 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
873 Target, FixedValue);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000874
875 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000876 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000877 unsigned Index = 0;
878 unsigned IsExtern = 0;
879 unsigned Type = 0;
880
881 if (Target.isAbsolute()) { // constant
882 // SymbolNum of 0 indicates the absolute section.
883 //
884 // FIXME: Currently, these are never generated (see code below). I cannot
885 // find a case where they are actually emitted.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000886 Type = macho::RIT_Vanilla;
Michael J. Spencerb0f3b3e2010-08-10 16:00:49 +0000887 } else {
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000888 // Check whether we need an external or internal relocation.
889 if (doesSymbolRequireExternRelocation(SD)) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000890 IsExtern = 1;
891 Index = SD->getIndex();
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000892 // For external relocations, make sure to offset the fixup value to
893 // compensate for the addend of the symbol address, if it was
894 // undefined. This occurs with weak definitions, for example.
895 if (!SD->Symbol->isUndefined())
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000896 FixedValue -= getSymbolAddress(SD, Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000897 } else {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000898 // The index is the section ordinal (1-based).
899 Index = SD->getFragment()->getParent()->getOrdinal() + 1;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000900 FixedValue += getSectionAddress(SD->getFragment()->getParent());
901 if (IsPCRel)
902 FixedValue -= getSectionAddress(Fragment->getParent());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000903 }
904
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000905 Type = macho::RIT_Vanilla;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000906 }
907
908 // struct relocation_info (8 bytes)
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000909 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000910 MRE.Word0 = FixupOffset;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000911 MRE.Word1 = ((Index << 0) |
912 (IsPCRel << 24) |
913 (Log2Size << 25) |
914 (IsExtern << 27) |
915 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000916 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000917 }
918
919 void BindIndirectSymbols(MCAssembler &Asm) {
920 // This is the point where 'as' creates actual symbols for indirect symbols
921 // (in the following two passes). It would be easier for us to do this
922 // sooner when we see the attribute, but that makes getting the order in the
923 // symbol table much more complicated than it is worth.
924 //
925 // FIXME: Revisit this when the dust settles.
926
927 // Bind non lazy symbol pointers first.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000928 unsigned IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000929 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000930 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000931 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +0000932 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000933
934 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
935 continue;
936
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000937 // Initialize the section indirect symbol base, if necessary.
938 if (!IndirectSymBase.count(it->SectionData))
939 IndirectSymBase[it->SectionData] = IndirectIndex;
Jim Grosbach3c384922010-11-11 20:16:23 +0000940
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000941 Asm.getOrCreateSymbolData(*it->Symbol);
942 }
943
944 // Then lazy symbol pointers and symbol stubs.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000945 IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000946 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000947 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000948 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +0000949 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000950
951 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
952 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
953 continue;
954
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000955 // Initialize the section indirect symbol base, if necessary.
956 if (!IndirectSymBase.count(it->SectionData))
957 IndirectSymBase[it->SectionData] = IndirectIndex;
958
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000959 // Set the symbol type to undefined lazy, but only on construction.
960 //
961 // FIXME: Do not hardcode.
962 bool Created;
963 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
964 if (Created)
965 Entry.setFlags(Entry.getFlags() | 0x0001);
966 }
967 }
968
969 /// ComputeSymbolTable - Compute the symbol table data
970 ///
971 /// \param StringTable [out] - The string table data.
972 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
973 /// string table.
974 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
975 std::vector<MachSymbolData> &LocalSymbolData,
976 std::vector<MachSymbolData> &ExternalSymbolData,
977 std::vector<MachSymbolData> &UndefinedSymbolData) {
978 // Build section lookup table.
979 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
980 unsigned Index = 1;
981 for (MCAssembler::iterator it = Asm.begin(),
982 ie = Asm.end(); it != ie; ++it, ++Index)
983 SectionIndexMap[&it->getSection()] = Index;
984 assert(Index <= 256 && "Too many sections!");
985
986 // Index 0 is always the empty string.
987 StringMap<uint64_t> StringIndexMap;
988 StringTable += '\x00';
989
990 // Build the symbol arrays and the string table, but only for non-local
991 // symbols.
992 //
993 // The particular order that we collect the symbols and create the string
994 // table, then sort the symbols is chosen to match 'as'. Even though it
995 // doesn't matter for correctness, this is important for letting us diff .o
996 // files.
997 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
998 ie = Asm.symbol_end(); it != ie; ++it) {
999 const MCSymbol &Symbol = it->getSymbol();
1000
1001 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +00001002 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001003 continue;
1004
1005 if (!it->isExternal() && !Symbol.isUndefined())
1006 continue;
1007
1008 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1009 if (!Entry) {
1010 Entry = StringTable.size();
1011 StringTable += Symbol.getName();
1012 StringTable += '\x00';
1013 }
1014
1015 MachSymbolData MSD;
1016 MSD.SymbolData = it;
1017 MSD.StringIndex = Entry;
1018
1019 if (Symbol.isUndefined()) {
1020 MSD.SectionIndex = 0;
1021 UndefinedSymbolData.push_back(MSD);
1022 } else if (Symbol.isAbsolute()) {
1023 MSD.SectionIndex = 0;
1024 ExternalSymbolData.push_back(MSD);
1025 } else {
1026 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1027 assert(MSD.SectionIndex && "Invalid section index!");
1028 ExternalSymbolData.push_back(MSD);
1029 }
1030 }
1031
1032 // Now add the data for local symbols.
1033 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1034 ie = Asm.symbol_end(); it != ie; ++it) {
1035 const MCSymbol &Symbol = it->getSymbol();
1036
1037 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +00001038 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001039 continue;
1040
1041 if (it->isExternal() || Symbol.isUndefined())
1042 continue;
1043
1044 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1045 if (!Entry) {
1046 Entry = StringTable.size();
1047 StringTable += Symbol.getName();
1048 StringTable += '\x00';
1049 }
1050
1051 MachSymbolData MSD;
1052 MSD.SymbolData = it;
1053 MSD.StringIndex = Entry;
1054
1055 if (Symbol.isAbsolute()) {
1056 MSD.SectionIndex = 0;
1057 LocalSymbolData.push_back(MSD);
1058 } else {
1059 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1060 assert(MSD.SectionIndex && "Invalid section index!");
1061 LocalSymbolData.push_back(MSD);
1062 }
1063 }
1064
1065 // External and undefined symbols are required to be in lexicographic order.
1066 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1067 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1068
1069 // Set the symbol indices.
1070 Index = 0;
1071 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1072 LocalSymbolData[i].SymbolData->setIndex(Index++);
1073 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1074 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1075 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1076 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1077
1078 // The string table is padded to a multiple of 4.
1079 while (StringTable.size() % 4)
1080 StringTable += '\x00';
1081 }
1082
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001083 void computeSectionAddresses(const MCAssembler &Asm,
1084 const MCAsmLayout &Layout) {
1085 uint64_t StartAddress = 0;
1086 const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
1087 for (int i = 0, n = Order.size(); i != n ; ++i) {
1088 const MCSectionData *SD = Order[i];
1089 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
1090 SectionAddress[SD] = StartAddress;
1091 StartAddress += Layout.getSectionAddressSize(SD);
1092 // Explicitly pad the section to match the alignment requirements of the
1093 // following one. This is for 'gas' compatibility, it shouldn't
1094 /// strictly be necessary.
1095 StartAddress += getPaddingSize(SD, Layout);
1096 }
1097 }
1098
1099 void ExecutePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout) {
1100 computeSectionAddresses(Asm, Layout);
1101
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001102 // Create symbol data for any indirect symbols.
1103 BindIndirectSymbols(Asm);
1104
1105 // Compute symbol table information and bind symbol indices.
1106 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1107 UndefinedSymbolData);
1108 }
1109
Rafael Espindola70703872010-09-30 02:22:20 +00001110
1111 bool IsFixupFullyResolved(const MCAssembler &Asm,
1112 const MCValue Target,
1113 bool IsPCRel,
1114 const MCFragment *DF) const {
Daniel Dunbar7976b882010-11-27 05:18:48 +00001115 // If we aren't using scattered symbols, the fixup is fully resolved.
1116 if (!Asm.getBackend().hasScatteredSymbols())
1117 return true;
Rafael Espindola70703872010-09-30 02:22:20 +00001118
Daniel Dunbar7976b882010-11-27 05:18:48 +00001119 // Otherwise, determine whether this value is actually resolved; scattering
1120 // may cause atoms to move.
Rafael Espindola70703872010-09-30 02:22:20 +00001121
Daniel Dunbar7976b882010-11-27 05:18:48 +00001122 // Check if we are using the "simple" resolution algorithm (e.g.,
1123 // i386).
1124 if (!Asm.getBackend().hasReliableSymbolDifference()) {
1125 const MCSection *BaseSection = 0;
1126 if (IsPCRel)
1127 BaseSection = &DF->getParent()->getSection();
1128
1129 return isScatteredFixupFullyResolvedSimple(Asm, Target, BaseSection);
Rafael Espindola70703872010-09-30 02:22:20 +00001130 }
Daniel Dunbar7976b882010-11-27 05:18:48 +00001131
1132 // Otherwise, compute the proper answer as reliably as possible.
1133
1134 // If this is a PCrel relocation, find the base atom (identified by its
1135 // symbol) that the fixup value is relative to.
1136 const MCSymbolData *BaseSymbol = 0;
1137 if (IsPCRel) {
1138 BaseSymbol = DF->getAtom();
1139 if (!BaseSymbol)
1140 return false;
1141 }
1142
1143 return isScatteredFixupFullyResolved(Asm, Target, BaseSymbol);
Rafael Espindola70703872010-09-30 02:22:20 +00001144 }
1145
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001146 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001147 unsigned NumSections = Asm.size();
1148
1149 // The section data starts after the header, the segment load command (and
1150 // section headers) and the symbol table.
1151 unsigned NumLoadCommands = 1;
1152 uint64_t LoadCommandsSize = Is64Bit ?
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001153 macho::SegmentLoadCommand64Size + NumSections * macho::Section64Size :
1154 macho::SegmentLoadCommand32Size + NumSections * macho::Section32Size;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001155
1156 // Add the symbol table load command sizes, if used.
1157 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1158 UndefinedSymbolData.size();
1159 if (NumSymbols) {
1160 NumLoadCommands += 2;
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001161 LoadCommandsSize += (macho::SymtabLoadCommandSize +
1162 macho::DysymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001163 }
1164
1165 // Compute the total size of the section data, as well as its file size and
1166 // vm size.
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001167 uint64_t SectionDataStart = (Is64Bit ? macho::Header64Size :
1168 macho::Header32Size) + LoadCommandsSize;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001169 uint64_t SectionDataSize = 0;
1170 uint64_t SectionDataFileSize = 0;
1171 uint64_t VMSize = 0;
1172 for (MCAssembler::const_iterator it = Asm.begin(),
1173 ie = Asm.end(); it != ie; ++it) {
1174 const MCSectionData &SD = *it;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001175 uint64_t Address = getSectionAddress(&SD);
1176 uint64_t Size = Layout.getSectionAddressSize(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +00001177 uint64_t FileSize = Layout.getSectionFileSize(&SD);
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001178 FileSize += getPaddingSize(&SD, Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001179
Daniel Dunbar5d428512010-03-25 02:00:07 +00001180 VMSize = std::max(VMSize, Address + Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001181
Rafael Espindolaf2dc4aa2010-11-17 20:03:54 +00001182 if (SD.getSection().isVirtualSection())
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001183 continue;
1184
Daniel Dunbar5d428512010-03-25 02:00:07 +00001185 SectionDataSize = std::max(SectionDataSize, Address + Size);
1186 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001187 }
1188
1189 // The section data is padded to 4 bytes.
1190 //
1191 // FIXME: Is this machine dependent?
1192 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1193 SectionDataFileSize += SectionDataPadding;
1194
1195 // Write the prolog, starting with the header and load command...
1196 WriteHeader(NumLoadCommands, LoadCommandsSize,
1197 Asm.getSubsectionsViaSymbols());
1198 WriteSegmentLoadCommand(NumSections, VMSize,
1199 SectionDataStart, SectionDataSize);
1200
1201 // ... and then the section headers.
1202 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1203 for (MCAssembler::const_iterator it = Asm.begin(),
1204 ie = Asm.end(); it != ie; ++it) {
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +00001205 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001206 unsigned NumRelocs = Relocs.size();
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001207 uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001208 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001209 RelocTableEnd += NumRelocs * macho::RelocationInfoSize;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001210 }
1211
1212 // Write the symbol table load command, if used.
1213 if (NumSymbols) {
1214 unsigned FirstLocalSymbol = 0;
1215 unsigned NumLocalSymbols = LocalSymbolData.size();
1216 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1217 unsigned NumExternalSymbols = ExternalSymbolData.size();
1218 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1219 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1220 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1221 unsigned NumSymTabSymbols =
1222 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1223 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1224 uint64_t IndirectSymbolOffset = 0;
1225
1226 // If used, the indirect symbols are written after the section data.
1227 if (NumIndirectSymbols)
1228 IndirectSymbolOffset = RelocTableEnd;
1229
1230 // The symbol table is written after the indirect symbol data.
1231 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1232
1233 // The string table is written after symbol table.
1234 uint64_t StringTableOffset =
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001235 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? macho::Nlist64Size :
1236 macho::Nlist32Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001237 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1238 StringTableOffset, StringTable.size());
1239
1240 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1241 FirstExternalSymbol, NumExternalSymbols,
1242 FirstUndefinedSymbol, NumUndefinedSymbols,
1243 IndirectSymbolOffset, NumIndirectSymbols);
1244 }
1245
1246 // Write the actual section data.
1247 for (MCAssembler::const_iterator it = Asm.begin(),
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001248 ie = Asm.end(); it != ie; ++it) {
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001249 Asm.WriteSectionData(it, Layout, this);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001250
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001251 uint64_t Pad = getPaddingSize(it, Layout);
1252 for (unsigned int i = 0; i < Pad; ++i)
1253 Write8(0);
1254 }
1255
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001256 // Write the extra padding.
1257 WriteZeros(SectionDataPadding);
1258
1259 // Write the relocation entries.
1260 for (MCAssembler::const_iterator it = Asm.begin(),
1261 ie = Asm.end(); it != ie; ++it) {
1262 // Write the section relocation entries, in reverse order to match 'as'
1263 // (approximately, the exact algorithm is more complicated than this).
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +00001264 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001265 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1266 Write32(Relocs[e - i - 1].Word0);
1267 Write32(Relocs[e - i - 1].Word1);
1268 }
1269 }
1270
1271 // Write the symbol table data, if used.
1272 if (NumSymbols) {
1273 // Write the indirect symbol entries.
1274 for (MCAssembler::const_indirect_symbol_iterator
1275 it = Asm.indirect_symbol_begin(),
1276 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1277 // Indirect symbols in the non lazy symbol pointer section have some
1278 // special handling.
1279 const MCSectionMachO &Section =
1280 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1281 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1282 // If this symbol is defined and internal, mark it as such.
1283 if (it->Symbol->isDefined() &&
1284 !Asm.getSymbolData(*it->Symbol).isExternal()) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +00001285 uint32_t Flags = macho::ISF_Local;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001286 if (it->Symbol->isAbsolute())
Daniel Dunbarf52788f2010-11-27 04:59:14 +00001287 Flags |= macho::ISF_Absolute;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001288 Write32(Flags);
1289 continue;
1290 }
1291 }
1292
1293 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1294 }
1295
1296 // FIXME: Check that offsets match computed ones.
1297
1298 // Write the symbol table entries.
1299 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001300 WriteNlist(LocalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001301 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001302 WriteNlist(ExternalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001303 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001304 WriteNlist(UndefinedSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001305
1306 // Write the string table.
1307 OS << StringTable.str();
1308 }
1309 }
1310};
1311
1312}
1313
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001314MCObjectWriter *llvm::createMachObjectWriter(raw_ostream &OS, bool is64Bit,
1315 uint32_t CPUType,
1316 uint32_t CPUSubtype,
1317 bool IsLittleEndian) {
1318 return new MachObjectWriter(OS, is64Bit, CPUType, CPUSubtype, IsLittleEndian);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001319}