blob: 7c6e59175f92df19a7476b8077c9f894b8e3dc1d [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"
Daniel Dunbaraa4b7dd2010-12-16 16:08:33 +000015#include "llvm/MC/MCMachObjectWriter.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000016#include "llvm/MC/MCObjectWriter.h"
17#include "llvm/MC/MCSectionMachO.h"
18#include "llvm/MC/MCSymbol.h"
Kevin Enderbya6eeb6e2010-05-07 21:44:23 +000019#include "llvm/MC/MCMachOSymbolFlags.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000020#include "llvm/MC/MCValue.h"
Daniel Dunbar821ecd72010-11-27 04:19:38 +000021#include "llvm/Object/MachOFormat.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000022#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000023#include "llvm/Target/TargetAsmBackend.h"
24
25// FIXME: Gross.
26#include "../Target/X86/X86FixupKinds.h"
27
28#include <vector>
29using namespace llvm;
Daniel Dunbar821ecd72010-11-27 04:19:38 +000030using namespace llvm::object;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000031
Rafael Espindolaa8c02c32010-09-30 03:11:42 +000032// FIXME: this has been copied from (or to) X86AsmBackend.cpp
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000033static unsigned getFixupKindLog2Size(unsigned Kind) {
34 switch (Kind) {
Jim Grosbachdff84b02010-12-02 00:28:45 +000035 // FIXME: Until ARM has it's own relocation stuff spun off, it comes
36 // through here and we don't want it to puke all over. Any reasonable
37 // values will only come when ARM relocation support gets added, at which
38 // point this will be X86 only again and the llvm_unreachable can be
39 // re-enabled.
40 default: return 0;// llvm_unreachable("invalid fixup kind!");
Rafael Espindolae04ed7e2010-11-28 14:17:56 +000041 case FK_PCRel_1:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000042 case FK_Data_1: return 0;
Rafael Espindolae04ed7e2010-11-28 14:17:56 +000043 case FK_PCRel_2:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000044 case FK_Data_2: return 1;
Rafael Espindolae04ed7e2010-11-28 14:17:56 +000045 case FK_PCRel_4:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000046 case X86::reloc_riprel_4byte:
Daniel Dunbar602b40f2010-03-19 18:07:55 +000047 case X86::reloc_riprel_4byte_movq_load:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +000048 case X86::reloc_signed_4byte:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000049 case FK_Data_4: return 2;
50 case FK_Data_8: return 3;
51 }
52}
53
Daniel Dunbare9460ec2010-05-10 23:15:13 +000054static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
55 // Undefined symbols are always extern.
56 if (SD->Symbol->isUndefined())
57 return true;
58
59 // References to weak definitions require external relocation entries; the
60 // definition may not always be the one in the same object file.
61 if (SD->getFlags() & SF_WeakDefinition)
62 return true;
63
64 // Otherwise, we can use an internal relocation.
65 return false;
66}
67
Rafael Espindola70703872010-09-30 02:22:20 +000068static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
69 const MCValue Target,
70 const MCSymbolData *BaseSymbol) {
71 // The effective fixup address is
72 // addr(atom(A)) + offset(A)
73 // - addr(atom(B)) - offset(B)
74 // - addr(BaseSymbol) + <fixup offset from base symbol>
75 // and the offsets are not relocatable, so the fixup is fully resolved when
76 // addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
77 //
78 // Note that "false" is almost always conservatively correct (it means we emit
79 // a relocation which is unnecessary), except when it would force us to emit a
80 // relocation which the target cannot encode.
81
82 const MCSymbolData *A_Base = 0, *B_Base = 0;
83 if (const MCSymbolRefExpr *A = Target.getSymA()) {
84 // Modified symbol references cannot be resolved.
85 if (A->getKind() != MCSymbolRefExpr::VK_None)
86 return false;
87
88 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
89 if (!A_Base)
90 return false;
91 }
92
93 if (const MCSymbolRefExpr *B = Target.getSymB()) {
94 // Modified symbol references cannot be resolved.
95 if (B->getKind() != MCSymbolRefExpr::VK_None)
96 return false;
97
98 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
99 if (!B_Base)
100 return false;
101 }
102
103 // If there is no base, A and B have to be the same atom for this fixup to be
104 // fully resolved.
105 if (!BaseSymbol)
106 return A_Base == B_Base;
107
108 // Otherwise, B must be missing and A must be the base.
109 return !B_Base && BaseSymbol == A_Base;
110}
111
112static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
113 const MCValue Target,
114 const MCSection *BaseSection) {
115 // The effective fixup address is
116 // addr(atom(A)) + offset(A)
117 // - addr(atom(B)) - offset(B)
118 // - addr(<base symbol>) + <fixup offset from base symbol>
119 // and the offsets are not relocatable, so the fixup is fully resolved when
120 // addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
121 //
122 // The simple (Darwin, except on x86_64) way of dealing with this was to
123 // assume that any reference to a temporary symbol *must* be a temporary
124 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
125 // relocation to a temporary symbol (in the same section) is fully
126 // resolved. This also works in conjunction with absolutized .set, which
127 // requires the compiler to use .set to absolutize the differences between
128 // symbols which the compiler knows to be assembly time constants, so we don't
129 // need to worry about considering symbol differences fully resolved.
130
131 // Non-relative fixups are only resolved if constant.
132 if (!BaseSection)
133 return Target.isAbsolute();
134
135 // Otherwise, relative fixups are only resolved if not a difference and the
136 // target is a temporary in the same section.
137 if (Target.isAbsolute() || Target.getSymB())
138 return false;
139
140 const MCSymbol *A = &Target.getSymA()->getSymbol();
141 if (!A->isTemporary() || !A->isInSection() ||
142 &A->getSection() != BaseSection)
143 return false;
144
145 return true;
146}
147
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000148namespace {
149
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000150class MachObjectWriter : public MCObjectWriter {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000151 /// MachSymbolData - Helper struct for containing some precomputed information
152 /// on symbols.
153 struct MachSymbolData {
154 MCSymbolData *SymbolData;
155 uint64_t StringIndex;
156 uint8_t SectionIndex;
157
158 // Support lexicographic sorting.
159 bool operator<(const MachSymbolData &RHS) const {
Benjamin Kramerc37791e2010-05-20 14:14:22 +0000160 return SymbolData->getSymbol().getName() <
161 RHS.SymbolData->getSymbol().getName();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000162 }
163 };
164
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000165 /// @name Utility Methods
166 /// @{
167
168 bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
169 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
170 (MCFixupKind) Kind);
171
172 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
173 }
174
175 /// @}
176
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000177 /// @name Relocation Data
178 /// @{
179
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000180 llvm::DenseMap<const MCSectionData*,
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000181 std::vector<macho::RelocationEntry> > Relocations;
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000182 llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000183
184 /// @}
185 /// @name Symbol Table Data
186 /// @{
187
188 SmallString<256> StringTable;
189 std::vector<MachSymbolData> LocalSymbolData;
190 std::vector<MachSymbolData> ExternalSymbolData;
191 std::vector<MachSymbolData> UndefinedSymbolData;
192
193 /// @}
194
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000195 SectionAddrMap SectionAddress;
196 uint64_t getSectionAddress(const MCSectionData* SD) const {
197 return SectionAddress.lookup(SD);
198 }
199 uint64_t getSymbolAddress(const MCSymbolData* SD,
200 const MCAsmLayout &Layout) const {
201 return getSectionAddress(SD->getFragment()->getParent()) +
202 Layout.getSymbolOffset(SD);
203 }
204 uint64_t getFragmentAddress(const MCFragment *Fragment,
205 const MCAsmLayout &Layout) const {
206 return getSectionAddress(Fragment->getParent()) +
207 Layout.getFragmentOffset(Fragment);
208 }
209
210 uint64_t getPaddingSize(const MCSectionData *SD,
211 const MCAsmLayout &Layout) const {
212 uint64_t EndAddr = getSectionAddress(SD) + Layout.getSectionAddressSize(SD);
213 unsigned Next = SD->getLayoutOrder() + 1;
214 if (Next >= Layout.getSectionOrder().size())
215 return 0;
216
217 const MCSectionData &NextSD = *Layout.getSectionOrder()[Next];
218 if (NextSD.getSection().isVirtualSection())
219 return 0;
220 return OffsetToAlignment(EndAddr, NextSD.getAlignment());
221 }
222
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000223 unsigned Is64Bit : 1;
224
Jim Grosbachc9d14392010-11-05 18:48:58 +0000225 uint32_t CPUType;
226 uint32_t CPUSubtype;
227
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000228public:
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000229 MachObjectWriter(raw_ostream &_OS,
230 bool _Is64Bit, uint32_t _CPUType, uint32_t _CPUSubtype,
231 bool _IsLittleEndian)
232 : MCObjectWriter(_OS, _IsLittleEndian),
233 Is64Bit(_Is64Bit), CPUType(_CPUType), CPUSubtype(_CPUSubtype) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000234 }
235
236 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
237 bool SubsectionsViaSymbols) {
238 uint32_t Flags = 0;
239
240 if (SubsectionsViaSymbols)
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000241 Flags |= macho::HF_SubsectionsViaSymbols;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000242
243 // struct mach_header (28 bytes) or
244 // struct mach_header_64 (32 bytes)
245
246 uint64_t Start = OS.tell();
247 (void) Start;
248
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000249 Write32(Is64Bit ? macho::HM_Object64 : macho::HM_Object32);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000250
Jim Grosbachc9d14392010-11-05 18:48:58 +0000251 Write32(CPUType);
252 Write32(CPUSubtype);
253
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000254 Write32(macho::HFT_Object);
Daniel Dunbar590956f2010-11-27 07:39:37 +0000255 Write32(NumLoadCommands);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000256 Write32(LoadCommandsSize);
257 Write32(Flags);
258 if (Is64Bit)
259 Write32(0); // reserved
260
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000261 assert(OS.tell() - Start == Is64Bit ?
262 macho::Header64Size : macho::Header32Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000263 }
264
265 /// WriteSegmentLoadCommand - Write a segment load command.
266 ///
267 /// \arg NumSections - The number of sections in this segment.
268 /// \arg SectionDataSize - The total size of the sections.
269 void WriteSegmentLoadCommand(unsigned NumSections,
270 uint64_t VMSize,
271 uint64_t SectionDataStartOffset,
272 uint64_t SectionDataSize) {
273 // struct segment_command (56 bytes) or
274 // struct segment_command_64 (72 bytes)
275
276 uint64_t Start = OS.tell();
277 (void) Start;
278
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000279 unsigned SegmentLoadCommandSize = Is64Bit ? macho::SegmentLoadCommand64Size:
280 macho::SegmentLoadCommand32Size;
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000281 Write32(Is64Bit ? macho::LCT_Segment64 : macho::LCT_Segment);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000282 Write32(SegmentLoadCommandSize +
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000283 NumSections * (Is64Bit ? macho::Section64Size :
284 macho::Section32Size));
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000285
286 WriteBytes("", 16);
287 if (Is64Bit) {
288 Write64(0); // vmaddr
289 Write64(VMSize); // vmsize
290 Write64(SectionDataStartOffset); // file offset
291 Write64(SectionDataSize); // file size
292 } else {
293 Write32(0); // vmaddr
294 Write32(VMSize); // vmsize
295 Write32(SectionDataStartOffset); // file offset
296 Write32(SectionDataSize); // file size
297 }
298 Write32(0x7); // maxprot
299 Write32(0x7); // initprot
300 Write32(NumSections);
301 Write32(0); // flags
302
303 assert(OS.tell() - Start == SegmentLoadCommandSize);
304 }
305
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000306 void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
307 const MCSectionData &SD, uint64_t FileOffset,
308 uint64_t RelocationsStart, unsigned NumRelocations) {
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000309 uint64_t SectionSize = Layout.getSectionAddressSize(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +0000310
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000311 // The offset is unused for virtual sections.
Rafael Espindolaf2dc4aa2010-11-17 20:03:54 +0000312 if (SD.getSection().isVirtualSection()) {
Daniel Dunbarb026d642010-03-25 07:10:05 +0000313 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000314 FileOffset = 0;
315 }
316
317 // struct section (68 bytes) or
318 // struct section_64 (80 bytes)
319
320 uint64_t Start = OS.tell();
321 (void) Start;
322
Daniel Dunbar56279f42010-05-18 17:28:20 +0000323 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000324 WriteBytes(Section.getSectionName(), 16);
325 WriteBytes(Section.getSegmentName(), 16);
326 if (Is64Bit) {
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000327 Write64(getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000328 Write64(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000329 } else {
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000330 Write32(getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000331 Write32(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000332 }
333 Write32(FileOffset);
334
335 unsigned Flags = Section.getTypeAndAttributes();
336 if (SD.hasInstructions())
337 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
338
339 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
340 Write32(Log2_32(SD.getAlignment()));
341 Write32(NumRelocations ? RelocationsStart : 0);
342 Write32(NumRelocations);
343 Write32(Flags);
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000344 Write32(IndirectSymBase.lookup(&SD)); // reserved1
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000345 Write32(Section.getStubSize()); // reserved2
346 if (Is64Bit)
347 Write32(0); // reserved3
348
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000349 assert(OS.tell() - Start == Is64Bit ? macho::Section64Size :
350 macho::Section32Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000351 }
352
353 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
354 uint32_t StringTableOffset,
355 uint32_t StringTableSize) {
356 // struct symtab_command (24 bytes)
357
358 uint64_t Start = OS.tell();
359 (void) Start;
360
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000361 Write32(macho::LCT_Symtab);
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000362 Write32(macho::SymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000363 Write32(SymbolOffset);
364 Write32(NumSymbols);
365 Write32(StringTableOffset);
366 Write32(StringTableSize);
367
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000368 assert(OS.tell() - Start == macho::SymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000369 }
370
371 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
372 uint32_t NumLocalSymbols,
373 uint32_t FirstExternalSymbol,
374 uint32_t NumExternalSymbols,
375 uint32_t FirstUndefinedSymbol,
376 uint32_t NumUndefinedSymbols,
377 uint32_t IndirectSymbolOffset,
378 uint32_t NumIndirectSymbols) {
379 // struct dysymtab_command (80 bytes)
380
381 uint64_t Start = OS.tell();
382 (void) Start;
383
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000384 Write32(macho::LCT_Dysymtab);
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000385 Write32(macho::DysymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000386 Write32(FirstLocalSymbol);
387 Write32(NumLocalSymbols);
388 Write32(FirstExternalSymbol);
389 Write32(NumExternalSymbols);
390 Write32(FirstUndefinedSymbol);
391 Write32(NumUndefinedSymbols);
392 Write32(0); // tocoff
393 Write32(0); // ntoc
394 Write32(0); // modtaboff
395 Write32(0); // nmodtab
396 Write32(0); // extrefsymoff
397 Write32(0); // nextrefsyms
398 Write32(IndirectSymbolOffset);
399 Write32(NumIndirectSymbols);
400 Write32(0); // extreloff
401 Write32(0); // nextrel
402 Write32(0); // locreloff
403 Write32(0); // nlocrel
404
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000405 assert(OS.tell() - Start == macho::DysymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000406 }
407
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000408 void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000409 MCSymbolData &Data = *MSD.SymbolData;
410 const MCSymbol &Symbol = Data.getSymbol();
411 uint8_t Type = 0;
412 uint16_t Flags = Data.getFlags();
413 uint32_t Address = 0;
414
415 // Set the N_TYPE bits. See <mach-o/nlist.h>.
416 //
417 // FIXME: Are the prebound or indirect fields possible here?
418 if (Symbol.isUndefined())
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000419 Type = macho::STT_Undefined;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000420 else if (Symbol.isAbsolute())
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000421 Type = macho::STT_Absolute;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000422 else
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000423 Type = macho::STT_Section;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000424
425 // FIXME: Set STAB bits.
426
427 if (Data.isPrivateExtern())
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000428 Type |= macho::STF_PrivateExtern;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000429
430 // Set external bit.
431 if (Data.isExternal() || Symbol.isUndefined())
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000432 Type |= macho::STF_External;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000433
434 // Compute the symbol address.
435 if (Symbol.isDefined()) {
436 if (Symbol.isAbsolute()) {
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000437 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000438 } else {
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000439 Address = getSymbolAddress(&Data, Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000440 }
441 } else if (Data.isCommon()) {
442 // Common symbols are encoded with the size in the address
443 // field, and their alignment in the flags.
444 Address = Data.getCommonSize();
445
446 // Common alignment is packed into the 'desc' bits.
447 if (unsigned Align = Data.getCommonAlignment()) {
448 unsigned Log2Size = Log2_32(Align);
449 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
450 if (Log2Size > 15)
Chris Lattner75361b62010-04-07 22:58:41 +0000451 report_fatal_error("invalid 'common' alignment '" +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000452 Twine(Align) + "'");
453 // FIXME: Keep this mask with the SymbolFlags enumeration.
454 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
455 }
456 }
457
458 // struct nlist (12 bytes)
459
460 Write32(MSD.StringIndex);
461 Write8(Type);
462 Write8(MSD.SectionIndex);
463
464 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
465 // value.
466 Write16(Flags);
467 if (Is64Bit)
468 Write64(Address);
469 else
470 Write32(Address);
471 }
472
Daniel Dunbar35b06572010-03-22 23:16:43 +0000473 // FIXME: We really need to improve the relocation validation. Basically, we
474 // want to implement a separate computation which evaluates the relocation
475 // entry as the linker would, and verifies that the resultant fixup value is
476 // exactly what the encoder wanted. This will catch several classes of
477 // problems:
478 //
479 // - Relocation entry bugs, the two algorithms are unlikely to have the same
480 // exact bug.
481 //
482 // - Relaxation issues, where we forget to relax something.
483 //
484 // - Input errors, where something cannot be correctly encoded. 'as' allows
485 // these through in many cases.
486
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000487 static bool isFixupKindRIPRel(unsigned Kind) {
488 return Kind == X86::reloc_riprel_4byte ||
489 Kind == X86::reloc_riprel_4byte_movq_load;
490 }
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000491 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000492 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000493 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000494 uint64_t &FixedValue) {
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000495 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Daniel Dunbar482ad802010-05-26 15:18:31 +0000496 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
497 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000498
499 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000500 uint32_t FixupOffset =
501 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
502 uint32_t FixupAddress =
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000503 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000504 int64_t Value = 0;
505 unsigned Index = 0;
506 unsigned IsExtern = 0;
507 unsigned Type = 0;
508
509 Value = Target.getConstant();
510
511 if (IsPCRel) {
512 // Compensate for the relocation offset, Darwin x86_64 relocations only
513 // have the addend and appear to have attempted to define it to be the
514 // actual expression addend without the PCrel bias. However, instructions
515 // with data following the relocation are not accomodated for (see comment
516 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
Benjamin Kramer454c4ce2010-04-08 15:25:57 +0000517 Value += 1LL << Log2Size;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000518 }
519
520 if (Target.isAbsolute()) { // constant
521 // SymbolNum of 0 indicates the absolute section.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000522 Type = macho::RIT_X86_64_Unsigned;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000523 Index = 0;
524
525 // FIXME: I believe this is broken, I don't think the linker can
526 // understand it. I think it would require a local relocation, but I'm not
527 // sure if that would work either. The official way to get an absolute
528 // PCrel relocation is to use an absolute symbol (which we don't support
529 // yet).
530 if (IsPCRel) {
531 IsExtern = 1;
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000532 Type = macho::RIT_X86_64_Branch;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000533 }
534 } else if (Target.getSymB()) { // A - B + constant
535 const MCSymbol *A = &Target.getSymA()->getSymbol();
536 MCSymbolData &A_SD = Asm.getSymbolData(*A);
Rafael Espindolab8141102010-09-27 18:13:03 +0000537 const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000538
539 const MCSymbol *B = &Target.getSymB()->getSymbol();
540 MCSymbolData &B_SD = Asm.getSymbolData(*B);
Rafael Espindolab8141102010-09-27 18:13:03 +0000541 const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000542
543 // Neither symbol can be modified.
544 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
545 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000546 report_fatal_error("unsupported relocation of modified symbol");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000547
548 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
549 // implement most of these correctly.
550 if (IsPCRel)
Chris Lattner75361b62010-04-07 22:58:41 +0000551 report_fatal_error("unsupported pc-relative relocation of difference");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000552
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000553 // The support for the situation where one or both of the symbols would
554 // require a local relocation is handled just like if the symbols were
555 // external. This is certainly used in the case of debug sections where
556 // the section has only temporary symbols and thus the symbols don't have
557 // base symbols. This is encoded using the section ordinal and
558 // non-extern relocation entries.
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000559
560 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000561 // a single SIGNED relocation); reject it for now. Except the case where
562 // both symbols don't have a base, equal but both NULL.
563 if (A_Base == B_Base && A_Base)
Chris Lattner75361b62010-04-07 22:58:41 +0000564 report_fatal_error("unsupported relocation with identical base");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000565
Rafael Espindolaf10d2be2010-12-07 01:09:54 +0000566 Value += getSymbolAddress(&A_SD, Layout) -
567 (A_Base == NULL ? 0 : getSymbolAddress(A_Base, Layout));
568 Value -= getSymbolAddress(&B_SD, Layout) -
569 (B_Base == NULL ? 0 : getSymbolAddress(B_Base, Layout));
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000570
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000571 if (A_Base) {
572 Index = A_Base->getIndex();
573 IsExtern = 1;
574 }
575 else {
576 Index = A_SD.getFragment()->getParent()->getOrdinal() + 1;
577 IsExtern = 0;
578 }
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000579 Type = macho::RIT_X86_64_Unsigned;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000580
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000581 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000582 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000583 MRE.Word1 = ((Index << 0) |
584 (IsPCRel << 24) |
585 (Log2Size << 25) |
586 (IsExtern << 27) |
587 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000588 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000589
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000590 if (B_Base) {
591 Index = B_Base->getIndex();
592 IsExtern = 1;
593 }
594 else {
595 Index = B_SD.getFragment()->getParent()->getOrdinal() + 1;
596 IsExtern = 0;
597 }
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000598 Type = macho::RIT_X86_64_Subtractor;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000599 } else {
600 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
601 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
Rafael Espindolab8141102010-09-27 18:13:03 +0000602 const MCSymbolData *Base = Asm.getAtom(&SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000603
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000604 // Relocations inside debug sections always use local relocations when
605 // possible. This seems to be done because the debugger doesn't fully
606 // understand x86_64 relocation entries, and expects to find values that
607 // have already been fixed up.
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000608 if (Symbol->isInSection()) {
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000609 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
610 Fragment->getParent()->getSection());
611 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
612 Base = 0;
613 }
614
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000615 // x86_64 almost always uses external relocations, except when there is no
616 // symbol to use as a base address (a local symbol with no preceeding
617 // non-local symbol).
618 if (Base) {
619 Index = Base->getIndex();
620 IsExtern = 1;
621
622 // Add the local offset, if needed.
623 if (Base != &SD)
Rafael Espindola1dda29b2010-12-06 21:51:55 +0000624 Value += Layout.getSymbolOffset(&SD) - Layout.getSymbolOffset(Base);
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000625 } else if (Symbol->isInSection()) {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000626 // The index is the section ordinal (1-based).
627 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000628 IsExtern = 0;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000629 Value += getSymbolAddress(&SD, Layout);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000630
631 if (IsPCRel)
Daniel Dunbardb4c7e62010-05-11 23:53:11 +0000632 Value -= FixupAddress + (1 << Log2Size);
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000633 } else if (Symbol->isVariable()) {
634 const MCExpr *Value = Symbol->getVariableValue();
635 int64_t Res;
636 bool isAbs = Value->EvaluateAsAbsolute(Res, Layout, SectionAddress);
637 if (isAbs) {
638 FixedValue = Res;
639 return;
640 } else {
641 report_fatal_error("unsupported relocation of variable '" +
642 Symbol->getName() + "'");
643 }
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000644 } else {
645 report_fatal_error("unsupported relocation of undefined symbol '" +
646 Symbol->getName() + "'");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000647 }
648
649 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
650 if (IsPCRel) {
651 if (IsRIPRel) {
652 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
653 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
654 // rewrite the movq to an leaq at link time if the symbol ends up in
655 // the same linkage unit.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000656 if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000657 Type = macho::RIT_X86_64_GOTLoad;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000658 else
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000659 Type = macho::RIT_X86_64_GOT;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000660 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000661 Type = macho::RIT_X86_64_TLV;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000662 } else if (Modifier != MCSymbolRefExpr::VK_None) {
663 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000664 } else {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000665 Type = macho::RIT_X86_64_Signed;
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000666
667 // The Darwin x86_64 relocation format has a problem where it cannot
668 // encode an address (L<foo> + <constant>) which is outside the atom
669 // containing L<foo>. Generally, this shouldn't occur but it does
670 // happen when we have a RIPrel instruction with data following the
671 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
672 // adjustment Darwin x86_64 uses, the offset is still negative and
673 // the linker has no way to recognize this.
674 //
675 // To work around this, Darwin uses several special relocation types
676 // to indicate the offsets. However, the specification or
677 // implementation of these seems to also be incomplete; they should
678 // adjust the addend as well based on the actual encoded instruction
679 // (the additional bias), but instead appear to just look at the
680 // final offset.
681 switch (-(Target.getConstant() + (1LL << Log2Size))) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000682 case 1: Type = macho::RIT_X86_64_Signed1; break;
683 case 2: Type = macho::RIT_X86_64_Signed2; break;
684 case 4: Type = macho::RIT_X86_64_Signed4; break;
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000685 }
686 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000687 } else {
688 if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000689 report_fatal_error("unsupported symbol modifier in branch "
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000690 "relocation");
691
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000692 Type = macho::RIT_X86_64_Branch;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000693 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000694 } else {
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000695 if (Modifier == MCSymbolRefExpr::VK_GOT) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000696 Type = macho::RIT_X86_64_GOT;
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000697 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
698 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
699 // which case all we do is set the PCrel bit in the relocation entry;
700 // this is used with exception handling, for example. The source is
701 // required to include any necessary offset directly.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000702 Type = macho::RIT_X86_64_GOT;
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000703 IsPCRel = 1;
Eric Christopher96ac5152010-05-26 00:02:12 +0000704 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
705 report_fatal_error("TLVP symbol modifier should have been rip-rel");
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000706 } else if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000707 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000708 else
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000709 Type = macho::RIT_X86_64_Unsigned;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000710 }
711 }
712
713 // x86_64 always writes custom values into the fixups.
714 FixedValue = Value;
715
716 // struct relocation_info (8 bytes)
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000717 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000718 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000719 MRE.Word1 = ((Index << 0) |
720 (IsPCRel << 24) |
721 (Log2Size << 25) |
722 (IsExtern << 27) |
723 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000724 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000725 }
726
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000727 void RecordScatteredRelocation(const MCAssembler &Asm,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000728 const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000729 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000730 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000731 uint64_t &FixedValue) {
Daniel Dunbar482ad802010-05-26 15:18:31 +0000732 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000733 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Daniel Dunbar482ad802010-05-26 15:18:31 +0000734 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000735 unsigned Type = macho::RIT_Vanilla;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000736
737 // See <reloc.h>.
738 const MCSymbol *A = &Target.getSymA()->getSymbol();
739 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
740
741 if (!A_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000742 report_fatal_error("symbol '" + A->getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000743 "' can not be undefined in a subtraction expression");
744
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000745 uint32_t Value = getSymbolAddress(A_SD, Layout);
746 uint64_t SecAddr = getSectionAddress(A_SD->getFragment()->getParent());
747 FixedValue += SecAddr;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000748 uint32_t Value2 = 0;
749
750 if (const MCSymbolRefExpr *B = Target.getSymB()) {
751 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
752
753 if (!B_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000754 report_fatal_error("symbol '" + B->getSymbol().getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000755 "' can not be undefined in a subtraction expression");
756
757 // Select the appropriate difference relocation type.
758 //
759 // Note that there is no longer any semantic difference between these two
760 // relocation types from the linkers point of view, this is done solely
761 // for pedantic compatibility with 'as'.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000762 Type = A_SD->isExternal() ? macho::RIT_Difference :
763 macho::RIT_LocalDifference;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000764 Value2 = getSymbolAddress(B_SD, Layout);
765 FixedValue -= getSectionAddress(B_SD->getFragment()->getParent());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000766 }
767
768 // Relocations are written out in reverse order, so the PAIR comes first.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000769 if (Type == macho::RIT_Difference || Type == macho::RIT_LocalDifference) {
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000770 macho::RelocationEntry MRE;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000771 MRE.Word0 = ((0 << 0) |
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000772 (macho::RIT_Pair << 24) |
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000773 (Log2Size << 28) |
774 (IsPCRel << 30) |
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000775 macho::RF_Scattered);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000776 MRE.Word1 = Value2;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000777 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000778 }
779
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000780 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000781 MRE.Word0 = ((FixupOffset << 0) |
782 (Type << 24) |
783 (Log2Size << 28) |
784 (IsPCRel << 30) |
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000785 macho::RF_Scattered);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000786 MRE.Word1 = Value;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000787 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000788 }
789
Eric Christopherc9ada472010-06-15 22:59:05 +0000790 void RecordTLVPRelocation(const MCAssembler &Asm,
Eric Christophere48dbf82010-06-16 00:26:36 +0000791 const MCAsmLayout &Layout,
792 const MCFragment *Fragment,
793 const MCFixup &Fixup, MCValue Target,
794 uint64_t &FixedValue) {
Eric Christopherc9ada472010-06-15 22:59:05 +0000795 assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
796 !Is64Bit &&
797 "Should only be called with a 32-bit TLVP relocation!");
798
Eric Christopherc9ada472010-06-15 22:59:05 +0000799 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
800 uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
801 unsigned IsPCRel = 0;
802
803 // Get the symbol data.
804 MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
805 unsigned Index = SD_A->getIndex();
806
Eric Christopherbc067372010-06-16 21:32:38 +0000807 // We're only going to have a second symbol in pic mode and it'll be a
808 // subtraction from the picbase. For 32-bit pic the addend is the difference
Eric Christopher04b8d3c2010-06-17 00:49:46 +0000809 // between the picbase and the next address. For 32-bit static the addend
810 // is zero.
Eric Christopherbc067372010-06-16 21:32:38 +0000811 if (Target.getSymB()) {
Eric Christopher1008d352010-06-22 23:51:47 +0000812 // If this is a subtraction then we're pcrel.
813 uint32_t FixupAddress =
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000814 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
Eric Christopher1008d352010-06-22 23:51:47 +0000815 MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
Eric Christopherc9ada472010-06-15 22:59:05 +0000816 IsPCRel = 1;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000817 FixedValue = (FixupAddress - getSymbolAddress(SD_B, Layout) +
Eric Christopher1008d352010-06-22 23:51:47 +0000818 Target.getConstant());
Chris Lattnerabf8f9c2010-08-16 16:35:20 +0000819 FixedValue += 1ULL << Log2Size;
Eric Christopherbc067372010-06-16 21:32:38 +0000820 } else {
821 FixedValue = 0;
822 }
Jim Grosbach3c384922010-11-11 20:16:23 +0000823
Eric Christopherc9ada472010-06-15 22:59:05 +0000824 // struct relocation_info (8 bytes)
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000825 macho::RelocationEntry MRE;
Eric Christopherc9ada472010-06-15 22:59:05 +0000826 MRE.Word0 = Value;
827 MRE.Word1 = ((Index << 0) |
828 (IsPCRel << 24) |
829 (Log2Size << 25) |
830 (1 << 27) | // Extern
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000831 (macho::RIT_TLV << 28)); // Type
Eric Christopherc9ada472010-06-15 22:59:05 +0000832 Relocations[Fragment->getParent()].push_back(MRE);
833 }
Jim Grosbach3c384922010-11-11 20:16:23 +0000834
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000835 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000836 const MCFragment *Fragment, const MCFixup &Fixup,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000837 MCValue Target, uint64_t &FixedValue) {
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000838 if (Is64Bit) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000839 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000840 return;
841 }
842
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000843 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Daniel Dunbar482ad802010-05-26 15:18:31 +0000844 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000845
Eric Christopherc9ada472010-06-15 22:59:05 +0000846 // If this is a 32-bit TLVP reloc it's handled a bit differently.
Daniel Dunbar23bea412010-09-17 15:21:50 +0000847 if (Target.getSymA() &&
848 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
Eric Christopherc9ada472010-06-15 22:59:05 +0000849 RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
850 return;
851 }
Jim Grosbach3c384922010-11-11 20:16:23 +0000852
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000853 // If this is a difference or a defined symbol plus an offset, then we need
854 // a scattered relocation entry.
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000855 // Differences always require scattered relocations.
856 if (Target.getSymB())
857 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
858 Target, FixedValue);
859
860 // Get the symbol data, if any.
861 MCSymbolData *SD = 0;
862 if (Target.getSymA())
863 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
864
865 // If this is an internal relocation with an offset, it also needs a
866 // scattered relocation entry.
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000867 uint32_t Offset = Target.getConstant();
868 if (IsPCRel)
869 Offset += 1 << Log2Size;
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000870 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
871 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
872 Target, FixedValue);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000873
874 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000875 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000876 unsigned Index = 0;
877 unsigned IsExtern = 0;
878 unsigned Type = 0;
879
880 if (Target.isAbsolute()) { // constant
881 // SymbolNum of 0 indicates the absolute section.
882 //
883 // FIXME: Currently, these are never generated (see code below). I cannot
884 // find a case where they are actually emitted.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000885 Type = macho::RIT_Vanilla;
Rafael Espindola545b77e2010-12-07 17:12:32 +0000886 } else if (SD->getSymbol().isVariable()) {
887 const MCExpr *Value = SD->getSymbol().getVariableValue();
888 int64_t Res;
889 bool isAbs = Value->EvaluateAsAbsolute(Res, Layout, SectionAddress);
890 if (isAbs) {
891 FixedValue = Res;
892 return;
893 } else {
894 report_fatal_error("unsupported relocation of variable '" +
895 SD->getSymbol().getName() + "'");
896 }
Michael J. Spencerb0f3b3e2010-08-10 16:00:49 +0000897 } else {
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000898 // Check whether we need an external or internal relocation.
899 if (doesSymbolRequireExternRelocation(SD)) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000900 IsExtern = 1;
901 Index = SD->getIndex();
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000902 // For external relocations, make sure to offset the fixup value to
903 // compensate for the addend of the symbol address, if it was
904 // undefined. This occurs with weak definitions, for example.
905 if (!SD->Symbol->isUndefined())
Rafael Espindola3b3148f2010-12-07 05:57:28 +0000906 FixedValue -= Layout.getSymbolOffset(SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000907 } else {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000908 // The index is the section ordinal (1-based).
909 Index = SD->getFragment()->getParent()->getOrdinal() + 1;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000910 FixedValue += getSectionAddress(SD->getFragment()->getParent());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000911 }
Rafael Espindolabf60dad2010-12-07 03:50:14 +0000912 if (IsPCRel)
913 FixedValue -= getSectionAddress(Fragment->getParent());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000914
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000915 Type = macho::RIT_Vanilla;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000916 }
917
918 // struct relocation_info (8 bytes)
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000919 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000920 MRE.Word0 = FixupOffset;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000921 MRE.Word1 = ((Index << 0) |
922 (IsPCRel << 24) |
923 (Log2Size << 25) |
924 (IsExtern << 27) |
925 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000926 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000927 }
928
929 void BindIndirectSymbols(MCAssembler &Asm) {
930 // This is the point where 'as' creates actual symbols for indirect symbols
931 // (in the following two passes). It would be easier for us to do this
932 // sooner when we see the attribute, but that makes getting the order in the
933 // symbol table much more complicated than it is worth.
934 //
935 // FIXME: Revisit this when the dust settles.
936
937 // Bind non lazy symbol pointers first.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000938 unsigned IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000939 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000940 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000941 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +0000942 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000943
944 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
945 continue;
946
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000947 // Initialize the section indirect symbol base, if necessary.
948 if (!IndirectSymBase.count(it->SectionData))
949 IndirectSymBase[it->SectionData] = IndirectIndex;
Jim Grosbach3c384922010-11-11 20:16:23 +0000950
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000951 Asm.getOrCreateSymbolData(*it->Symbol);
952 }
953
954 // Then lazy symbol pointers and symbol stubs.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000955 IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000956 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000957 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000958 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +0000959 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000960
961 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
962 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
963 continue;
964
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000965 // Initialize the section indirect symbol base, if necessary.
966 if (!IndirectSymBase.count(it->SectionData))
967 IndirectSymBase[it->SectionData] = IndirectIndex;
968
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000969 // Set the symbol type to undefined lazy, but only on construction.
970 //
971 // FIXME: Do not hardcode.
972 bool Created;
973 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
974 if (Created)
975 Entry.setFlags(Entry.getFlags() | 0x0001);
976 }
977 }
978
979 /// ComputeSymbolTable - Compute the symbol table data
980 ///
981 /// \param StringTable [out] - The string table data.
982 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
983 /// string table.
984 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
985 std::vector<MachSymbolData> &LocalSymbolData,
986 std::vector<MachSymbolData> &ExternalSymbolData,
987 std::vector<MachSymbolData> &UndefinedSymbolData) {
988 // Build section lookup table.
989 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
990 unsigned Index = 1;
991 for (MCAssembler::iterator it = Asm.begin(),
992 ie = Asm.end(); it != ie; ++it, ++Index)
993 SectionIndexMap[&it->getSection()] = Index;
994 assert(Index <= 256 && "Too many sections!");
995
996 // Index 0 is always the empty string.
997 StringMap<uint64_t> StringIndexMap;
998 StringTable += '\x00';
999
1000 // Build the symbol arrays and the string table, but only for non-local
1001 // symbols.
1002 //
1003 // The particular order that we collect the symbols and create the string
1004 // table, then sort the symbols is chosen to match 'as'. Even though it
1005 // doesn't matter for correctness, this is important for letting us diff .o
1006 // files.
1007 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1008 ie = Asm.symbol_end(); it != ie; ++it) {
1009 const MCSymbol &Symbol = it->getSymbol();
1010
1011 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +00001012 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001013 continue;
1014
1015 if (!it->isExternal() && !Symbol.isUndefined())
1016 continue;
1017
1018 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1019 if (!Entry) {
1020 Entry = StringTable.size();
1021 StringTable += Symbol.getName();
1022 StringTable += '\x00';
1023 }
1024
1025 MachSymbolData MSD;
1026 MSD.SymbolData = it;
1027 MSD.StringIndex = Entry;
1028
1029 if (Symbol.isUndefined()) {
1030 MSD.SectionIndex = 0;
1031 UndefinedSymbolData.push_back(MSD);
1032 } else if (Symbol.isAbsolute()) {
1033 MSD.SectionIndex = 0;
1034 ExternalSymbolData.push_back(MSD);
1035 } else {
1036 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1037 assert(MSD.SectionIndex && "Invalid section index!");
1038 ExternalSymbolData.push_back(MSD);
1039 }
1040 }
1041
1042 // Now add the data for local symbols.
1043 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1044 ie = Asm.symbol_end(); it != ie; ++it) {
1045 const MCSymbol &Symbol = it->getSymbol();
1046
1047 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +00001048 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001049 continue;
1050
1051 if (it->isExternal() || Symbol.isUndefined())
1052 continue;
1053
1054 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1055 if (!Entry) {
1056 Entry = StringTable.size();
1057 StringTable += Symbol.getName();
1058 StringTable += '\x00';
1059 }
1060
1061 MachSymbolData MSD;
1062 MSD.SymbolData = it;
1063 MSD.StringIndex = Entry;
1064
1065 if (Symbol.isAbsolute()) {
1066 MSD.SectionIndex = 0;
1067 LocalSymbolData.push_back(MSD);
1068 } else {
1069 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1070 assert(MSD.SectionIndex && "Invalid section index!");
1071 LocalSymbolData.push_back(MSD);
1072 }
1073 }
1074
1075 // External and undefined symbols are required to be in lexicographic order.
1076 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1077 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1078
1079 // Set the symbol indices.
1080 Index = 0;
1081 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1082 LocalSymbolData[i].SymbolData->setIndex(Index++);
1083 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1084 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1085 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1086 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1087
1088 // The string table is padded to a multiple of 4.
1089 while (StringTable.size() % 4)
1090 StringTable += '\x00';
1091 }
1092
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001093 void computeSectionAddresses(const MCAssembler &Asm,
1094 const MCAsmLayout &Layout) {
1095 uint64_t StartAddress = 0;
1096 const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
1097 for (int i = 0, n = Order.size(); i != n ; ++i) {
1098 const MCSectionData *SD = Order[i];
1099 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
1100 SectionAddress[SD] = StartAddress;
1101 StartAddress += Layout.getSectionAddressSize(SD);
1102 // Explicitly pad the section to match the alignment requirements of the
1103 // following one. This is for 'gas' compatibility, it shouldn't
1104 /// strictly be necessary.
1105 StartAddress += getPaddingSize(SD, Layout);
1106 }
1107 }
1108
1109 void ExecutePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout) {
1110 computeSectionAddresses(Asm, Layout);
1111
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001112 // Create symbol data for any indirect symbols.
1113 BindIndirectSymbols(Asm);
1114
1115 // Compute symbol table information and bind symbol indices.
1116 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1117 UndefinedSymbolData);
1118 }
1119
Rafael Espindola70703872010-09-30 02:22:20 +00001120
1121 bool IsFixupFullyResolved(const MCAssembler &Asm,
1122 const MCValue Target,
1123 bool IsPCRel,
1124 const MCFragment *DF) const {
Daniel Dunbar7976b882010-11-27 05:18:48 +00001125 // If we aren't using scattered symbols, the fixup is fully resolved.
1126 if (!Asm.getBackend().hasScatteredSymbols())
1127 return true;
Rafael Espindola70703872010-09-30 02:22:20 +00001128
Daniel Dunbar7976b882010-11-27 05:18:48 +00001129 // Otherwise, determine whether this value is actually resolved; scattering
1130 // may cause atoms to move.
Rafael Espindola70703872010-09-30 02:22:20 +00001131
Daniel Dunbar7976b882010-11-27 05:18:48 +00001132 // Check if we are using the "simple" resolution algorithm (e.g.,
1133 // i386).
1134 if (!Asm.getBackend().hasReliableSymbolDifference()) {
1135 const MCSection *BaseSection = 0;
1136 if (IsPCRel)
1137 BaseSection = &DF->getParent()->getSection();
1138
1139 return isScatteredFixupFullyResolvedSimple(Asm, Target, BaseSection);
Rafael Espindola70703872010-09-30 02:22:20 +00001140 }
Daniel Dunbar7976b882010-11-27 05:18:48 +00001141
1142 // Otherwise, compute the proper answer as reliably as possible.
1143
1144 // If this is a PCrel relocation, find the base atom (identified by its
1145 // symbol) that the fixup value is relative to.
1146 const MCSymbolData *BaseSymbol = 0;
1147 if (IsPCRel) {
1148 BaseSymbol = DF->getAtom();
1149 if (!BaseSymbol)
1150 return false;
1151 }
1152
1153 return isScatteredFixupFullyResolved(Asm, Target, BaseSymbol);
Rafael Espindola70703872010-09-30 02:22:20 +00001154 }
1155
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001156 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001157 unsigned NumSections = Asm.size();
1158
1159 // The section data starts after the header, the segment load command (and
1160 // section headers) and the symbol table.
1161 unsigned NumLoadCommands = 1;
1162 uint64_t LoadCommandsSize = Is64Bit ?
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001163 macho::SegmentLoadCommand64Size + NumSections * macho::Section64Size :
1164 macho::SegmentLoadCommand32Size + NumSections * macho::Section32Size;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001165
1166 // Add the symbol table load command sizes, if used.
1167 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1168 UndefinedSymbolData.size();
1169 if (NumSymbols) {
1170 NumLoadCommands += 2;
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001171 LoadCommandsSize += (macho::SymtabLoadCommandSize +
1172 macho::DysymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001173 }
1174
1175 // Compute the total size of the section data, as well as its file size and
1176 // vm size.
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001177 uint64_t SectionDataStart = (Is64Bit ? macho::Header64Size :
1178 macho::Header32Size) + LoadCommandsSize;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001179 uint64_t SectionDataSize = 0;
1180 uint64_t SectionDataFileSize = 0;
1181 uint64_t VMSize = 0;
1182 for (MCAssembler::const_iterator it = Asm.begin(),
1183 ie = Asm.end(); it != ie; ++it) {
1184 const MCSectionData &SD = *it;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001185 uint64_t Address = getSectionAddress(&SD);
1186 uint64_t Size = Layout.getSectionAddressSize(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +00001187 uint64_t FileSize = Layout.getSectionFileSize(&SD);
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001188 FileSize += getPaddingSize(&SD, Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001189
Daniel Dunbar5d428512010-03-25 02:00:07 +00001190 VMSize = std::max(VMSize, Address + Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001191
Rafael Espindolaf2dc4aa2010-11-17 20:03:54 +00001192 if (SD.getSection().isVirtualSection())
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001193 continue;
1194
Daniel Dunbar5d428512010-03-25 02:00:07 +00001195 SectionDataSize = std::max(SectionDataSize, Address + Size);
1196 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001197 }
1198
1199 // The section data is padded to 4 bytes.
1200 //
1201 // FIXME: Is this machine dependent?
1202 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1203 SectionDataFileSize += SectionDataPadding;
1204
1205 // Write the prolog, starting with the header and load command...
1206 WriteHeader(NumLoadCommands, LoadCommandsSize,
1207 Asm.getSubsectionsViaSymbols());
1208 WriteSegmentLoadCommand(NumSections, VMSize,
1209 SectionDataStart, SectionDataSize);
1210
1211 // ... and then the section headers.
1212 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1213 for (MCAssembler::const_iterator it = Asm.begin(),
1214 ie = Asm.end(); it != ie; ++it) {
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +00001215 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001216 unsigned NumRelocs = Relocs.size();
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001217 uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001218 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001219 RelocTableEnd += NumRelocs * macho::RelocationInfoSize;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001220 }
1221
1222 // Write the symbol table load command, if used.
1223 if (NumSymbols) {
1224 unsigned FirstLocalSymbol = 0;
1225 unsigned NumLocalSymbols = LocalSymbolData.size();
1226 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1227 unsigned NumExternalSymbols = ExternalSymbolData.size();
1228 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1229 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1230 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1231 unsigned NumSymTabSymbols =
1232 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1233 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1234 uint64_t IndirectSymbolOffset = 0;
1235
1236 // If used, the indirect symbols are written after the section data.
1237 if (NumIndirectSymbols)
1238 IndirectSymbolOffset = RelocTableEnd;
1239
1240 // The symbol table is written after the indirect symbol data.
1241 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1242
1243 // The string table is written after symbol table.
1244 uint64_t StringTableOffset =
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001245 SymbolTableOffset + NumSymTabSymbols * (Is64Bit ? macho::Nlist64Size :
1246 macho::Nlist32Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001247 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1248 StringTableOffset, StringTable.size());
1249
1250 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1251 FirstExternalSymbol, NumExternalSymbols,
1252 FirstUndefinedSymbol, NumUndefinedSymbols,
1253 IndirectSymbolOffset, NumIndirectSymbols);
1254 }
1255
1256 // Write the actual section data.
1257 for (MCAssembler::const_iterator it = Asm.begin(),
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001258 ie = Asm.end(); it != ie; ++it) {
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001259 Asm.WriteSectionData(it, Layout, this);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001260
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001261 uint64_t Pad = getPaddingSize(it, Layout);
1262 for (unsigned int i = 0; i < Pad; ++i)
1263 Write8(0);
1264 }
1265
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001266 // Write the extra padding.
1267 WriteZeros(SectionDataPadding);
1268
1269 // Write the relocation entries.
1270 for (MCAssembler::const_iterator it = Asm.begin(),
1271 ie = Asm.end(); it != ie; ++it) {
1272 // Write the section relocation entries, in reverse order to match 'as'
1273 // (approximately, the exact algorithm is more complicated than this).
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +00001274 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001275 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1276 Write32(Relocs[e - i - 1].Word0);
1277 Write32(Relocs[e - i - 1].Word1);
1278 }
1279 }
1280
1281 // Write the symbol table data, if used.
1282 if (NumSymbols) {
1283 // Write the indirect symbol entries.
1284 for (MCAssembler::const_indirect_symbol_iterator
1285 it = Asm.indirect_symbol_begin(),
1286 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1287 // Indirect symbols in the non lazy symbol pointer section have some
1288 // special handling.
1289 const MCSectionMachO &Section =
1290 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1291 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1292 // If this symbol is defined and internal, mark it as such.
1293 if (it->Symbol->isDefined() &&
1294 !Asm.getSymbolData(*it->Symbol).isExternal()) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +00001295 uint32_t Flags = macho::ISF_Local;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001296 if (it->Symbol->isAbsolute())
Daniel Dunbarf52788f2010-11-27 04:59:14 +00001297 Flags |= macho::ISF_Absolute;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001298 Write32(Flags);
1299 continue;
1300 }
1301 }
1302
1303 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1304 }
1305
1306 // FIXME: Check that offsets match computed ones.
1307
1308 // Write the symbol table entries.
1309 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001310 WriteNlist(LocalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001311 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001312 WriteNlist(ExternalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001313 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001314 WriteNlist(UndefinedSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001315
1316 // Write the string table.
1317 OS << StringTable.str();
1318 }
1319 }
1320};
1321
1322}
1323
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001324MCObjectWriter *llvm::createMachObjectWriter(raw_ostream &OS, bool is64Bit,
1325 uint32_t CPUType,
1326 uint32_t CPUSubtype,
1327 bool IsLittleEndian) {
1328 return new MachObjectWriter(OS, is64Bit, CPUType, CPUSubtype, IsLittleEndian);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001329}