blob: a4c612d0d696c02f9fb6b14c2b3bbec97e8b2ddc [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 +0000228public:
Daniel Dunbarae5abd52010-12-16 16:09:19 +0000229 MachObjectWriter(MCMachObjectTargetWriter *MOTW, raw_ostream &_OS,
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000230 bool _IsLittleEndian)
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000231 : MCObjectWriter(_OS, _IsLittleEndian), TargetObjectWriter(MOTW) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000232 }
233
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000234 /// @name Target Writer Proxy Accessors
235 /// @{
236
237 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Daniel Dunbar532c4562010-12-22 13:49:43 +0000238 bool isARM() const {
239 uint32_t CPUType = TargetObjectWriter->getCPUType() & mach::CTFM_ArchMask;
240 return CPUType == mach::CTM_ARM;
241 }
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000242
243 /// @}
244
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000245 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
246 bool SubsectionsViaSymbols) {
247 uint32_t Flags = 0;
248
249 if (SubsectionsViaSymbols)
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000250 Flags |= macho::HF_SubsectionsViaSymbols;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000251
252 // struct mach_header (28 bytes) or
253 // struct mach_header_64 (32 bytes)
254
255 uint64_t Start = OS.tell();
256 (void) Start;
257
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000258 Write32(is64Bit() ? macho::HM_Object64 : macho::HM_Object32);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000259
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000260 Write32(TargetObjectWriter->getCPUType());
261 Write32(TargetObjectWriter->getCPUSubtype());
Jim Grosbachc9d14392010-11-05 18:48:58 +0000262
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000263 Write32(macho::HFT_Object);
Daniel Dunbar590956f2010-11-27 07:39:37 +0000264 Write32(NumLoadCommands);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000265 Write32(LoadCommandsSize);
266 Write32(Flags);
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000267 if (is64Bit())
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000268 Write32(0); // reserved
269
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000270 assert(OS.tell() - Start == is64Bit() ?
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000271 macho::Header64Size : macho::Header32Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000272 }
273
274 /// WriteSegmentLoadCommand - Write a segment load command.
275 ///
276 /// \arg NumSections - The number of sections in this segment.
277 /// \arg SectionDataSize - The total size of the sections.
278 void WriteSegmentLoadCommand(unsigned NumSections,
279 uint64_t VMSize,
280 uint64_t SectionDataStartOffset,
281 uint64_t SectionDataSize) {
282 // struct segment_command (56 bytes) or
283 // struct segment_command_64 (72 bytes)
284
285 uint64_t Start = OS.tell();
286 (void) Start;
287
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000288 unsigned SegmentLoadCommandSize =
289 is64Bit() ? macho::SegmentLoadCommand64Size:
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000290 macho::SegmentLoadCommand32Size;
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000291 Write32(is64Bit() ? macho::LCT_Segment64 : macho::LCT_Segment);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000292 Write32(SegmentLoadCommandSize +
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000293 NumSections * (is64Bit() ? macho::Section64Size :
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000294 macho::Section32Size));
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000295
296 WriteBytes("", 16);
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000297 if (is64Bit()) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000298 Write64(0); // vmaddr
299 Write64(VMSize); // vmsize
300 Write64(SectionDataStartOffset); // file offset
301 Write64(SectionDataSize); // file size
302 } else {
303 Write32(0); // vmaddr
304 Write32(VMSize); // vmsize
305 Write32(SectionDataStartOffset); // file offset
306 Write32(SectionDataSize); // file size
307 }
308 Write32(0x7); // maxprot
309 Write32(0x7); // initprot
310 Write32(NumSections);
311 Write32(0); // flags
312
313 assert(OS.tell() - Start == SegmentLoadCommandSize);
314 }
315
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000316 void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
317 const MCSectionData &SD, uint64_t FileOffset,
318 uint64_t RelocationsStart, unsigned NumRelocations) {
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000319 uint64_t SectionSize = Layout.getSectionAddressSize(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +0000320
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000321 // The offset is unused for virtual sections.
Rafael Espindolaf2dc4aa2010-11-17 20:03:54 +0000322 if (SD.getSection().isVirtualSection()) {
Daniel Dunbarb026d642010-03-25 07:10:05 +0000323 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000324 FileOffset = 0;
325 }
326
327 // struct section (68 bytes) or
328 // struct section_64 (80 bytes)
329
330 uint64_t Start = OS.tell();
331 (void) Start;
332
Daniel Dunbar56279f42010-05-18 17:28:20 +0000333 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000334 WriteBytes(Section.getSectionName(), 16);
335 WriteBytes(Section.getSegmentName(), 16);
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000336 if (is64Bit()) {
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000337 Write64(getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000338 Write64(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000339 } else {
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000340 Write32(getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000341 Write32(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000342 }
343 Write32(FileOffset);
344
345 unsigned Flags = Section.getTypeAndAttributes();
346 if (SD.hasInstructions())
347 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
348
349 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
350 Write32(Log2_32(SD.getAlignment()));
351 Write32(NumRelocations ? RelocationsStart : 0);
352 Write32(NumRelocations);
353 Write32(Flags);
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000354 Write32(IndirectSymBase.lookup(&SD)); // reserved1
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000355 Write32(Section.getStubSize()); // reserved2
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000356 if (is64Bit())
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000357 Write32(0); // reserved3
358
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000359 assert(OS.tell() - Start == is64Bit() ? macho::Section64Size :
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000360 macho::Section32Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000361 }
362
363 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
364 uint32_t StringTableOffset,
365 uint32_t StringTableSize) {
366 // struct symtab_command (24 bytes)
367
368 uint64_t Start = OS.tell();
369 (void) Start;
370
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000371 Write32(macho::LCT_Symtab);
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000372 Write32(macho::SymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000373 Write32(SymbolOffset);
374 Write32(NumSymbols);
375 Write32(StringTableOffset);
376 Write32(StringTableSize);
377
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000378 assert(OS.tell() - Start == macho::SymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000379 }
380
381 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
382 uint32_t NumLocalSymbols,
383 uint32_t FirstExternalSymbol,
384 uint32_t NumExternalSymbols,
385 uint32_t FirstUndefinedSymbol,
386 uint32_t NumUndefinedSymbols,
387 uint32_t IndirectSymbolOffset,
388 uint32_t NumIndirectSymbols) {
389 // struct dysymtab_command (80 bytes)
390
391 uint64_t Start = OS.tell();
392 (void) Start;
393
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000394 Write32(macho::LCT_Dysymtab);
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000395 Write32(macho::DysymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000396 Write32(FirstLocalSymbol);
397 Write32(NumLocalSymbols);
398 Write32(FirstExternalSymbol);
399 Write32(NumExternalSymbols);
400 Write32(FirstUndefinedSymbol);
401 Write32(NumUndefinedSymbols);
402 Write32(0); // tocoff
403 Write32(0); // ntoc
404 Write32(0); // modtaboff
405 Write32(0); // nmodtab
406 Write32(0); // extrefsymoff
407 Write32(0); // nextrefsyms
408 Write32(IndirectSymbolOffset);
409 Write32(NumIndirectSymbols);
410 Write32(0); // extreloff
411 Write32(0); // nextrel
412 Write32(0); // locreloff
413 Write32(0); // nlocrel
414
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000415 assert(OS.tell() - Start == macho::DysymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000416 }
417
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000418 void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000419 MCSymbolData &Data = *MSD.SymbolData;
420 const MCSymbol &Symbol = Data.getSymbol();
421 uint8_t Type = 0;
422 uint16_t Flags = Data.getFlags();
423 uint32_t Address = 0;
424
425 // Set the N_TYPE bits. See <mach-o/nlist.h>.
426 //
427 // FIXME: Are the prebound or indirect fields possible here?
428 if (Symbol.isUndefined())
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000429 Type = macho::STT_Undefined;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000430 else if (Symbol.isAbsolute())
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000431 Type = macho::STT_Absolute;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000432 else
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000433 Type = macho::STT_Section;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000434
435 // FIXME: Set STAB bits.
436
437 if (Data.isPrivateExtern())
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000438 Type |= macho::STF_PrivateExtern;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000439
440 // Set external bit.
441 if (Data.isExternal() || Symbol.isUndefined())
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000442 Type |= macho::STF_External;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000443
444 // Compute the symbol address.
445 if (Symbol.isDefined()) {
446 if (Symbol.isAbsolute()) {
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000447 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000448 } else {
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000449 Address = getSymbolAddress(&Data, Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000450 }
451 } else if (Data.isCommon()) {
452 // Common symbols are encoded with the size in the address
453 // field, and their alignment in the flags.
454 Address = Data.getCommonSize();
455
456 // Common alignment is packed into the 'desc' bits.
457 if (unsigned Align = Data.getCommonAlignment()) {
458 unsigned Log2Size = Log2_32(Align);
459 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
460 if (Log2Size > 15)
Chris Lattner75361b62010-04-07 22:58:41 +0000461 report_fatal_error("invalid 'common' alignment '" +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000462 Twine(Align) + "'");
463 // FIXME: Keep this mask with the SymbolFlags enumeration.
464 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
465 }
466 }
467
468 // struct nlist (12 bytes)
469
470 Write32(MSD.StringIndex);
471 Write8(Type);
472 Write8(MSD.SectionIndex);
473
474 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
475 // value.
476 Write16(Flags);
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000477 if (is64Bit())
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000478 Write64(Address);
479 else
480 Write32(Address);
481 }
482
Daniel Dunbar35b06572010-03-22 23:16:43 +0000483 // FIXME: We really need to improve the relocation validation. Basically, we
484 // want to implement a separate computation which evaluates the relocation
485 // entry as the linker would, and verifies that the resultant fixup value is
486 // exactly what the encoder wanted. This will catch several classes of
487 // problems:
488 //
489 // - Relocation entry bugs, the two algorithms are unlikely to have the same
490 // exact bug.
491 //
492 // - Relaxation issues, where we forget to relax something.
493 //
494 // - Input errors, where something cannot be correctly encoded. 'as' allows
495 // these through in many cases.
496
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000497 static bool isFixupKindRIPRel(unsigned Kind) {
498 return Kind == X86::reloc_riprel_4byte ||
499 Kind == X86::reloc_riprel_4byte_movq_load;
500 }
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000501 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000502 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000503 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000504 uint64_t &FixedValue) {
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000505 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Daniel Dunbar482ad802010-05-26 15:18:31 +0000506 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
507 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000508
509 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000510 uint32_t FixupOffset =
511 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
512 uint32_t FixupAddress =
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000513 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000514 int64_t Value = 0;
515 unsigned Index = 0;
516 unsigned IsExtern = 0;
517 unsigned Type = 0;
518
519 Value = Target.getConstant();
520
521 if (IsPCRel) {
522 // Compensate for the relocation offset, Darwin x86_64 relocations only
523 // have the addend and appear to have attempted to define it to be the
524 // actual expression addend without the PCrel bias. However, instructions
525 // with data following the relocation are not accomodated for (see comment
526 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
Benjamin Kramer454c4ce2010-04-08 15:25:57 +0000527 Value += 1LL << Log2Size;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000528 }
529
530 if (Target.isAbsolute()) { // constant
531 // SymbolNum of 0 indicates the absolute section.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000532 Type = macho::RIT_X86_64_Unsigned;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000533 Index = 0;
534
535 // FIXME: I believe this is broken, I don't think the linker can
536 // understand it. I think it would require a local relocation, but I'm not
537 // sure if that would work either. The official way to get an absolute
538 // PCrel relocation is to use an absolute symbol (which we don't support
539 // yet).
540 if (IsPCRel) {
541 IsExtern = 1;
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000542 Type = macho::RIT_X86_64_Branch;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000543 }
544 } else if (Target.getSymB()) { // A - B + constant
545 const MCSymbol *A = &Target.getSymA()->getSymbol();
546 MCSymbolData &A_SD = Asm.getSymbolData(*A);
Rafael Espindolab8141102010-09-27 18:13:03 +0000547 const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000548
549 const MCSymbol *B = &Target.getSymB()->getSymbol();
550 MCSymbolData &B_SD = Asm.getSymbolData(*B);
Rafael Espindolab8141102010-09-27 18:13:03 +0000551 const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000552
553 // Neither symbol can be modified.
554 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
555 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000556 report_fatal_error("unsupported relocation of modified symbol");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000557
558 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
559 // implement most of these correctly.
560 if (IsPCRel)
Chris Lattner75361b62010-04-07 22:58:41 +0000561 report_fatal_error("unsupported pc-relative relocation of difference");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000562
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000563 // The support for the situation where one or both of the symbols would
564 // require a local relocation is handled just like if the symbols were
565 // external. This is certainly used in the case of debug sections where
566 // the section has only temporary symbols and thus the symbols don't have
567 // base symbols. This is encoded using the section ordinal and
568 // non-extern relocation entries.
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000569
570 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000571 // a single SIGNED relocation); reject it for now. Except the case where
572 // both symbols don't have a base, equal but both NULL.
573 if (A_Base == B_Base && A_Base)
Chris Lattner75361b62010-04-07 22:58:41 +0000574 report_fatal_error("unsupported relocation with identical base");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000575
Rafael Espindolaf10d2be2010-12-07 01:09:54 +0000576 Value += getSymbolAddress(&A_SD, Layout) -
577 (A_Base == NULL ? 0 : getSymbolAddress(A_Base, Layout));
578 Value -= getSymbolAddress(&B_SD, Layout) -
579 (B_Base == NULL ? 0 : getSymbolAddress(B_Base, Layout));
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000580
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000581 if (A_Base) {
582 Index = A_Base->getIndex();
583 IsExtern = 1;
584 }
585 else {
586 Index = A_SD.getFragment()->getParent()->getOrdinal() + 1;
587 IsExtern = 0;
588 }
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000589 Type = macho::RIT_X86_64_Unsigned;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000590
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000591 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000592 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000593 MRE.Word1 = ((Index << 0) |
594 (IsPCRel << 24) |
595 (Log2Size << 25) |
596 (IsExtern << 27) |
597 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000598 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000599
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000600 if (B_Base) {
601 Index = B_Base->getIndex();
602 IsExtern = 1;
603 }
604 else {
605 Index = B_SD.getFragment()->getParent()->getOrdinal() + 1;
606 IsExtern = 0;
607 }
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000608 Type = macho::RIT_X86_64_Subtractor;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000609 } else {
610 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
611 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
Rafael Espindolab8141102010-09-27 18:13:03 +0000612 const MCSymbolData *Base = Asm.getAtom(&SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000613
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000614 // Relocations inside debug sections always use local relocations when
615 // possible. This seems to be done because the debugger doesn't fully
616 // understand x86_64 relocation entries, and expects to find values that
617 // have already been fixed up.
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000618 if (Symbol->isInSection()) {
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000619 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
620 Fragment->getParent()->getSection());
621 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
622 Base = 0;
623 }
624
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000625 // x86_64 almost always uses external relocations, except when there is no
626 // symbol to use as a base address (a local symbol with no preceeding
627 // non-local symbol).
628 if (Base) {
629 Index = Base->getIndex();
630 IsExtern = 1;
631
632 // Add the local offset, if needed.
633 if (Base != &SD)
Rafael Espindola1dda29b2010-12-06 21:51:55 +0000634 Value += Layout.getSymbolOffset(&SD) - Layout.getSymbolOffset(Base);
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000635 } else if (Symbol->isInSection()) {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000636 // The index is the section ordinal (1-based).
637 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000638 IsExtern = 0;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000639 Value += getSymbolAddress(&SD, Layout);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000640
641 if (IsPCRel)
Daniel Dunbardb4c7e62010-05-11 23:53:11 +0000642 Value -= FixupAddress + (1 << Log2Size);
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000643 } else if (Symbol->isVariable()) {
644 const MCExpr *Value = Symbol->getVariableValue();
645 int64_t Res;
646 bool isAbs = Value->EvaluateAsAbsolute(Res, Layout, SectionAddress);
647 if (isAbs) {
648 FixedValue = Res;
649 return;
650 } else {
651 report_fatal_error("unsupported relocation of variable '" +
652 Symbol->getName() + "'");
653 }
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000654 } else {
655 report_fatal_error("unsupported relocation of undefined symbol '" +
656 Symbol->getName() + "'");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000657 }
658
659 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
660 if (IsPCRel) {
661 if (IsRIPRel) {
662 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
663 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
664 // rewrite the movq to an leaq at link time if the symbol ends up in
665 // the same linkage unit.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000666 if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000667 Type = macho::RIT_X86_64_GOTLoad;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000668 else
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000669 Type = macho::RIT_X86_64_GOT;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000670 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000671 Type = macho::RIT_X86_64_TLV;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000672 } else if (Modifier != MCSymbolRefExpr::VK_None) {
673 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000674 } else {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000675 Type = macho::RIT_X86_64_Signed;
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000676
677 // The Darwin x86_64 relocation format has a problem where it cannot
678 // encode an address (L<foo> + <constant>) which is outside the atom
679 // containing L<foo>. Generally, this shouldn't occur but it does
680 // happen when we have a RIPrel instruction with data following the
681 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
682 // adjustment Darwin x86_64 uses, the offset is still negative and
683 // the linker has no way to recognize this.
684 //
685 // To work around this, Darwin uses several special relocation types
686 // to indicate the offsets. However, the specification or
687 // implementation of these seems to also be incomplete; they should
688 // adjust the addend as well based on the actual encoded instruction
689 // (the additional bias), but instead appear to just look at the
690 // final offset.
691 switch (-(Target.getConstant() + (1LL << Log2Size))) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000692 case 1: Type = macho::RIT_X86_64_Signed1; break;
693 case 2: Type = macho::RIT_X86_64_Signed2; break;
694 case 4: Type = macho::RIT_X86_64_Signed4; break;
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000695 }
696 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000697 } else {
698 if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000699 report_fatal_error("unsupported symbol modifier in branch "
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000700 "relocation");
701
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000702 Type = macho::RIT_X86_64_Branch;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000703 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000704 } else {
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000705 if (Modifier == MCSymbolRefExpr::VK_GOT) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000706 Type = macho::RIT_X86_64_GOT;
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000707 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
708 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
709 // which case all we do is set the PCrel bit in the relocation entry;
710 // this is used with exception handling, for example. The source is
711 // required to include any necessary offset directly.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000712 Type = macho::RIT_X86_64_GOT;
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000713 IsPCRel = 1;
Eric Christopher96ac5152010-05-26 00:02:12 +0000714 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
715 report_fatal_error("TLVP symbol modifier should have been rip-rel");
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000716 } else if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000717 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000718 else
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000719 Type = macho::RIT_X86_64_Unsigned;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000720 }
721 }
722
723 // x86_64 always writes custom values into the fixups.
724 FixedValue = Value;
725
726 // struct relocation_info (8 bytes)
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000727 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000728 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000729 MRE.Word1 = ((Index << 0) |
730 (IsPCRel << 24) |
731 (Log2Size << 25) |
732 (IsExtern << 27) |
733 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000734 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000735 }
736
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000737 void RecordScatteredRelocation(const MCAssembler &Asm,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000738 const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000739 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000740 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000741 uint64_t &FixedValue) {
Daniel Dunbar482ad802010-05-26 15:18:31 +0000742 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000743 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Daniel Dunbar482ad802010-05-26 15:18:31 +0000744 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000745 unsigned Type = macho::RIT_Vanilla;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000746
747 // See <reloc.h>.
748 const MCSymbol *A = &Target.getSymA()->getSymbol();
749 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
750
751 if (!A_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000752 report_fatal_error("symbol '" + A->getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000753 "' can not be undefined in a subtraction expression");
754
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000755 uint32_t Value = getSymbolAddress(A_SD, Layout);
756 uint64_t SecAddr = getSectionAddress(A_SD->getFragment()->getParent());
757 FixedValue += SecAddr;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000758 uint32_t Value2 = 0;
759
760 if (const MCSymbolRefExpr *B = Target.getSymB()) {
761 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
762
763 if (!B_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000764 report_fatal_error("symbol '" + B->getSymbol().getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000765 "' can not be undefined in a subtraction expression");
766
767 // Select the appropriate difference relocation type.
768 //
769 // Note that there is no longer any semantic difference between these two
770 // relocation types from the linkers point of view, this is done solely
771 // for pedantic compatibility with 'as'.
Matt Beaumont-Gaye733cf82010-12-21 23:43:23 +0000772 Type = A_SD->isExternal() ? (unsigned)macho::RIT_Difference :
773 (unsigned)macho::RIT_Generic_LocalDifference;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000774 Value2 = getSymbolAddress(B_SD, Layout);
775 FixedValue -= getSectionAddress(B_SD->getFragment()->getParent());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000776 }
777
778 // Relocations are written out in reverse order, so the PAIR comes first.
Daniel Dunbare1feeb92010-12-21 15:26:45 +0000779 if (Type == macho::RIT_Difference ||
780 Type == macho::RIT_Generic_LocalDifference) {
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000781 macho::RelocationEntry MRE;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000782 MRE.Word0 = ((0 << 0) |
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000783 (macho::RIT_Pair << 24) |
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000784 (Log2Size << 28) |
785 (IsPCRel << 30) |
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000786 macho::RF_Scattered);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000787 MRE.Word1 = Value2;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000788 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000789 }
790
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000791 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000792 MRE.Word0 = ((FixupOffset << 0) |
793 (Type << 24) |
794 (Log2Size << 28) |
795 (IsPCRel << 30) |
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000796 macho::RF_Scattered);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000797 MRE.Word1 = Value;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000798 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000799 }
800
Eric Christopherc9ada472010-06-15 22:59:05 +0000801 void RecordTLVPRelocation(const MCAssembler &Asm,
Eric Christophere48dbf82010-06-16 00:26:36 +0000802 const MCAsmLayout &Layout,
803 const MCFragment *Fragment,
804 const MCFixup &Fixup, MCValue Target,
805 uint64_t &FixedValue) {
Eric Christopherc9ada472010-06-15 22:59:05 +0000806 assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000807 !is64Bit() &&
Eric Christopherc9ada472010-06-15 22:59:05 +0000808 "Should only be called with a 32-bit TLVP relocation!");
809
Eric Christopherc9ada472010-06-15 22:59:05 +0000810 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
811 uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
812 unsigned IsPCRel = 0;
813
814 // Get the symbol data.
815 MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
816 unsigned Index = SD_A->getIndex();
817
Eric Christopherbc067372010-06-16 21:32:38 +0000818 // We're only going to have a second symbol in pic mode and it'll be a
819 // subtraction from the picbase. For 32-bit pic the addend is the difference
Eric Christopher04b8d3c2010-06-17 00:49:46 +0000820 // between the picbase and the next address. For 32-bit static the addend
821 // is zero.
Eric Christopherbc067372010-06-16 21:32:38 +0000822 if (Target.getSymB()) {
Eric Christopher1008d352010-06-22 23:51:47 +0000823 // If this is a subtraction then we're pcrel.
824 uint32_t FixupAddress =
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000825 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
Eric Christopher1008d352010-06-22 23:51:47 +0000826 MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
Eric Christopherc9ada472010-06-15 22:59:05 +0000827 IsPCRel = 1;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000828 FixedValue = (FixupAddress - getSymbolAddress(SD_B, Layout) +
Eric Christopher1008d352010-06-22 23:51:47 +0000829 Target.getConstant());
Chris Lattnerabf8f9c2010-08-16 16:35:20 +0000830 FixedValue += 1ULL << Log2Size;
Eric Christopherbc067372010-06-16 21:32:38 +0000831 } else {
832 FixedValue = 0;
833 }
Jim Grosbach3c384922010-11-11 20:16:23 +0000834
Eric Christopherc9ada472010-06-15 22:59:05 +0000835 // struct relocation_info (8 bytes)
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000836 macho::RelocationEntry MRE;
Eric Christopherc9ada472010-06-15 22:59:05 +0000837 MRE.Word0 = Value;
Daniel Dunbare1feeb92010-12-21 15:26:45 +0000838 MRE.Word1 = ((Index << 0) |
839 (IsPCRel << 24) |
840 (Log2Size << 25) |
841 (1 << 27) | // Extern
842 (macho::RIT_Generic_TLV << 28)); // Type
Eric Christopherc9ada472010-06-15 22:59:05 +0000843 Relocations[Fragment->getParent()].push_back(MRE);
844 }
Jim Grosbach3c384922010-11-11 20:16:23 +0000845
Daniel Dunbar532c4562010-12-22 13:49:43 +0000846 void RecordARMRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
847 const MCFragment *Fragment, const MCFixup &Fixup,
848 MCValue Target, uint64_t &FixedValue) {
849 // FIXME!
850 }
851
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000852 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000853 const MCFragment *Fragment, const MCFixup &Fixup,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000854 MCValue Target, uint64_t &FixedValue) {
Daniel Dunbar532c4562010-12-22 13:49:43 +0000855 // FIXME: These needs to be factored into the target Mach-O writer.
856 if (isARM()) {
857 RecordARMRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
858 return;
859 }
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000860 if (is64Bit()) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000861 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000862 return;
863 }
864
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000865 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Daniel Dunbar482ad802010-05-26 15:18:31 +0000866 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000867
Eric Christopherc9ada472010-06-15 22:59:05 +0000868 // If this is a 32-bit TLVP reloc it's handled a bit differently.
Daniel Dunbar23bea412010-09-17 15:21:50 +0000869 if (Target.getSymA() &&
870 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
Eric Christopherc9ada472010-06-15 22:59:05 +0000871 RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
872 return;
873 }
Jim Grosbach3c384922010-11-11 20:16:23 +0000874
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000875 // If this is a difference or a defined symbol plus an offset, then we need
876 // a scattered relocation entry.
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000877 // Differences always require scattered relocations.
878 if (Target.getSymB())
879 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
880 Target, FixedValue);
881
882 // Get the symbol data, if any.
883 MCSymbolData *SD = 0;
884 if (Target.getSymA())
885 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
886
887 // If this is an internal relocation with an offset, it also needs a
888 // scattered relocation entry.
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000889 uint32_t Offset = Target.getConstant();
890 if (IsPCRel)
891 Offset += 1 << Log2Size;
Daniel Dunbara8251fa2010-05-10 23:15:20 +0000892 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
893 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
894 Target, FixedValue);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000895
896 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000897 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000898 unsigned Index = 0;
899 unsigned IsExtern = 0;
900 unsigned Type = 0;
901
902 if (Target.isAbsolute()) { // constant
903 // SymbolNum of 0 indicates the absolute section.
904 //
905 // FIXME: Currently, these are never generated (see code below). I cannot
906 // find a case where they are actually emitted.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000907 Type = macho::RIT_Vanilla;
Rafael Espindola545b77e2010-12-07 17:12:32 +0000908 } else if (SD->getSymbol().isVariable()) {
909 const MCExpr *Value = SD->getSymbol().getVariableValue();
910 int64_t Res;
911 bool isAbs = Value->EvaluateAsAbsolute(Res, Layout, SectionAddress);
912 if (isAbs) {
913 FixedValue = Res;
914 return;
915 } else {
916 report_fatal_error("unsupported relocation of variable '" +
917 SD->getSymbol().getName() + "'");
918 }
Michael J. Spencerb0f3b3e2010-08-10 16:00:49 +0000919 } else {
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000920 // Check whether we need an external or internal relocation.
921 if (doesSymbolRequireExternRelocation(SD)) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000922 IsExtern = 1;
923 Index = SD->getIndex();
Daniel Dunbare9460ec2010-05-10 23:15:13 +0000924 // For external relocations, make sure to offset the fixup value to
925 // compensate for the addend of the symbol address, if it was
926 // undefined. This occurs with weak definitions, for example.
927 if (!SD->Symbol->isUndefined())
Rafael Espindola3b3148f2010-12-07 05:57:28 +0000928 FixedValue -= Layout.getSymbolOffset(SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000929 } else {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000930 // The index is the section ordinal (1-based).
931 Index = SD->getFragment()->getParent()->getOrdinal() + 1;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000932 FixedValue += getSectionAddress(SD->getFragment()->getParent());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000933 }
Rafael Espindolabf60dad2010-12-07 03:50:14 +0000934 if (IsPCRel)
935 FixedValue -= getSectionAddress(Fragment->getParent());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000936
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000937 Type = macho::RIT_Vanilla;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000938 }
939
940 // struct relocation_info (8 bytes)
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000941 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000942 MRE.Word0 = FixupOffset;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000943 MRE.Word1 = ((Index << 0) |
944 (IsPCRel << 24) |
945 (Log2Size << 25) |
946 (IsExtern << 27) |
947 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000948 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000949 }
950
951 void BindIndirectSymbols(MCAssembler &Asm) {
952 // This is the point where 'as' creates actual symbols for indirect symbols
953 // (in the following two passes). It would be easier for us to do this
954 // sooner when we see the attribute, but that makes getting the order in the
955 // symbol table much more complicated than it is worth.
956 //
957 // FIXME: Revisit this when the dust settles.
958
959 // Bind non lazy symbol pointers first.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000960 unsigned 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_NON_LAZY_SYMBOL_POINTERS)
967 continue;
968
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000969 // Initialize the section indirect symbol base, if necessary.
970 if (!IndirectSymBase.count(it->SectionData))
971 IndirectSymBase[it->SectionData] = IndirectIndex;
Jim Grosbach3c384922010-11-11 20:16:23 +0000972
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000973 Asm.getOrCreateSymbolData(*it->Symbol);
974 }
975
976 // Then lazy symbol pointers and symbol stubs.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000977 IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000978 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000979 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000980 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +0000981 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000982
983 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
984 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
985 continue;
986
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000987 // Initialize the section indirect symbol base, if necessary.
988 if (!IndirectSymBase.count(it->SectionData))
989 IndirectSymBase[it->SectionData] = IndirectIndex;
990
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000991 // Set the symbol type to undefined lazy, but only on construction.
992 //
993 // FIXME: Do not hardcode.
994 bool Created;
995 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
996 if (Created)
997 Entry.setFlags(Entry.getFlags() | 0x0001);
998 }
999 }
1000
1001 /// ComputeSymbolTable - Compute the symbol table data
1002 ///
1003 /// \param StringTable [out] - The string table data.
1004 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
1005 /// string table.
1006 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
1007 std::vector<MachSymbolData> &LocalSymbolData,
1008 std::vector<MachSymbolData> &ExternalSymbolData,
1009 std::vector<MachSymbolData> &UndefinedSymbolData) {
1010 // Build section lookup table.
1011 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
1012 unsigned Index = 1;
1013 for (MCAssembler::iterator it = Asm.begin(),
1014 ie = Asm.end(); it != ie; ++it, ++Index)
1015 SectionIndexMap[&it->getSection()] = Index;
1016 assert(Index <= 256 && "Too many sections!");
1017
1018 // Index 0 is always the empty string.
1019 StringMap<uint64_t> StringIndexMap;
1020 StringTable += '\x00';
1021
1022 // Build the symbol arrays and the string table, but only for non-local
1023 // symbols.
1024 //
1025 // The particular order that we collect the symbols and create the string
1026 // table, then sort the symbols is chosen to match 'as'. Even though it
1027 // doesn't matter for correctness, this is important for letting us diff .o
1028 // files.
1029 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1030 ie = Asm.symbol_end(); it != ie; ++it) {
1031 const MCSymbol &Symbol = it->getSymbol();
1032
1033 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +00001034 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001035 continue;
1036
1037 if (!it->isExternal() && !Symbol.isUndefined())
1038 continue;
1039
1040 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1041 if (!Entry) {
1042 Entry = StringTable.size();
1043 StringTable += Symbol.getName();
1044 StringTable += '\x00';
1045 }
1046
1047 MachSymbolData MSD;
1048 MSD.SymbolData = it;
1049 MSD.StringIndex = Entry;
1050
1051 if (Symbol.isUndefined()) {
1052 MSD.SectionIndex = 0;
1053 UndefinedSymbolData.push_back(MSD);
1054 } else if (Symbol.isAbsolute()) {
1055 MSD.SectionIndex = 0;
1056 ExternalSymbolData.push_back(MSD);
1057 } else {
1058 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1059 assert(MSD.SectionIndex && "Invalid section index!");
1060 ExternalSymbolData.push_back(MSD);
1061 }
1062 }
1063
1064 // Now add the data for local symbols.
1065 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1066 ie = Asm.symbol_end(); it != ie; ++it) {
1067 const MCSymbol &Symbol = it->getSymbol();
1068
1069 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +00001070 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001071 continue;
1072
1073 if (it->isExternal() || Symbol.isUndefined())
1074 continue;
1075
1076 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1077 if (!Entry) {
1078 Entry = StringTable.size();
1079 StringTable += Symbol.getName();
1080 StringTable += '\x00';
1081 }
1082
1083 MachSymbolData MSD;
1084 MSD.SymbolData = it;
1085 MSD.StringIndex = Entry;
1086
1087 if (Symbol.isAbsolute()) {
1088 MSD.SectionIndex = 0;
1089 LocalSymbolData.push_back(MSD);
1090 } else {
1091 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1092 assert(MSD.SectionIndex && "Invalid section index!");
1093 LocalSymbolData.push_back(MSD);
1094 }
1095 }
1096
1097 // External and undefined symbols are required to be in lexicographic order.
1098 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1099 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1100
1101 // Set the symbol indices.
1102 Index = 0;
1103 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1104 LocalSymbolData[i].SymbolData->setIndex(Index++);
1105 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1106 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1107 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1108 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1109
1110 // The string table is padded to a multiple of 4.
1111 while (StringTable.size() % 4)
1112 StringTable += '\x00';
1113 }
1114
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001115 void computeSectionAddresses(const MCAssembler &Asm,
1116 const MCAsmLayout &Layout) {
1117 uint64_t StartAddress = 0;
1118 const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
1119 for (int i = 0, n = Order.size(); i != n ; ++i) {
1120 const MCSectionData *SD = Order[i];
1121 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
1122 SectionAddress[SD] = StartAddress;
1123 StartAddress += Layout.getSectionAddressSize(SD);
1124 // Explicitly pad the section to match the alignment requirements of the
1125 // following one. This is for 'gas' compatibility, it shouldn't
1126 /// strictly be necessary.
1127 StartAddress += getPaddingSize(SD, Layout);
1128 }
1129 }
1130
1131 void ExecutePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout) {
1132 computeSectionAddresses(Asm, Layout);
1133
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001134 // Create symbol data for any indirect symbols.
1135 BindIndirectSymbols(Asm);
1136
1137 // Compute symbol table information and bind symbol indices.
1138 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1139 UndefinedSymbolData);
1140 }
1141
Daniel Dunbar1f3662a2010-12-17 04:54:54 +00001142 bool IsSymbolRefDifferenceFullyResolved(const MCAssembler &Asm,
1143 const MCSymbolRefExpr *A,
Rafael Espindola31327802010-12-18 06:27:54 +00001144 const MCSymbolRefExpr *B,
1145 bool InSet) const {
1146 if (InSet)
1147 return true;
1148
Daniel Dunbarb8742272010-12-17 05:50:29 +00001149 if (!TargetObjectWriter->useAggressiveSymbolFolding())
1150 return false;
1151
Daniel Dunbar32c1c5a2010-12-17 04:54:58 +00001152 // The effective address is
1153 // addr(atom(A)) + offset(A)
1154 // - addr(atom(B)) - offset(B)
1155 // and the offsets are not relocatable, so the fixup is fully resolved when
1156 // addr(atom(A)) - addr(atom(B)) == 0.
1157 const MCSymbolData *A_Base = 0, *B_Base = 0;
1158
1159 // Modified symbol references cannot be resolved.
1160 if (A->getKind() != MCSymbolRefExpr::VK_None ||
1161 B->getKind() != MCSymbolRefExpr::VK_None)
1162 return false;
1163
1164 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
1165 if (!A_Base)
1166 return false;
1167
1168 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
1169 if (!B_Base)
1170 return false;
1171
1172 // If the atoms are the same, they are guaranteed to have the same address.
1173 if (A_Base == B_Base)
1174 return true;
1175
1176 // Otherwise, we can't prove this is fully resolved.
Daniel Dunbar1f3662a2010-12-17 04:54:54 +00001177 return false;
1178 }
1179
Rafael Espindola70703872010-09-30 02:22:20 +00001180 bool IsFixupFullyResolved(const MCAssembler &Asm,
1181 const MCValue Target,
1182 bool IsPCRel,
1183 const MCFragment *DF) const {
Daniel Dunbar7976b882010-11-27 05:18:48 +00001184 // Otherwise, determine whether this value is actually resolved; scattering
1185 // may cause atoms to move.
Rafael Espindola70703872010-09-30 02:22:20 +00001186
Daniel Dunbar7976b882010-11-27 05:18:48 +00001187 // Check if we are using the "simple" resolution algorithm (e.g.,
1188 // i386).
1189 if (!Asm.getBackend().hasReliableSymbolDifference()) {
1190 const MCSection *BaseSection = 0;
1191 if (IsPCRel)
1192 BaseSection = &DF->getParent()->getSection();
1193
1194 return isScatteredFixupFullyResolvedSimple(Asm, Target, BaseSection);
Rafael Espindola70703872010-09-30 02:22:20 +00001195 }
Daniel Dunbar7976b882010-11-27 05:18:48 +00001196
1197 // Otherwise, compute the proper answer as reliably as possible.
1198
1199 // If this is a PCrel relocation, find the base atom (identified by its
1200 // symbol) that the fixup value is relative to.
1201 const MCSymbolData *BaseSymbol = 0;
1202 if (IsPCRel) {
1203 BaseSymbol = DF->getAtom();
1204 if (!BaseSymbol)
1205 return false;
1206 }
1207
1208 return isScatteredFixupFullyResolved(Asm, Target, BaseSymbol);
Rafael Espindola70703872010-09-30 02:22:20 +00001209 }
1210
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001211 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001212 unsigned NumSections = Asm.size();
1213
1214 // The section data starts after the header, the segment load command (and
1215 // section headers) and the symbol table.
1216 unsigned NumLoadCommands = 1;
Daniel Dunbar5d05d972010-12-16 17:21:02 +00001217 uint64_t LoadCommandsSize = is64Bit() ?
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001218 macho::SegmentLoadCommand64Size + NumSections * macho::Section64Size :
1219 macho::SegmentLoadCommand32Size + NumSections * macho::Section32Size;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001220
1221 // Add the symbol table load command sizes, if used.
1222 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1223 UndefinedSymbolData.size();
1224 if (NumSymbols) {
1225 NumLoadCommands += 2;
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001226 LoadCommandsSize += (macho::SymtabLoadCommandSize +
1227 macho::DysymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001228 }
1229
1230 // Compute the total size of the section data, as well as its file size and
1231 // vm size.
Daniel Dunbar5d05d972010-12-16 17:21:02 +00001232 uint64_t SectionDataStart = (is64Bit() ? macho::Header64Size :
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001233 macho::Header32Size) + LoadCommandsSize;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001234 uint64_t SectionDataSize = 0;
1235 uint64_t SectionDataFileSize = 0;
1236 uint64_t VMSize = 0;
1237 for (MCAssembler::const_iterator it = Asm.begin(),
1238 ie = Asm.end(); it != ie; ++it) {
1239 const MCSectionData &SD = *it;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001240 uint64_t Address = getSectionAddress(&SD);
1241 uint64_t Size = Layout.getSectionAddressSize(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +00001242 uint64_t FileSize = Layout.getSectionFileSize(&SD);
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001243 FileSize += getPaddingSize(&SD, Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001244
Daniel Dunbar5d428512010-03-25 02:00:07 +00001245 VMSize = std::max(VMSize, Address + Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001246
Rafael Espindolaf2dc4aa2010-11-17 20:03:54 +00001247 if (SD.getSection().isVirtualSection())
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001248 continue;
1249
Daniel Dunbar5d428512010-03-25 02:00:07 +00001250 SectionDataSize = std::max(SectionDataSize, Address + Size);
1251 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001252 }
1253
1254 // The section data is padded to 4 bytes.
1255 //
1256 // FIXME: Is this machine dependent?
1257 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1258 SectionDataFileSize += SectionDataPadding;
1259
1260 // Write the prolog, starting with the header and load command...
1261 WriteHeader(NumLoadCommands, LoadCommandsSize,
1262 Asm.getSubsectionsViaSymbols());
1263 WriteSegmentLoadCommand(NumSections, VMSize,
1264 SectionDataStart, SectionDataSize);
1265
1266 // ... and then the section headers.
1267 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1268 for (MCAssembler::const_iterator it = Asm.begin(),
1269 ie = Asm.end(); it != ie; ++it) {
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +00001270 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001271 unsigned NumRelocs = Relocs.size();
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001272 uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001273 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001274 RelocTableEnd += NumRelocs * macho::RelocationInfoSize;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001275 }
1276
1277 // Write the symbol table load command, if used.
1278 if (NumSymbols) {
1279 unsigned FirstLocalSymbol = 0;
1280 unsigned NumLocalSymbols = LocalSymbolData.size();
1281 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1282 unsigned NumExternalSymbols = ExternalSymbolData.size();
1283 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1284 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1285 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1286 unsigned NumSymTabSymbols =
1287 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1288 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1289 uint64_t IndirectSymbolOffset = 0;
1290
1291 // If used, the indirect symbols are written after the section data.
1292 if (NumIndirectSymbols)
1293 IndirectSymbolOffset = RelocTableEnd;
1294
1295 // The symbol table is written after the indirect symbol data.
1296 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1297
1298 // The string table is written after symbol table.
1299 uint64_t StringTableOffset =
Daniel Dunbar5d05d972010-12-16 17:21:02 +00001300 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ? macho::Nlist64Size :
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001301 macho::Nlist32Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001302 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1303 StringTableOffset, StringTable.size());
1304
1305 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1306 FirstExternalSymbol, NumExternalSymbols,
1307 FirstUndefinedSymbol, NumUndefinedSymbols,
1308 IndirectSymbolOffset, NumIndirectSymbols);
1309 }
1310
1311 // Write the actual section data.
1312 for (MCAssembler::const_iterator it = Asm.begin(),
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001313 ie = Asm.end(); it != ie; ++it) {
Daniel Dunbar5d2477c2010-12-17 02:45:59 +00001314 Asm.WriteSectionData(it, Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001315
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001316 uint64_t Pad = getPaddingSize(it, Layout);
1317 for (unsigned int i = 0; i < Pad; ++i)
1318 Write8(0);
1319 }
1320
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001321 // Write the extra padding.
1322 WriteZeros(SectionDataPadding);
1323
1324 // Write the relocation entries.
1325 for (MCAssembler::const_iterator it = Asm.begin(),
1326 ie = Asm.end(); it != ie; ++it) {
1327 // Write the section relocation entries, in reverse order to match 'as'
1328 // (approximately, the exact algorithm is more complicated than this).
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +00001329 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001330 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1331 Write32(Relocs[e - i - 1].Word0);
1332 Write32(Relocs[e - i - 1].Word1);
1333 }
1334 }
1335
1336 // Write the symbol table data, if used.
1337 if (NumSymbols) {
1338 // Write the indirect symbol entries.
1339 for (MCAssembler::const_indirect_symbol_iterator
1340 it = Asm.indirect_symbol_begin(),
1341 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1342 // Indirect symbols in the non lazy symbol pointer section have some
1343 // special handling.
1344 const MCSectionMachO &Section =
1345 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1346 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1347 // If this symbol is defined and internal, mark it as such.
1348 if (it->Symbol->isDefined() &&
1349 !Asm.getSymbolData(*it->Symbol).isExternal()) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +00001350 uint32_t Flags = macho::ISF_Local;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001351 if (it->Symbol->isAbsolute())
Daniel Dunbarf52788f2010-11-27 04:59:14 +00001352 Flags |= macho::ISF_Absolute;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001353 Write32(Flags);
1354 continue;
1355 }
1356 }
1357
1358 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1359 }
1360
1361 // FIXME: Check that offsets match computed ones.
1362
1363 // Write the symbol table entries.
1364 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001365 WriteNlist(LocalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001366 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001367 WriteNlist(ExternalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001368 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001369 WriteNlist(UndefinedSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001370
1371 // Write the string table.
1372 OS << StringTable.str();
1373 }
1374 }
1375};
1376
1377}
1378
Daniel Dunbarae5abd52010-12-16 16:09:19 +00001379MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
Daniel Dunbar5d05d972010-12-16 17:21:02 +00001380 raw_ostream &OS,
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001381 bool IsLittleEndian) {
Daniel Dunbar5d05d972010-12-16 17:21:02 +00001382 return new MachObjectWriter(MOTW, OS, IsLittleEndian);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001383}