blob: fa132d8aebbf5e4bdf97465f38a3489efb841bc4 [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 Dunbarae5abd52010-12-16 16:09:19 +000010#include "llvm/MC/MCMachObjectWriter.h"
11#include "llvm/ADT/OwningPtr.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000012#include "llvm/ADT/StringMap.h"
13#include "llvm/ADT/Twine.h"
14#include "llvm/MC/MCAssembler.h"
Daniel Dunbar207e06e2010-03-24 03:43:40 +000015#include "llvm/MC/MCAsmLayout.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000016#include "llvm/MC/MCExpr.h"
17#include "llvm/MC/MCObjectWriter.h"
18#include "llvm/MC/MCSectionMachO.h"
19#include "llvm/MC/MCSymbol.h"
Kevin Enderbya6eeb6e2010-05-07 21:44:23 +000020#include "llvm/MC/MCMachOSymbolFlags.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000021#include "llvm/MC/MCValue.h"
Daniel Dunbar821ecd72010-11-27 04:19:38 +000022#include "llvm/Object/MachOFormat.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000023#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000024#include "llvm/Target/TargetAsmBackend.h"
25
26// FIXME: Gross.
27#include "../Target/X86/X86FixupKinds.h"
28
29#include <vector>
30using namespace llvm;
Daniel Dunbar821ecd72010-11-27 04:19:38 +000031using namespace llvm::object;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000032
Rafael Espindolaa8c02c32010-09-30 03:11:42 +000033// FIXME: this has been copied from (or to) X86AsmBackend.cpp
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000034static unsigned getFixupKindLog2Size(unsigned Kind) {
35 switch (Kind) {
Jim Grosbachdff84b02010-12-02 00:28:45 +000036 // FIXME: Until ARM has it's own relocation stuff spun off, it comes
37 // through here and we don't want it to puke all over. Any reasonable
38 // values will only come when ARM relocation support gets added, at which
39 // point this will be X86 only again and the llvm_unreachable can be
40 // re-enabled.
41 default: return 0;// llvm_unreachable("invalid fixup kind!");
Rafael Espindolae04ed7e2010-11-28 14:17:56 +000042 case FK_PCRel_1:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000043 case FK_Data_1: return 0;
Rafael Espindolae04ed7e2010-11-28 14:17:56 +000044 case FK_PCRel_2:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000045 case FK_Data_2: return 1;
Rafael Espindolae04ed7e2010-11-28 14:17:56 +000046 case FK_PCRel_4:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000047 case X86::reloc_riprel_4byte:
Daniel Dunbar602b40f2010-03-19 18:07:55 +000048 case X86::reloc_riprel_4byte_movq_load:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +000049 case X86::reloc_signed_4byte:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000050 case FK_Data_4: return 2;
51 case FK_Data_8: return 3;
52 }
53}
54
Daniel Dunbare9460ec2010-05-10 23:15:13 +000055static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
56 // Undefined symbols are always extern.
57 if (SD->Symbol->isUndefined())
58 return true;
59
60 // References to weak definitions require external relocation entries; the
61 // definition may not always be the one in the same object file.
62 if (SD->getFlags() & SF_WeakDefinition)
63 return true;
64
65 // Otherwise, we can use an internal relocation.
66 return false;
67}
68
Rafael Espindola70703872010-09-30 02:22:20 +000069static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
70 const MCValue Target,
71 const MCSymbolData *BaseSymbol) {
72 // The effective fixup address is
73 // addr(atom(A)) + offset(A)
74 // - addr(atom(B)) - offset(B)
75 // - addr(BaseSymbol) + <fixup offset from base symbol>
76 // and the offsets are not relocatable, so the fixup is fully resolved when
77 // addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
78 //
79 // Note that "false" is almost always conservatively correct (it means we emit
80 // a relocation which is unnecessary), except when it would force us to emit a
81 // relocation which the target cannot encode.
82
83 const MCSymbolData *A_Base = 0, *B_Base = 0;
84 if (const MCSymbolRefExpr *A = Target.getSymA()) {
85 // Modified symbol references cannot be resolved.
86 if (A->getKind() != MCSymbolRefExpr::VK_None)
87 return false;
88
89 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
90 if (!A_Base)
91 return false;
92 }
93
94 if (const MCSymbolRefExpr *B = Target.getSymB()) {
95 // Modified symbol references cannot be resolved.
96 if (B->getKind() != MCSymbolRefExpr::VK_None)
97 return false;
98
99 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
100 if (!B_Base)
101 return false;
102 }
103
104 // If there is no base, A and B have to be the same atom for this fixup to be
105 // fully resolved.
106 if (!BaseSymbol)
107 return A_Base == B_Base;
108
109 // Otherwise, B must be missing and A must be the base.
110 return !B_Base && BaseSymbol == A_Base;
111}
112
113static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
114 const MCValue Target,
115 const MCSection *BaseSection) {
116 // The effective fixup address is
117 // addr(atom(A)) + offset(A)
118 // - addr(atom(B)) - offset(B)
119 // - addr(<base symbol>) + <fixup offset from base symbol>
120 // and the offsets are not relocatable, so the fixup is fully resolved when
121 // addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
122 //
123 // The simple (Darwin, except on x86_64) way of dealing with this was to
124 // assume that any reference to a temporary symbol *must* be a temporary
125 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
126 // relocation to a temporary symbol (in the same section) is fully
127 // resolved. This also works in conjunction with absolutized .set, which
128 // requires the compiler to use .set to absolutize the differences between
129 // symbols which the compiler knows to be assembly time constants, so we don't
130 // need to worry about considering symbol differences fully resolved.
131
132 // Non-relative fixups are only resolved if constant.
133 if (!BaseSection)
134 return Target.isAbsolute();
135
136 // Otherwise, relative fixups are only resolved if not a difference and the
137 // target is a temporary in the same section.
138 if (Target.isAbsolute() || Target.getSymB())
139 return false;
140
141 const MCSymbol *A = &Target.getSymA()->getSymbol();
142 if (!A->isTemporary() || !A->isInSection() ||
143 &A->getSection() != BaseSection)
144 return false;
145
146 return true;
147}
148
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000149namespace {
150
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000151class MachObjectWriter : public MCObjectWriter {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000152 /// MachSymbolData - Helper struct for containing some precomputed information
153 /// on symbols.
154 struct MachSymbolData {
155 MCSymbolData *SymbolData;
156 uint64_t StringIndex;
157 uint8_t SectionIndex;
158
159 // Support lexicographic sorting.
160 bool operator<(const MachSymbolData &RHS) const {
Benjamin Kramerc37791e2010-05-20 14:14:22 +0000161 return SymbolData->getSymbol().getName() <
162 RHS.SymbolData->getSymbol().getName();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000163 }
164 };
165
Daniel Dunbarae5abd52010-12-16 16:09:19 +0000166 /// The target specific Mach-O writer instance.
167 llvm::OwningPtr<MCMachObjectTargetWriter> TargetObjectWriter;
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000168
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000169 /// @name Relocation Data
170 /// @{
171
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000172 llvm::DenseMap<const MCSectionData*,
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000173 std::vector<macho::RelocationEntry> > Relocations;
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000174 llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000175
176 /// @}
177 /// @name Symbol Table Data
178 /// @{
179
180 SmallString<256> StringTable;
181 std::vector<MachSymbolData> LocalSymbolData;
182 std::vector<MachSymbolData> ExternalSymbolData;
183 std::vector<MachSymbolData> UndefinedSymbolData;
184
185 /// @}
186
Daniel Dunbarae5abd52010-12-16 16:09:19 +0000187private:
188 /// @name Utility Methods
189 /// @{
190
191 bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
192 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
193 (MCFixupKind) Kind);
194
195 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
196 }
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 Dunbarae5abd52010-12-16 16:09:19 +0000234 MachObjectWriter(MCMachObjectTargetWriter *MOTW, raw_ostream &_OS,
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000235 bool _Is64Bit, uint32_t _CPUType, uint32_t _CPUSubtype,
236 bool _IsLittleEndian)
Daniel Dunbarae5abd52010-12-16 16:09:19 +0000237 : MCObjectWriter(_OS, _IsLittleEndian), TargetObjectWriter(MOTW),
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000238 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 Dunbar7e06af82010-12-16 15:42:31 +0000492 static bool isFixupKindRIPRel(unsigned Kind) {
493 return Kind == X86::reloc_riprel_4byte ||
494 Kind == X86::reloc_riprel_4byte_movq_load;
495 }
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000496 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000497 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000498 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000499 uint64_t &FixedValue) {
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000500 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Daniel Dunbar482ad802010-05-26 15:18:31 +0000501 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
502 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000503
504 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000505 uint32_t FixupOffset =
506 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
507 uint32_t FixupAddress =
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000508 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000509 int64_t Value = 0;
510 unsigned Index = 0;
511 unsigned IsExtern = 0;
512 unsigned Type = 0;
513
514 Value = Target.getConstant();
515
516 if (IsPCRel) {
517 // Compensate for the relocation offset, Darwin x86_64 relocations only
518 // have the addend and appear to have attempted to define it to be the
519 // actual expression addend without the PCrel bias. However, instructions
520 // with data following the relocation are not accomodated for (see comment
521 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
Benjamin Kramer454c4ce2010-04-08 15:25:57 +0000522 Value += 1LL << Log2Size;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000523 }
524
525 if (Target.isAbsolute()) { // constant
526 // SymbolNum of 0 indicates the absolute section.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000527 Type = macho::RIT_X86_64_Unsigned;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000528 Index = 0;
529
530 // FIXME: I believe this is broken, I don't think the linker can
531 // understand it. I think it would require a local relocation, but I'm not
532 // sure if that would work either. The official way to get an absolute
533 // PCrel relocation is to use an absolute symbol (which we don't support
534 // yet).
535 if (IsPCRel) {
536 IsExtern = 1;
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000537 Type = macho::RIT_X86_64_Branch;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000538 }
539 } else if (Target.getSymB()) { // A - B + constant
540 const MCSymbol *A = &Target.getSymA()->getSymbol();
541 MCSymbolData &A_SD = Asm.getSymbolData(*A);
Rafael Espindolab8141102010-09-27 18:13:03 +0000542 const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000543
544 const MCSymbol *B = &Target.getSymB()->getSymbol();
545 MCSymbolData &B_SD = Asm.getSymbolData(*B);
Rafael Espindolab8141102010-09-27 18:13:03 +0000546 const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000547
548 // Neither symbol can be modified.
549 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
550 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000551 report_fatal_error("unsupported relocation of modified symbol");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000552
553 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
554 // implement most of these correctly.
555 if (IsPCRel)
Chris Lattner75361b62010-04-07 22:58:41 +0000556 report_fatal_error("unsupported pc-relative relocation of difference");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000557
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000558 // The support for the situation where one or both of the symbols would
559 // require a local relocation is handled just like if the symbols were
560 // external. This is certainly used in the case of debug sections where
561 // the section has only temporary symbols and thus the symbols don't have
562 // base symbols. This is encoded using the section ordinal and
563 // non-extern relocation entries.
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000564
565 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000566 // a single SIGNED relocation); reject it for now. Except the case where
567 // both symbols don't have a base, equal but both NULL.
568 if (A_Base == B_Base && A_Base)
Chris Lattner75361b62010-04-07 22:58:41 +0000569 report_fatal_error("unsupported relocation with identical base");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000570
Rafael Espindolaf10d2be2010-12-07 01:09:54 +0000571 Value += getSymbolAddress(&A_SD, Layout) -
572 (A_Base == NULL ? 0 : getSymbolAddress(A_Base, Layout));
573 Value -= getSymbolAddress(&B_SD, Layout) -
574 (B_Base == NULL ? 0 : getSymbolAddress(B_Base, Layout));
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000575
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000576 if (A_Base) {
577 Index = A_Base->getIndex();
578 IsExtern = 1;
579 }
580 else {
581 Index = A_SD.getFragment()->getParent()->getOrdinal() + 1;
582 IsExtern = 0;
583 }
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000584 Type = macho::RIT_X86_64_Unsigned;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000585
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000586 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000587 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000588 MRE.Word1 = ((Index << 0) |
589 (IsPCRel << 24) |
590 (Log2Size << 25) |
591 (IsExtern << 27) |
592 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000593 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000594
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000595 if (B_Base) {
596 Index = B_Base->getIndex();
597 IsExtern = 1;
598 }
599 else {
600 Index = B_SD.getFragment()->getParent()->getOrdinal() + 1;
601 IsExtern = 0;
602 }
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000603 Type = macho::RIT_X86_64_Subtractor;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000604 } else {
605 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
606 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
Rafael Espindolab8141102010-09-27 18:13:03 +0000607 const MCSymbolData *Base = Asm.getAtom(&SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000608
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000609 // Relocations inside debug sections always use local relocations when
610 // possible. This seems to be done because the debugger doesn't fully
611 // understand x86_64 relocation entries, and expects to find values that
612 // have already been fixed up.
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000613 if (Symbol->isInSection()) {
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000614 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
615 Fragment->getParent()->getSection());
616 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
617 Base = 0;
618 }
619
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000620 // x86_64 almost always uses external relocations, except when there is no
621 // symbol to use as a base address (a local symbol with no preceeding
622 // non-local symbol).
623 if (Base) {
624 Index = Base->getIndex();
625 IsExtern = 1;
626
627 // Add the local offset, if needed.
628 if (Base != &SD)
Rafael Espindola1dda29b2010-12-06 21:51:55 +0000629 Value += Layout.getSymbolOffset(&SD) - Layout.getSymbolOffset(Base);
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000630 } else if (Symbol->isInSection()) {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000631 // The index is the section ordinal (1-based).
632 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000633 IsExtern = 0;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000634 Value += getSymbolAddress(&SD, Layout);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000635
636 if (IsPCRel)
Daniel Dunbardb4c7e62010-05-11 23:53:11 +0000637 Value -= FixupAddress + (1 << Log2Size);
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000638 } else if (Symbol->isVariable()) {
639 const MCExpr *Value = Symbol->getVariableValue();
640 int64_t Res;
641 bool isAbs = Value->EvaluateAsAbsolute(Res, Layout, SectionAddress);
642 if (isAbs) {
643 FixedValue = Res;
644 return;
645 } else {
646 report_fatal_error("unsupported relocation of variable '" +
647 Symbol->getName() + "'");
648 }
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000649 } else {
650 report_fatal_error("unsupported relocation of undefined symbol '" +
651 Symbol->getName() + "'");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000652 }
653
654 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
655 if (IsPCRel) {
656 if (IsRIPRel) {
657 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
658 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
659 // rewrite the movq to an leaq at link time if the symbol ends up in
660 // the same linkage unit.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000661 if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000662 Type = macho::RIT_X86_64_GOTLoad;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000663 else
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000664 Type = macho::RIT_X86_64_GOT;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000665 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000666 Type = macho::RIT_X86_64_TLV;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000667 } else if (Modifier != MCSymbolRefExpr::VK_None) {
668 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000669 } else {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000670 Type = macho::RIT_X86_64_Signed;
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000671
672 // The Darwin x86_64 relocation format has a problem where it cannot
673 // encode an address (L<foo> + <constant>) which is outside the atom
674 // containing L<foo>. Generally, this shouldn't occur but it does
675 // happen when we have a RIPrel instruction with data following the
676 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
677 // adjustment Darwin x86_64 uses, the offset is still negative and
678 // the linker has no way to recognize this.
679 //
680 // To work around this, Darwin uses several special relocation types
681 // to indicate the offsets. However, the specification or
682 // implementation of these seems to also be incomplete; they should
683 // adjust the addend as well based on the actual encoded instruction
684 // (the additional bias), but instead appear to just look at the
685 // final offset.
686 switch (-(Target.getConstant() + (1LL << Log2Size))) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000687 case 1: Type = macho::RIT_X86_64_Signed1; break;
688 case 2: Type = macho::RIT_X86_64_Signed2; break;
689 case 4: Type = macho::RIT_X86_64_Signed4; break;
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000690 }
691 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000692 } else {
693 if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000694 report_fatal_error("unsupported symbol modifier in branch "
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000695 "relocation");
696
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000697 Type = macho::RIT_X86_64_Branch;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000698 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000699 } else {
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000700 if (Modifier == MCSymbolRefExpr::VK_GOT) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000701 Type = macho::RIT_X86_64_GOT;
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000702 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
703 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
704 // which case all we do is set the PCrel bit in the relocation entry;
705 // this is used with exception handling, for example. The source is
706 // required to include any necessary offset directly.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000707 Type = macho::RIT_X86_64_GOT;
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000708 IsPCRel = 1;
Eric Christopher96ac5152010-05-26 00:02:12 +0000709 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
710 report_fatal_error("TLVP symbol modifier should have been rip-rel");
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000711 } else if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000712 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000713 else
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000714 Type = macho::RIT_X86_64_Unsigned;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000715 }
716 }
717
718 // x86_64 always writes custom values into the fixups.
719 FixedValue = Value;
720
721 // struct relocation_info (8 bytes)
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000722 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000723 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000724 MRE.Word1 = ((Index << 0) |
725 (IsPCRel << 24) |
726 (Log2Size << 25) |
727 (IsExtern << 27) |
728 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000729 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000730 }
731
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000732 void RecordScatteredRelocation(const MCAssembler &Asm,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000733 const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000734 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000735 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000736 uint64_t &FixedValue) {
Daniel Dunbar482ad802010-05-26 15:18:31 +0000737 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000738 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Daniel Dunbar482ad802010-05-26 15:18:31 +0000739 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000740 unsigned Type = macho::RIT_Vanilla;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000741
742 // See <reloc.h>.
743 const MCSymbol *A = &Target.getSymA()->getSymbol();
744 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
745
746 if (!A_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000747 report_fatal_error("symbol '" + A->getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000748 "' can not be undefined in a subtraction expression");
749
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000750 uint32_t Value = getSymbolAddress(A_SD, Layout);
751 uint64_t SecAddr = getSectionAddress(A_SD->getFragment()->getParent());
752 FixedValue += SecAddr;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000753 uint32_t Value2 = 0;
754
755 if (const MCSymbolRefExpr *B = Target.getSymB()) {
756 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
757
758 if (!B_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000759 report_fatal_error("symbol '" + B->getSymbol().getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000760 "' can not be undefined in a subtraction expression");
761
762 // Select the appropriate difference relocation type.
763 //
764 // Note that there is no longer any semantic difference between these two
765 // relocation types from the linkers point of view, this is done solely
766 // for pedantic compatibility with 'as'.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000767 Type = A_SD->isExternal() ? macho::RIT_Difference :
768 macho::RIT_LocalDifference;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000769 Value2 = getSymbolAddress(B_SD, Layout);
770 FixedValue -= getSectionAddress(B_SD->getFragment()->getParent());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000771 }
772
773 // Relocations are written out in reverse order, so the PAIR comes first.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000774 if (Type == macho::RIT_Difference || Type == macho::RIT_LocalDifference) {
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000775 macho::RelocationEntry MRE;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000776 MRE.Word0 = ((0 << 0) |
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000777 (macho::RIT_Pair << 24) |
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000778 (Log2Size << 28) |
779 (IsPCRel << 30) |
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000780 macho::RF_Scattered);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000781 MRE.Word1 = Value2;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000782 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000783 }
784
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000785 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000786 MRE.Word0 = ((FixupOffset << 0) |
787 (Type << 24) |
788 (Log2Size << 28) |
789 (IsPCRel << 30) |
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000790 macho::RF_Scattered);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000791 MRE.Word1 = Value;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000792 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000793 }
794
Eric Christopherc9ada472010-06-15 22:59:05 +0000795 void RecordTLVPRelocation(const MCAssembler &Asm,
Eric Christophere48dbf82010-06-16 00:26:36 +0000796 const MCAsmLayout &Layout,
797 const MCFragment *Fragment,
798 const MCFixup &Fixup, MCValue Target,
799 uint64_t &FixedValue) {
Eric Christopherc9ada472010-06-15 22:59:05 +0000800 assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
801 !Is64Bit &&
802 "Should only be called with a 32-bit TLVP relocation!");
803
Eric Christopherc9ada472010-06-15 22:59:05 +0000804 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
805 uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
806 unsigned IsPCRel = 0;
807
808 // Get the symbol data.
809 MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
810 unsigned Index = SD_A->getIndex();
811
Eric Christopherbc067372010-06-16 21:32:38 +0000812 // We're only going to have a second symbol in pic mode and it'll be a
813 // subtraction from the picbase. For 32-bit pic the addend is the difference
Eric Christopher04b8d3c2010-06-17 00:49:46 +0000814 // between the picbase and the next address. For 32-bit static the addend
815 // is zero.
Eric Christopherbc067372010-06-16 21:32:38 +0000816 if (Target.getSymB()) {
Eric Christopher1008d352010-06-22 23:51:47 +0000817 // If this is a subtraction then we're pcrel.
818 uint32_t FixupAddress =
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000819 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
Eric Christopher1008d352010-06-22 23:51:47 +0000820 MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
Eric Christopherc9ada472010-06-15 22:59:05 +0000821 IsPCRel = 1;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000822 FixedValue = (FixupAddress - getSymbolAddress(SD_B, Layout) +
Eric Christopher1008d352010-06-22 23:51:47 +0000823 Target.getConstant());
Chris Lattnerabf8f9c2010-08-16 16:35:20 +0000824 FixedValue += 1ULL << Log2Size;
Eric Christopherbc067372010-06-16 21:32:38 +0000825 } else {
826 FixedValue = 0;
827 }
Jim Grosbach3c384922010-11-11 20:16:23 +0000828
Eric Christopherc9ada472010-06-15 22:59:05 +0000829 // struct relocation_info (8 bytes)
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000830 macho::RelocationEntry MRE;
Eric Christopherc9ada472010-06-15 22:59:05 +0000831 MRE.Word0 = Value;
832 MRE.Word1 = ((Index << 0) |
833 (IsPCRel << 24) |
834 (Log2Size << 25) |
835 (1 << 27) | // Extern
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000836 (macho::RIT_TLV << 28)); // Type
Eric Christopherc9ada472010-06-15 22:59:05 +0000837 Relocations[Fragment->getParent()].push_back(MRE);
838 }
Jim Grosbach3c384922010-11-11 20:16:23 +0000839
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000840 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000841 const MCFragment *Fragment, const MCFixup &Fixup,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000842 MCValue Target, uint64_t &FixedValue) {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000843 if (Is64Bit) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000844 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000845 return;
846 }
847
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000848 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Daniel Dunbar482ad802010-05-26 15:18:31 +0000849 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000850
Eric Christopherc9ada472010-06-15 22:59:05 +0000851 // If this is a 32-bit TLVP reloc it's handled a bit differently.
Daniel Dunbar23bea412010-09-17 15:21:50 +0000852 if (Target.getSymA() &&
853 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
Eric Christopherc9ada472010-06-15 22:59:05 +0000854 RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
855 return;
856 }
Jim Grosbach3c384922010-11-11 20:16:23 +0000857
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000858 // If this is a difference or a defined symbol plus an offset, then we need
859 // a scattered relocation entry.
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000860 // Differences always require scattered relocations.
861 if (Target.getSymB())
862 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
863 Target, FixedValue);
864
865 // Get the symbol data, if any.
866 MCSymbolData *SD = 0;
867 if (Target.getSymA())
868 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
869
870 // If this is an internal relocation with an offset, it also needs a
871 // scattered relocation entry.
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000872 uint32_t Offset = Target.getConstant();
873 if (IsPCRel)
874 Offset += 1 << Log2Size;
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000875 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
876 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
877 Target, FixedValue);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000878
879 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000880 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000881 unsigned Index = 0;
882 unsigned IsExtern = 0;
883 unsigned Type = 0;
884
885 if (Target.isAbsolute()) { // constant
886 // SymbolNum of 0 indicates the absolute section.
887 //
888 // FIXME: Currently, these are never generated (see code below). I cannot
889 // find a case where they are actually emitted.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000890 Type = macho::RIT_Vanilla;
Rafael Espindola545b77e2010-12-07 17:12:32 +0000891 } else if (SD->getSymbol().isVariable()) {
892 const MCExpr *Value = SD->getSymbol().getVariableValue();
893 int64_t Res;
894 bool isAbs = Value->EvaluateAsAbsolute(Res, Layout, SectionAddress);
895 if (isAbs) {
896 FixedValue = Res;
897 return;
898 } else {
899 report_fatal_error("unsupported relocation of variable '" +
900 SD->getSymbol().getName() + "'");
901 }
Michael J. Spencerb0f3b3e2010-08-10 16:00:49 +0000902 } else {
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000903 // Check whether we need an external or internal relocation.
904 if (doesSymbolRequireExternRelocation(SD)) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000905 IsExtern = 1;
906 Index = SD->getIndex();
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000907 // For external relocations, make sure to offset the fixup value to
908 // compensate for the addend of the symbol address, if it was
909 // undefined. This occurs with weak definitions, for example.
910 if (!SD->Symbol->isUndefined())
Rafael Espindola3b3148f2010-12-07 05:57:28 +0000911 FixedValue -= Layout.getSymbolOffset(SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000912 } else {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000913 // The index is the section ordinal (1-based).
914 Index = SD->getFragment()->getParent()->getOrdinal() + 1;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000915 FixedValue += getSectionAddress(SD->getFragment()->getParent());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000916 }
Rafael Espindolabf60dad2010-12-07 03:50:14 +0000917 if (IsPCRel)
918 FixedValue -= getSectionAddress(Fragment->getParent());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000919
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000920 Type = macho::RIT_Vanilla;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000921 }
922
923 // struct relocation_info (8 bytes)
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000924 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000925 MRE.Word0 = FixupOffset;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000926 MRE.Word1 = ((Index << 0) |
927 (IsPCRel << 24) |
928 (Log2Size << 25) |
929 (IsExtern << 27) |
930 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000931 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000932 }
933
934 void BindIndirectSymbols(MCAssembler &Asm) {
935 // This is the point where 'as' creates actual symbols for indirect symbols
936 // (in the following two passes). It would be easier for us to do this
937 // sooner when we see the attribute, but that makes getting the order in the
938 // symbol table much more complicated than it is worth.
939 //
940 // FIXME: Revisit this when the dust settles.
941
942 // Bind non lazy symbol pointers first.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000943 unsigned IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000944 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000945 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000946 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +0000947 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000948
949 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
950 continue;
951
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000952 // Initialize the section indirect symbol base, if necessary.
953 if (!IndirectSymBase.count(it->SectionData))
954 IndirectSymBase[it->SectionData] = IndirectIndex;
Jim Grosbach3c384922010-11-11 20:16:23 +0000955
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000956 Asm.getOrCreateSymbolData(*it->Symbol);
957 }
958
959 // Then lazy symbol pointers and symbol stubs.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000960 IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000961 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000962 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000963 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +0000964 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000965
966 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
967 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
968 continue;
969
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000970 // Initialize the section indirect symbol base, if necessary.
971 if (!IndirectSymBase.count(it->SectionData))
972 IndirectSymBase[it->SectionData] = IndirectIndex;
973
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000974 // Set the symbol type to undefined lazy, but only on construction.
975 //
976 // FIXME: Do not hardcode.
977 bool Created;
978 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
979 if (Created)
980 Entry.setFlags(Entry.getFlags() | 0x0001);
981 }
982 }
983
984 /// ComputeSymbolTable - Compute the symbol table data
985 ///
986 /// \param StringTable [out] - The string table data.
987 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
988 /// string table.
989 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
990 std::vector<MachSymbolData> &LocalSymbolData,
991 std::vector<MachSymbolData> &ExternalSymbolData,
992 std::vector<MachSymbolData> &UndefinedSymbolData) {
993 // Build section lookup table.
994 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
995 unsigned Index = 1;
996 for (MCAssembler::iterator it = Asm.begin(),
997 ie = Asm.end(); it != ie; ++it, ++Index)
998 SectionIndexMap[&it->getSection()] = Index;
999 assert(Index <= 256 && "Too many sections!");
1000
1001 // Index 0 is always the empty string.
1002 StringMap<uint64_t> StringIndexMap;
1003 StringTable += '\x00';
1004
1005 // Build the symbol arrays and the string table, but only for non-local
1006 // symbols.
1007 //
1008 // The particular order that we collect the symbols and create the string
1009 // table, then sort the symbols is chosen to match 'as'. Even though it
1010 // doesn't matter for correctness, this is important for letting us diff .o
1011 // files.
1012 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1013 ie = Asm.symbol_end(); it != ie; ++it) {
1014 const MCSymbol &Symbol = it->getSymbol();
1015
1016 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +00001017 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001018 continue;
1019
1020 if (!it->isExternal() && !Symbol.isUndefined())
1021 continue;
1022
1023 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1024 if (!Entry) {
1025 Entry = StringTable.size();
1026 StringTable += Symbol.getName();
1027 StringTable += '\x00';
1028 }
1029
1030 MachSymbolData MSD;
1031 MSD.SymbolData = it;
1032 MSD.StringIndex = Entry;
1033
1034 if (Symbol.isUndefined()) {
1035 MSD.SectionIndex = 0;
1036 UndefinedSymbolData.push_back(MSD);
1037 } else if (Symbol.isAbsolute()) {
1038 MSD.SectionIndex = 0;
1039 ExternalSymbolData.push_back(MSD);
1040 } else {
1041 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1042 assert(MSD.SectionIndex && "Invalid section index!");
1043 ExternalSymbolData.push_back(MSD);
1044 }
1045 }
1046
1047 // Now add the data for local symbols.
1048 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1049 ie = Asm.symbol_end(); it != ie; ++it) {
1050 const MCSymbol &Symbol = it->getSymbol();
1051
1052 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +00001053 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001054 continue;
1055
1056 if (it->isExternal() || Symbol.isUndefined())
1057 continue;
1058
1059 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1060 if (!Entry) {
1061 Entry = StringTable.size();
1062 StringTable += Symbol.getName();
1063 StringTable += '\x00';
1064 }
1065
1066 MachSymbolData MSD;
1067 MSD.SymbolData = it;
1068 MSD.StringIndex = Entry;
1069
1070 if (Symbol.isAbsolute()) {
1071 MSD.SectionIndex = 0;
1072 LocalSymbolData.push_back(MSD);
1073 } else {
1074 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1075 assert(MSD.SectionIndex && "Invalid section index!");
1076 LocalSymbolData.push_back(MSD);
1077 }
1078 }
1079
1080 // External and undefined symbols are required to be in lexicographic order.
1081 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1082 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1083
1084 // Set the symbol indices.
1085 Index = 0;
1086 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1087 LocalSymbolData[i].SymbolData->setIndex(Index++);
1088 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1089 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1090 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1091 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1092
1093 // The string table is padded to a multiple of 4.
1094 while (StringTable.size() % 4)
1095 StringTable += '\x00';
1096 }
1097
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001098 void computeSectionAddresses(const MCAssembler &Asm,
1099 const MCAsmLayout &Layout) {
1100 uint64_t StartAddress = 0;
1101 const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
1102 for (int i = 0, n = Order.size(); i != n ; ++i) {
1103 const MCSectionData *SD = Order[i];
1104 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
1105 SectionAddress[SD] = StartAddress;
1106 StartAddress += Layout.getSectionAddressSize(SD);
1107 // Explicitly pad the section to match the alignment requirements of the
1108 // following one. This is for 'gas' compatibility, it shouldn't
1109 /// strictly be necessary.
1110 StartAddress += getPaddingSize(SD, Layout);
1111 }
1112 }
1113
1114 void ExecutePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout) {
1115 computeSectionAddresses(Asm, Layout);
1116
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001117 // Create symbol data for any indirect symbols.
1118 BindIndirectSymbols(Asm);
1119
1120 // Compute symbol table information and bind symbol indices.
1121 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1122 UndefinedSymbolData);
1123 }
1124
Rafael Espindola70703872010-09-30 02:22:20 +00001125
1126 bool IsFixupFullyResolved(const MCAssembler &Asm,
1127 const MCValue Target,
1128 bool IsPCRel,
1129 const MCFragment *DF) const {
Daniel Dunbar7976b882010-11-27 05:18:48 +00001130 // If we aren't using scattered symbols, the fixup is fully resolved.
1131 if (!Asm.getBackend().hasScatteredSymbols())
1132 return true;
Rafael Espindola70703872010-09-30 02:22:20 +00001133
Daniel Dunbar7976b882010-11-27 05:18:48 +00001134 // Otherwise, determine whether this value is actually resolved; scattering
1135 // may cause atoms to move.
Rafael Espindola70703872010-09-30 02:22:20 +00001136
Daniel Dunbar7976b882010-11-27 05:18:48 +00001137 // Check if we are using the "simple" resolution algorithm (e.g.,
1138 // i386).
1139 if (!Asm.getBackend().hasReliableSymbolDifference()) {
1140 const MCSection *BaseSection = 0;
1141 if (IsPCRel)
1142 BaseSection = &DF->getParent()->getSection();
1143
1144 return isScatteredFixupFullyResolvedSimple(Asm, Target, BaseSection);
Rafael Espindola70703872010-09-30 02:22:20 +00001145 }
Daniel Dunbar7976b882010-11-27 05:18:48 +00001146
1147 // Otherwise, compute the proper answer as reliably as possible.
1148
1149 // If this is a PCrel relocation, find the base atom (identified by its
1150 // symbol) that the fixup value is relative to.
1151 const MCSymbolData *BaseSymbol = 0;
1152 if (IsPCRel) {
1153 BaseSymbol = DF->getAtom();
1154 if (!BaseSymbol)
1155 return false;
1156 }
1157
1158 return isScatteredFixupFullyResolved(Asm, Target, BaseSymbol);
Rafael Espindola70703872010-09-30 02:22:20 +00001159 }
1160
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001161 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001162 unsigned NumSections = Asm.size();
1163
1164 // The section data starts after the header, the segment load command (and
1165 // section headers) and the symbol table.
1166 unsigned NumLoadCommands = 1;
1167 uint64_t LoadCommandsSize = Is64Bit ?
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001168 macho::SegmentLoadCommand64Size + NumSections * macho::Section64Size :
1169 macho::SegmentLoadCommand32Size + NumSections * macho::Section32Size;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001170
1171 // Add the symbol table load command sizes, if used.
1172 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1173 UndefinedSymbolData.size();
1174 if (NumSymbols) {
1175 NumLoadCommands += 2;
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001176 LoadCommandsSize += (macho::SymtabLoadCommandSize +
1177 macho::DysymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001178 }
1179
1180 // Compute the total size of the section data, as well as its file size and
1181 // vm size.
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001182 uint64_t SectionDataStart = (Is64Bit ? macho::Header64Size :
1183 macho::Header32Size) + LoadCommandsSize;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001184 uint64_t SectionDataSize = 0;
1185 uint64_t SectionDataFileSize = 0;
1186 uint64_t VMSize = 0;
1187 for (MCAssembler::const_iterator it = Asm.begin(),
1188 ie = Asm.end(); it != ie; ++it) {
1189 const MCSectionData &SD = *it;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001190 uint64_t Address = getSectionAddress(&SD);
1191 uint64_t Size = Layout.getSectionAddressSize(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +00001192 uint64_t FileSize = Layout.getSectionFileSize(&SD);
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001193 FileSize += getPaddingSize(&SD, Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001194
Daniel Dunbar5d428512010-03-25 02:00:07 +00001195 VMSize = std::max(VMSize, Address + Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001196
Rafael Espindolaf2dc4aa2010-11-17 20:03:54 +00001197 if (SD.getSection().isVirtualSection())
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001198 continue;
1199
Daniel Dunbar5d428512010-03-25 02:00:07 +00001200 SectionDataSize = std::max(SectionDataSize, Address + Size);
1201 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001202 }
1203
1204 // The section data is padded to 4 bytes.
1205 //
1206 // FIXME: Is this machine dependent?
1207 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1208 SectionDataFileSize += SectionDataPadding;
1209
1210 // Write the prolog, starting with the header and load command...
1211 WriteHeader(NumLoadCommands, LoadCommandsSize,
1212 Asm.getSubsectionsViaSymbols());
1213 WriteSegmentLoadCommand(NumSections, VMSize,
1214 SectionDataStart, SectionDataSize);
1215
1216 // ... and then the section headers.
1217 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1218 for (MCAssembler::const_iterator it = Asm.begin(),
1219 ie = Asm.end(); it != ie; ++it) {
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +00001220 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001221 unsigned NumRelocs = Relocs.size();
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001222 uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001223 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001224 RelocTableEnd += NumRelocs * macho::RelocationInfoSize;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001225 }
1226
1227 // Write the symbol table load command, if used.
1228 if (NumSymbols) {
1229 unsigned FirstLocalSymbol = 0;
1230 unsigned NumLocalSymbols = LocalSymbolData.size();
1231 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1232 unsigned NumExternalSymbols = ExternalSymbolData.size();
1233 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1234 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1235 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1236 unsigned NumSymTabSymbols =
1237 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1238 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1239 uint64_t IndirectSymbolOffset = 0;
1240
1241 // If used, the indirect symbols are written after the section data.
1242 if (NumIndirectSymbols)
1243 IndirectSymbolOffset = RelocTableEnd;
1244
1245 // The symbol table is written after the indirect symbol data.
1246 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1247
1248 // The string table is written after symbol table.
1249 uint64_t StringTableOffset =
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001250 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? macho::Nlist64Size :
1251 macho::Nlist32Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001252 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1253 StringTableOffset, StringTable.size());
1254
1255 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1256 FirstExternalSymbol, NumExternalSymbols,
1257 FirstUndefinedSymbol, NumUndefinedSymbols,
1258 IndirectSymbolOffset, NumIndirectSymbols);
1259 }
1260
1261 // Write the actual section data.
1262 for (MCAssembler::const_iterator it = Asm.begin(),
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001263 ie = Asm.end(); it != ie; ++it) {
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001264 Asm.WriteSectionData(it, Layout, this);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001265
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001266 uint64_t Pad = getPaddingSize(it, Layout);
1267 for (unsigned int i = 0; i < Pad; ++i)
1268 Write8(0);
1269 }
1270
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001271 // Write the extra padding.
1272 WriteZeros(SectionDataPadding);
1273
1274 // Write the relocation entries.
1275 for (MCAssembler::const_iterator it = Asm.begin(),
1276 ie = Asm.end(); it != ie; ++it) {
1277 // Write the section relocation entries, in reverse order to match 'as'
1278 // (approximately, the exact algorithm is more complicated than this).
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +00001279 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001280 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1281 Write32(Relocs[e - i - 1].Word0);
1282 Write32(Relocs[e - i - 1].Word1);
1283 }
1284 }
1285
1286 // Write the symbol table data, if used.
1287 if (NumSymbols) {
1288 // Write the indirect symbol entries.
1289 for (MCAssembler::const_indirect_symbol_iterator
1290 it = Asm.indirect_symbol_begin(),
1291 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1292 // Indirect symbols in the non lazy symbol pointer section have some
1293 // special handling.
1294 const MCSectionMachO &Section =
1295 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1296 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1297 // If this symbol is defined and internal, mark it as such.
1298 if (it->Symbol->isDefined() &&
1299 !Asm.getSymbolData(*it->Symbol).isExternal()) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +00001300 uint32_t Flags = macho::ISF_Local;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001301 if (it->Symbol->isAbsolute())
Daniel Dunbarf52788f2010-11-27 04:59:14 +00001302 Flags |= macho::ISF_Absolute;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001303 Write32(Flags);
1304 continue;
1305 }
1306 }
1307
1308 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1309 }
1310
1311 // FIXME: Check that offsets match computed ones.
1312
1313 // Write the symbol table entries.
1314 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001315 WriteNlist(LocalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001316 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001317 WriteNlist(ExternalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001318 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001319 WriteNlist(UndefinedSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001320
1321 // Write the string table.
1322 OS << StringTable.str();
1323 }
1324 }
1325};
1326
1327}
1328
Daniel Dunbarae5abd52010-12-16 16:09:19 +00001329MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
1330 raw_ostream &OS, bool is64Bit,
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001331 uint32_t CPUType,
1332 uint32_t CPUSubtype,
1333 bool IsLittleEndian) {
Daniel Dunbarae5abd52010-12-16 16:09:19 +00001334 return new MachObjectWriter(MOTW, OS, is64Bit, CPUType, CPUSubtype,
1335 IsLittleEndian);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001336}