blob: cab64521afb189c76f16aa6c9cd4bf380bce4179 [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.
Daniel Dunbar294e6782010-12-22 16:19:24 +000027#include "../Target/ARM/ARMFixupKinds.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000028#include "../Target/X86/X86FixupKinds.h"
29
30#include <vector>
31using namespace llvm;
Daniel Dunbar821ecd72010-11-27 04:19:38 +000032using namespace llvm::object;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000033
Rafael Espindolaa8c02c32010-09-30 03:11:42 +000034// FIXME: this has been copied from (or to) X86AsmBackend.cpp
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000035static unsigned getFixupKindLog2Size(unsigned Kind) {
36 switch (Kind) {
Daniel Dunbar5cc63902010-12-22 16:32:41 +000037 default:
38 llvm_unreachable("invalid fixup kind!");
Rafael Espindolae04ed7e2010-11-28 14:17:56 +000039 case FK_PCRel_1:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000040 case FK_Data_1: return 0;
Rafael Espindolae04ed7e2010-11-28 14:17:56 +000041 case FK_PCRel_2:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000042 case FK_Data_2: return 1;
Rafael Espindolae04ed7e2010-11-28 14:17:56 +000043 case FK_PCRel_4:
Daniel Dunbar5cc63902010-12-22 16:32:41 +000044 // FIXME: Remove these!!!
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000045 case X86::reloc_riprel_4byte:
Daniel Dunbar602b40f2010-03-19 18:07:55 +000046 case X86::reloc_riprel_4byte_movq_load:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +000047 case X86::reloc_signed_4byte:
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000048 case FK_Data_4: return 2;
49 case FK_Data_8: return 3;
50 }
51}
52
Daniel Dunbare9460ec2010-05-10 23:15:13 +000053static bool doesSymbolRequireExternRelocation(MCSymbolData *SD) {
54 // Undefined symbols are always extern.
55 if (SD->Symbol->isUndefined())
56 return true;
57
58 // References to weak definitions require external relocation entries; the
59 // definition may not always be the one in the same object file.
60 if (SD->getFlags() & SF_WeakDefinition)
61 return true;
62
63 // Otherwise, we can use an internal relocation.
64 return false;
65}
66
Rafael Espindola70703872010-09-30 02:22:20 +000067static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
68 const MCValue Target,
69 const MCSymbolData *BaseSymbol) {
70 // The effective fixup address is
71 // addr(atom(A)) + offset(A)
72 // - addr(atom(B)) - offset(B)
73 // - addr(BaseSymbol) + <fixup offset from base symbol>
74 // and the offsets are not relocatable, so the fixup is fully resolved when
75 // addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
76 //
77 // Note that "false" is almost always conservatively correct (it means we emit
78 // a relocation which is unnecessary), except when it would force us to emit a
79 // relocation which the target cannot encode.
80
81 const MCSymbolData *A_Base = 0, *B_Base = 0;
82 if (const MCSymbolRefExpr *A = Target.getSymA()) {
83 // Modified symbol references cannot be resolved.
84 if (A->getKind() != MCSymbolRefExpr::VK_None)
85 return false;
86
87 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
88 if (!A_Base)
89 return false;
90 }
91
92 if (const MCSymbolRefExpr *B = Target.getSymB()) {
93 // Modified symbol references cannot be resolved.
94 if (B->getKind() != MCSymbolRefExpr::VK_None)
95 return false;
96
97 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
98 if (!B_Base)
99 return false;
100 }
101
102 // If there is no base, A and B have to be the same atom for this fixup to be
103 // fully resolved.
104 if (!BaseSymbol)
105 return A_Base == B_Base;
106
107 // Otherwise, B must be missing and A must be the base.
108 return !B_Base && BaseSymbol == A_Base;
109}
110
111static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
112 const MCValue Target,
113 const MCSection *BaseSection) {
114 // The effective fixup address is
115 // addr(atom(A)) + offset(A)
116 // - addr(atom(B)) - offset(B)
117 // - addr(<base symbol>) + <fixup offset from base symbol>
118 // and the offsets are not relocatable, so the fixup is fully resolved when
119 // addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
120 //
121 // The simple (Darwin, except on x86_64) way of dealing with this was to
122 // assume that any reference to a temporary symbol *must* be a temporary
123 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
124 // relocation to a temporary symbol (in the same section) is fully
125 // resolved. This also works in conjunction with absolutized .set, which
126 // requires the compiler to use .set to absolutize the differences between
127 // symbols which the compiler knows to be assembly time constants, so we don't
128 // need to worry about considering symbol differences fully resolved.
129
130 // Non-relative fixups are only resolved if constant.
131 if (!BaseSection)
132 return Target.isAbsolute();
133
134 // Otherwise, relative fixups are only resolved if not a difference and the
135 // target is a temporary in the same section.
136 if (Target.isAbsolute() || Target.getSymB())
137 return false;
138
139 const MCSymbol *A = &Target.getSymA()->getSymbol();
140 if (!A->isTemporary() || !A->isInSection() ||
141 &A->getSection() != BaseSection)
142 return false;
143
144 return true;
145}
146
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000147namespace {
148
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000149class MachObjectWriter : public MCObjectWriter {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000150 /// MachSymbolData - Helper struct for containing some precomputed information
151 /// on symbols.
152 struct MachSymbolData {
153 MCSymbolData *SymbolData;
154 uint64_t StringIndex;
155 uint8_t SectionIndex;
156
157 // Support lexicographic sorting.
158 bool operator<(const MachSymbolData &RHS) const {
Benjamin Kramerc37791e2010-05-20 14:14:22 +0000159 return SymbolData->getSymbol().getName() <
160 RHS.SymbolData->getSymbol().getName();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000161 }
162 };
163
Daniel Dunbarae5abd52010-12-16 16:09:19 +0000164 /// The target specific Mach-O writer instance.
165 llvm::OwningPtr<MCMachObjectTargetWriter> TargetObjectWriter;
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000166
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000167 /// @name Relocation Data
168 /// @{
169
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000170 llvm::DenseMap<const MCSectionData*,
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000171 std::vector<macho::RelocationEntry> > Relocations;
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000172 llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000173
174 /// @}
175 /// @name Symbol Table Data
176 /// @{
177
178 SmallString<256> StringTable;
179 std::vector<MachSymbolData> LocalSymbolData;
180 std::vector<MachSymbolData> ExternalSymbolData;
181 std::vector<MachSymbolData> UndefinedSymbolData;
182
183 /// @}
184
Daniel Dunbarae5abd52010-12-16 16:09:19 +0000185private:
186 /// @name Utility Methods
187 /// @{
188
189 bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
190 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
191 (MCFixupKind) Kind);
192
193 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
194 }
195
196 /// @}
197
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000198 SectionAddrMap SectionAddress;
199 uint64_t getSectionAddress(const MCSectionData* SD) const {
200 return SectionAddress.lookup(SD);
201 }
202 uint64_t getSymbolAddress(const MCSymbolData* SD,
203 const MCAsmLayout &Layout) const {
204 return getSectionAddress(SD->getFragment()->getParent()) +
205 Layout.getSymbolOffset(SD);
206 }
207 uint64_t getFragmentAddress(const MCFragment *Fragment,
208 const MCAsmLayout &Layout) const {
209 return getSectionAddress(Fragment->getParent()) +
210 Layout.getFragmentOffset(Fragment);
211 }
212
213 uint64_t getPaddingSize(const MCSectionData *SD,
214 const MCAsmLayout &Layout) const {
215 uint64_t EndAddr = getSectionAddress(SD) + Layout.getSectionAddressSize(SD);
216 unsigned Next = SD->getLayoutOrder() + 1;
217 if (Next >= Layout.getSectionOrder().size())
218 return 0;
219
220 const MCSectionData &NextSD = *Layout.getSectionOrder()[Next];
221 if (NextSD.getSection().isVirtualSection())
222 return 0;
223 return OffsetToAlignment(EndAddr, NextSD.getAlignment());
224 }
225
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000226public:
Daniel Dunbarae5abd52010-12-16 16:09:19 +0000227 MachObjectWriter(MCMachObjectTargetWriter *MOTW, raw_ostream &_OS,
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000228 bool _IsLittleEndian)
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000229 : MCObjectWriter(_OS, _IsLittleEndian), TargetObjectWriter(MOTW) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000230 }
231
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000232 /// @name Target Writer Proxy Accessors
233 /// @{
234
235 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Daniel Dunbar532c4562010-12-22 13:49:43 +0000236 bool isARM() const {
Daniel Dunbarfdfbc6a2010-12-22 16:19:20 +0000237 uint32_t CPUType = TargetObjectWriter->getCPUType() & ~mach::CTFM_ArchMask;
Daniel Dunbar532c4562010-12-22 13:49:43 +0000238 return CPUType == mach::CTM_ARM;
239 }
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000240
241 /// @}
242
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000243 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
244 bool SubsectionsViaSymbols) {
245 uint32_t Flags = 0;
246
247 if (SubsectionsViaSymbols)
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000248 Flags |= macho::HF_SubsectionsViaSymbols;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000249
250 // struct mach_header (28 bytes) or
251 // struct mach_header_64 (32 bytes)
252
253 uint64_t Start = OS.tell();
254 (void) Start;
255
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000256 Write32(is64Bit() ? macho::HM_Object64 : macho::HM_Object32);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000257
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000258 Write32(TargetObjectWriter->getCPUType());
259 Write32(TargetObjectWriter->getCPUSubtype());
Jim Grosbachc9d14392010-11-05 18:48:58 +0000260
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000261 Write32(macho::HFT_Object);
Daniel Dunbar590956f2010-11-27 07:39:37 +0000262 Write32(NumLoadCommands);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000263 Write32(LoadCommandsSize);
264 Write32(Flags);
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000265 if (is64Bit())
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000266 Write32(0); // reserved
267
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000268 assert(OS.tell() - Start == is64Bit() ?
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000269 macho::Header64Size : macho::Header32Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000270 }
271
272 /// WriteSegmentLoadCommand - Write a segment load command.
273 ///
274 /// \arg NumSections - The number of sections in this segment.
275 /// \arg SectionDataSize - The total size of the sections.
276 void WriteSegmentLoadCommand(unsigned NumSections,
277 uint64_t VMSize,
278 uint64_t SectionDataStartOffset,
279 uint64_t SectionDataSize) {
280 // struct segment_command (56 bytes) or
281 // struct segment_command_64 (72 bytes)
282
283 uint64_t Start = OS.tell();
284 (void) Start;
285
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000286 unsigned SegmentLoadCommandSize =
287 is64Bit() ? macho::SegmentLoadCommand64Size:
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000288 macho::SegmentLoadCommand32Size;
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000289 Write32(is64Bit() ? macho::LCT_Segment64 : macho::LCT_Segment);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000290 Write32(SegmentLoadCommandSize +
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000291 NumSections * (is64Bit() ? macho::Section64Size :
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000292 macho::Section32Size));
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000293
294 WriteBytes("", 16);
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000295 if (is64Bit()) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000296 Write64(0); // vmaddr
297 Write64(VMSize); // vmsize
298 Write64(SectionDataStartOffset); // file offset
299 Write64(SectionDataSize); // file size
300 } else {
301 Write32(0); // vmaddr
302 Write32(VMSize); // vmsize
303 Write32(SectionDataStartOffset); // file offset
304 Write32(SectionDataSize); // file size
305 }
306 Write32(0x7); // maxprot
307 Write32(0x7); // initprot
308 Write32(NumSections);
309 Write32(0); // flags
310
311 assert(OS.tell() - Start == SegmentLoadCommandSize);
312 }
313
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000314 void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
315 const MCSectionData &SD, uint64_t FileOffset,
316 uint64_t RelocationsStart, unsigned NumRelocations) {
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000317 uint64_t SectionSize = Layout.getSectionAddressSize(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +0000318
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000319 // The offset is unused for virtual sections.
Rafael Espindolaf2dc4aa2010-11-17 20:03:54 +0000320 if (SD.getSection().isVirtualSection()) {
Daniel Dunbarb026d642010-03-25 07:10:05 +0000321 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000322 FileOffset = 0;
323 }
324
325 // struct section (68 bytes) or
326 // struct section_64 (80 bytes)
327
328 uint64_t Start = OS.tell();
329 (void) Start;
330
Daniel Dunbar56279f42010-05-18 17:28:20 +0000331 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000332 WriteBytes(Section.getSectionName(), 16);
333 WriteBytes(Section.getSegmentName(), 16);
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000334 if (is64Bit()) {
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000335 Write64(getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000336 Write64(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000337 } else {
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000338 Write32(getSectionAddress(&SD)); // address
Daniel Dunbar5d428512010-03-25 02:00:07 +0000339 Write32(SectionSize); // size
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000340 }
341 Write32(FileOffset);
342
343 unsigned Flags = Section.getTypeAndAttributes();
344 if (SD.hasInstructions())
345 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
346
347 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
348 Write32(Log2_32(SD.getAlignment()));
349 Write32(NumRelocations ? RelocationsStart : 0);
350 Write32(NumRelocations);
351 Write32(Flags);
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +0000352 Write32(IndirectSymBase.lookup(&SD)); // reserved1
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000353 Write32(Section.getStubSize()); // reserved2
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000354 if (is64Bit())
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000355 Write32(0); // reserved3
356
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000357 assert(OS.tell() - Start == is64Bit() ? macho::Section64Size :
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000358 macho::Section32Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000359 }
360
361 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
362 uint32_t StringTableOffset,
363 uint32_t StringTableSize) {
364 // struct symtab_command (24 bytes)
365
366 uint64_t Start = OS.tell();
367 (void) Start;
368
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000369 Write32(macho::LCT_Symtab);
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000370 Write32(macho::SymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000371 Write32(SymbolOffset);
372 Write32(NumSymbols);
373 Write32(StringTableOffset);
374 Write32(StringTableSize);
375
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000376 assert(OS.tell() - Start == macho::SymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000377 }
378
379 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
380 uint32_t NumLocalSymbols,
381 uint32_t FirstExternalSymbol,
382 uint32_t NumExternalSymbols,
383 uint32_t FirstUndefinedSymbol,
384 uint32_t NumUndefinedSymbols,
385 uint32_t IndirectSymbolOffset,
386 uint32_t NumIndirectSymbols) {
387 // struct dysymtab_command (80 bytes)
388
389 uint64_t Start = OS.tell();
390 (void) Start;
391
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000392 Write32(macho::LCT_Dysymtab);
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000393 Write32(macho::DysymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000394 Write32(FirstLocalSymbol);
395 Write32(NumLocalSymbols);
396 Write32(FirstExternalSymbol);
397 Write32(NumExternalSymbols);
398 Write32(FirstUndefinedSymbol);
399 Write32(NumUndefinedSymbols);
400 Write32(0); // tocoff
401 Write32(0); // ntoc
402 Write32(0); // modtaboff
403 Write32(0); // nmodtab
404 Write32(0); // extrefsymoff
405 Write32(0); // nextrefsyms
406 Write32(IndirectSymbolOffset);
407 Write32(NumIndirectSymbols);
408 Write32(0); // extreloff
409 Write32(0); // nextrel
410 Write32(0); // locreloff
411 Write32(0); // nlocrel
412
Daniel Dunbar821ecd72010-11-27 04:19:38 +0000413 assert(OS.tell() - Start == macho::DysymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000414 }
415
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000416 void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000417 MCSymbolData &Data = *MSD.SymbolData;
418 const MCSymbol &Symbol = Data.getSymbol();
419 uint8_t Type = 0;
420 uint16_t Flags = Data.getFlags();
421 uint32_t Address = 0;
422
423 // Set the N_TYPE bits. See <mach-o/nlist.h>.
424 //
425 // FIXME: Are the prebound or indirect fields possible here?
426 if (Symbol.isUndefined())
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000427 Type = macho::STT_Undefined;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000428 else if (Symbol.isAbsolute())
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000429 Type = macho::STT_Absolute;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000430 else
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000431 Type = macho::STT_Section;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000432
433 // FIXME: Set STAB bits.
434
435 if (Data.isPrivateExtern())
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000436 Type |= macho::STF_PrivateExtern;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000437
438 // Set external bit.
439 if (Data.isExternal() || Symbol.isUndefined())
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000440 Type |= macho::STF_External;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000441
442 // Compute the symbol address.
443 if (Symbol.isDefined()) {
444 if (Symbol.isAbsolute()) {
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000445 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000446 } else {
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000447 Address = getSymbolAddress(&Data, Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000448 }
449 } else if (Data.isCommon()) {
450 // Common symbols are encoded with the size in the address
451 // field, and their alignment in the flags.
452 Address = Data.getCommonSize();
453
454 // Common alignment is packed into the 'desc' bits.
455 if (unsigned Align = Data.getCommonAlignment()) {
456 unsigned Log2Size = Log2_32(Align);
457 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
458 if (Log2Size > 15)
Chris Lattner75361b62010-04-07 22:58:41 +0000459 report_fatal_error("invalid 'common' alignment '" +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000460 Twine(Align) + "'");
461 // FIXME: Keep this mask with the SymbolFlags enumeration.
462 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
463 }
464 }
465
466 // struct nlist (12 bytes)
467
468 Write32(MSD.StringIndex);
469 Write8(Type);
470 Write8(MSD.SectionIndex);
471
472 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
473 // value.
474 Write16(Flags);
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000475 if (is64Bit())
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000476 Write64(Address);
477 else
478 Write32(Address);
479 }
480
Daniel Dunbar35b06572010-03-22 23:16:43 +0000481 // FIXME: We really need to improve the relocation validation. Basically, we
482 // want to implement a separate computation which evaluates the relocation
483 // entry as the linker would, and verifies that the resultant fixup value is
484 // exactly what the encoder wanted. This will catch several classes of
485 // problems:
486 //
487 // - Relocation entry bugs, the two algorithms are unlikely to have the same
488 // exact bug.
489 //
490 // - Relaxation issues, where we forget to relax something.
491 //
492 // - Input errors, where something cannot be correctly encoded. 'as' allows
493 // these through in many cases.
494
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000495 static bool isFixupKindRIPRel(unsigned Kind) {
496 return Kind == X86::reloc_riprel_4byte ||
497 Kind == X86::reloc_riprel_4byte_movq_load;
498 }
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000499 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000500 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000501 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000502 uint64_t &FixedValue) {
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000503 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Daniel Dunbar482ad802010-05-26 15:18:31 +0000504 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
505 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000506
507 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000508 uint32_t FixupOffset =
509 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
510 uint32_t FixupAddress =
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000511 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000512 int64_t Value = 0;
513 unsigned Index = 0;
514 unsigned IsExtern = 0;
515 unsigned Type = 0;
516
517 Value = Target.getConstant();
518
519 if (IsPCRel) {
520 // Compensate for the relocation offset, Darwin x86_64 relocations only
521 // have the addend and appear to have attempted to define it to be the
522 // actual expression addend without the PCrel bias. However, instructions
523 // with data following the relocation are not accomodated for (see comment
524 // below regarding SIGNED{1,2,4}), so it isn't exactly that either.
Benjamin Kramer454c4ce2010-04-08 15:25:57 +0000525 Value += 1LL << Log2Size;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000526 }
527
528 if (Target.isAbsolute()) { // constant
529 // SymbolNum of 0 indicates the absolute section.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000530 Type = macho::RIT_X86_64_Unsigned;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000531 Index = 0;
532
533 // FIXME: I believe this is broken, I don't think the linker can
534 // understand it. I think it would require a local relocation, but I'm not
535 // sure if that would work either. The official way to get an absolute
536 // PCrel relocation is to use an absolute symbol (which we don't support
537 // yet).
538 if (IsPCRel) {
539 IsExtern = 1;
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000540 Type = macho::RIT_X86_64_Branch;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000541 }
542 } else if (Target.getSymB()) { // A - B + constant
543 const MCSymbol *A = &Target.getSymA()->getSymbol();
544 MCSymbolData &A_SD = Asm.getSymbolData(*A);
Rafael Espindolab8141102010-09-27 18:13:03 +0000545 const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000546
547 const MCSymbol *B = &Target.getSymB()->getSymbol();
548 MCSymbolData &B_SD = Asm.getSymbolData(*B);
Rafael Espindolab8141102010-09-27 18:13:03 +0000549 const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000550
551 // Neither symbol can be modified.
552 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
553 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000554 report_fatal_error("unsupported relocation of modified symbol");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000555
556 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
557 // implement most of these correctly.
558 if (IsPCRel)
Chris Lattner75361b62010-04-07 22:58:41 +0000559 report_fatal_error("unsupported pc-relative relocation of difference");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000560
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000561 // The support for the situation where one or both of the symbols would
562 // require a local relocation is handled just like if the symbols were
563 // external. This is certainly used in the case of debug sections where
564 // the section has only temporary symbols and thus the symbols don't have
565 // base symbols. This is encoded using the section ordinal and
566 // non-extern relocation entries.
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000567
568 // Darwin 'as' doesn't emit correct relocations for this (it ends up with
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000569 // a single SIGNED relocation); reject it for now. Except the case where
570 // both symbols don't have a base, equal but both NULL.
571 if (A_Base == B_Base && A_Base)
Chris Lattner75361b62010-04-07 22:58:41 +0000572 report_fatal_error("unsupported relocation with identical base");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000573
Rafael Espindolaf10d2be2010-12-07 01:09:54 +0000574 Value += getSymbolAddress(&A_SD, Layout) -
575 (A_Base == NULL ? 0 : getSymbolAddress(A_Base, Layout));
576 Value -= getSymbolAddress(&B_SD, Layout) -
577 (B_Base == NULL ? 0 : getSymbolAddress(B_Base, Layout));
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000578
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000579 if (A_Base) {
580 Index = A_Base->getIndex();
581 IsExtern = 1;
582 }
583 else {
584 Index = A_SD.getFragment()->getParent()->getOrdinal() + 1;
585 IsExtern = 0;
586 }
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000587 Type = macho::RIT_X86_64_Unsigned;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000588
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000589 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000590 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000591 MRE.Word1 = ((Index << 0) |
592 (IsPCRel << 24) |
593 (Log2Size << 25) |
594 (IsExtern << 27) |
595 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000596 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000597
Kevin Enderby8c9aa922010-10-02 00:13:41 +0000598 if (B_Base) {
599 Index = B_Base->getIndex();
600 IsExtern = 1;
601 }
602 else {
603 Index = B_SD.getFragment()->getParent()->getOrdinal() + 1;
604 IsExtern = 0;
605 }
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000606 Type = macho::RIT_X86_64_Subtractor;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000607 } else {
608 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
609 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
Rafael Espindolab8141102010-09-27 18:13:03 +0000610 const MCSymbolData *Base = Asm.getAtom(&SD);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000611
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000612 // Relocations inside debug sections always use local relocations when
613 // possible. This seems to be done because the debugger doesn't fully
614 // understand x86_64 relocation entries, and expects to find values that
615 // have already been fixed up.
Daniel Dunbar2d7fd612010-05-05 19:01:05 +0000616 if (Symbol->isInSection()) {
Daniel Dunbarae7fb0b2010-05-05 17:22:39 +0000617 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
618 Fragment->getParent()->getSection());
619 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
620 Base = 0;
621 }
622
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000623 // x86_64 almost always uses external relocations, except when there is no
624 // symbol to use as a base address (a local symbol with no preceeding
625 // non-local symbol).
626 if (Base) {
627 Index = Base->getIndex();
628 IsExtern = 1;
629
630 // Add the local offset, if needed.
631 if (Base != &SD)
Rafael Espindola1dda29b2010-12-06 21:51:55 +0000632 Value += Layout.getSymbolOffset(&SD) - Layout.getSymbolOffset(Base);
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000633 } else if (Symbol->isInSection()) {
Daniel Dunbar8fb04032010-03-25 08:08:54 +0000634 // The index is the section ordinal (1-based).
635 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000636 IsExtern = 0;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000637 Value += getSymbolAddress(&SD, Layout);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000638
639 if (IsPCRel)
Daniel Dunbardb4c7e62010-05-11 23:53:11 +0000640 Value -= FixupAddress + (1 << Log2Size);
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000641 } else if (Symbol->isVariable()) {
642 const MCExpr *Value = Symbol->getVariableValue();
643 int64_t Res;
644 bool isAbs = Value->EvaluateAsAbsolute(Res, Layout, SectionAddress);
645 if (isAbs) {
646 FixedValue = Res;
647 return;
648 } else {
649 report_fatal_error("unsupported relocation of variable '" +
650 Symbol->getName() + "'");
651 }
Daniel Dunbaref4591e2010-05-11 23:53:05 +0000652 } else {
653 report_fatal_error("unsupported relocation of undefined symbol '" +
654 Symbol->getName() + "'");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000655 }
656
657 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
658 if (IsPCRel) {
659 if (IsRIPRel) {
660 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
661 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
662 // rewrite the movq to an leaq at link time if the symbol ends up in
663 // the same linkage unit.
Daniel Dunbar482ad802010-05-26 15:18:31 +0000664 if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000665 Type = macho::RIT_X86_64_GOTLoad;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000666 else
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000667 Type = macho::RIT_X86_64_GOT;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000668 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000669 Type = macho::RIT_X86_64_TLV;
Eric Christopheraeed4d82010-05-27 00:52:31 +0000670 } else if (Modifier != MCSymbolRefExpr::VK_None) {
671 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000672 } else {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000673 Type = macho::RIT_X86_64_Signed;
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000674
675 // The Darwin x86_64 relocation format has a problem where it cannot
676 // encode an address (L<foo> + <constant>) which is outside the atom
677 // containing L<foo>. Generally, this shouldn't occur but it does
678 // happen when we have a RIPrel instruction with data following the
679 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
680 // adjustment Darwin x86_64 uses, the offset is still negative and
681 // the linker has no way to recognize this.
682 //
683 // To work around this, Darwin uses several special relocation types
684 // to indicate the offsets. However, the specification or
685 // implementation of these seems to also be incomplete; they should
686 // adjust the addend as well based on the actual encoded instruction
687 // (the additional bias), but instead appear to just look at the
688 // final offset.
689 switch (-(Target.getConstant() + (1LL << Log2Size))) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000690 case 1: Type = macho::RIT_X86_64_Signed1; break;
691 case 2: Type = macho::RIT_X86_64_Signed2; break;
692 case 4: Type = macho::RIT_X86_64_Signed4; break;
Daniel Dunbarf0f6cdb2010-05-14 18:53:40 +0000693 }
694 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000695 } else {
696 if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000697 report_fatal_error("unsupported symbol modifier in branch "
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000698 "relocation");
699
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000700 Type = macho::RIT_X86_64_Branch;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000701 }
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000702 } else {
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000703 if (Modifier == MCSymbolRefExpr::VK_GOT) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000704 Type = macho::RIT_X86_64_GOT;
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000705 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
706 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in
707 // which case all we do is set the PCrel bit in the relocation entry;
708 // this is used with exception handling, for example. The source is
709 // required to include any necessary offset directly.
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000710 Type = macho::RIT_X86_64_GOT;
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000711 IsPCRel = 1;
Eric Christopher96ac5152010-05-26 00:02:12 +0000712 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
713 report_fatal_error("TLVP symbol modifier should have been rip-rel");
Daniel Dunbar1de558b2010-03-29 23:56:40 +0000714 } else if (Modifier != MCSymbolRefExpr::VK_None)
Chris Lattner75361b62010-04-07 22:58:41 +0000715 report_fatal_error("unsupported symbol modifier in relocation");
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000716 else
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000717 Type = macho::RIT_X86_64_Unsigned;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000718 }
719 }
720
721 // x86_64 always writes custom values into the fixups.
722 FixedValue = Value;
723
724 // struct relocation_info (8 bytes)
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000725 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000726 MRE.Word0 = FixupOffset;
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000727 MRE.Word1 = ((Index << 0) |
728 (IsPCRel << 24) |
729 (Log2Size << 25) |
730 (IsExtern << 27) |
731 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +0000732 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000733 }
734
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000735 void RecordScatteredRelocation(const MCAssembler &Asm,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000736 const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000737 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000738 const MCFixup &Fixup, MCValue Target,
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000739 uint64_t &FixedValue) {
Daniel Dunbar482ad802010-05-26 15:18:31 +0000740 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000741 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Daniel Dunbar482ad802010-05-26 15:18:31 +0000742 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000743 unsigned Type = macho::RIT_Vanilla;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000744
745 // See <reloc.h>.
746 const MCSymbol *A = &Target.getSymA()->getSymbol();
747 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
748
749 if (!A_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000750 report_fatal_error("symbol '" + A->getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000751 "' can not be undefined in a subtraction expression");
752
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000753 uint32_t Value = getSymbolAddress(A_SD, Layout);
754 uint64_t SecAddr = getSectionAddress(A_SD->getFragment()->getParent());
755 FixedValue += SecAddr;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000756 uint32_t Value2 = 0;
757
758 if (const MCSymbolRefExpr *B = Target.getSymB()) {
759 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
760
761 if (!B_SD->getFragment())
Chris Lattner75361b62010-04-07 22:58:41 +0000762 report_fatal_error("symbol '" + B->getSymbol().getName() +
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000763 "' can not be undefined in a subtraction expression");
764
765 // Select the appropriate difference relocation type.
766 //
767 // Note that there is no longer any semantic difference between these two
768 // relocation types from the linkers point of view, this is done solely
769 // for pedantic compatibility with 'as'.
Matt Beaumont-Gaye733cf82010-12-21 23:43:23 +0000770 Type = A_SD->isExternal() ? (unsigned)macho::RIT_Difference :
771 (unsigned)macho::RIT_Generic_LocalDifference;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000772 Value2 = getSymbolAddress(B_SD, Layout);
773 FixedValue -= getSectionAddress(B_SD->getFragment()->getParent());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000774 }
775
776 // Relocations are written out in reverse order, so the PAIR comes first.
Daniel Dunbare1feeb92010-12-21 15:26:45 +0000777 if (Type == macho::RIT_Difference ||
778 Type == macho::RIT_Generic_LocalDifference) {
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000779 macho::RelocationEntry MRE;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000780 MRE.Word0 = ((0 << 0) |
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000781 (macho::RIT_Pair << 24) |
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000782 (Log2Size << 28) |
783 (IsPCRel << 30) |
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000784 macho::RF_Scattered);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000785 MRE.Word1 = Value2;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000786 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000787 }
788
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000789 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +0000790 MRE.Word0 = ((FixupOffset << 0) |
791 (Type << 24) |
792 (Log2Size << 28) |
793 (IsPCRel << 30) |
Daniel Dunbarf52788f2010-11-27 04:59:14 +0000794 macho::RF_Scattered);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000795 MRE.Word1 = Value;
Daniel Dunbarb7514182010-03-22 20:35:50 +0000796 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000797 }
798
Daniel Dunbar25bcc9c2010-12-22 16:45:29 +0000799 void RecordARMScatteredRelocation(const MCAssembler &Asm,
800 const MCAsmLayout &Layout,
801 const MCFragment *Fragment,
802 const MCFixup &Fixup, MCValue Target,
803 uint64_t &FixedValue) {
804 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
805 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
806 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
807 unsigned Type = macho::RIT_Vanilla;
808
809 // See <reloc.h>.
810 const MCSymbol *A = &Target.getSymA()->getSymbol();
811 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
812
813 if (!A_SD->getFragment())
814 report_fatal_error("symbol '" + A->getName() +
815 "' can not be undefined in a subtraction expression");
816
817 uint32_t Value = getSymbolAddress(A_SD, Layout);
818 uint64_t SecAddr = getSectionAddress(A_SD->getFragment()->getParent());
819 FixedValue += SecAddr;
820 uint32_t Value2 = 0;
821
822 if (const MCSymbolRefExpr *B = Target.getSymB()) {
823 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
824
825 if (!B_SD->getFragment())
826 report_fatal_error("symbol '" + B->getSymbol().getName() +
827 "' can not be undefined in a subtraction expression");
828
829 // Select the appropriate difference relocation type.
Daniel Dunbardf561e02010-12-22 16:52:19 +0000830 Type = macho::RIT_Difference;
Daniel Dunbar25bcc9c2010-12-22 16:45:29 +0000831 Value2 = getSymbolAddress(B_SD, Layout);
832 FixedValue -= getSectionAddress(B_SD->getFragment()->getParent());
833 }
834
835 // Relocations are written out in reverse order, so the PAIR comes first.
836 if (Type == macho::RIT_Difference ||
837 Type == macho::RIT_Generic_LocalDifference) {
838 macho::RelocationEntry MRE;
839 MRE.Word0 = ((0 << 0) |
840 (macho::RIT_Pair << 24) |
841 (Log2Size << 28) |
842 (IsPCRel << 30) |
843 macho::RF_Scattered);
844 MRE.Word1 = Value2;
845 Relocations[Fragment->getParent()].push_back(MRE);
846 }
847
848 macho::RelocationEntry MRE;
849 MRE.Word0 = ((FixupOffset << 0) |
850 (Type << 24) |
851 (Log2Size << 28) |
852 (IsPCRel << 30) |
853 macho::RF_Scattered);
854 MRE.Word1 = Value;
855 Relocations[Fragment->getParent()].push_back(MRE);
856 }
857
Eric Christopherc9ada472010-06-15 22:59:05 +0000858 void RecordTLVPRelocation(const MCAssembler &Asm,
Eric Christophere48dbf82010-06-16 00:26:36 +0000859 const MCAsmLayout &Layout,
860 const MCFragment *Fragment,
861 const MCFixup &Fixup, MCValue Target,
862 uint64_t &FixedValue) {
Eric Christopherc9ada472010-06-15 22:59:05 +0000863 assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000864 !is64Bit() &&
Eric Christopherc9ada472010-06-15 22:59:05 +0000865 "Should only be called with a 32-bit TLVP relocation!");
866
Eric Christopherc9ada472010-06-15 22:59:05 +0000867 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
868 uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
869 unsigned IsPCRel = 0;
870
871 // Get the symbol data.
872 MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
873 unsigned Index = SD_A->getIndex();
874
Eric Christopherbc067372010-06-16 21:32:38 +0000875 // We're only going to have a second symbol in pic mode and it'll be a
876 // subtraction from the picbase. For 32-bit pic the addend is the difference
Eric Christopher04b8d3c2010-06-17 00:49:46 +0000877 // between the picbase and the next address. For 32-bit static the addend
878 // is zero.
Eric Christopherbc067372010-06-16 21:32:38 +0000879 if (Target.getSymB()) {
Eric Christopher1008d352010-06-22 23:51:47 +0000880 // If this is a subtraction then we're pcrel.
881 uint32_t FixupAddress =
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000882 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
Eric Christopher1008d352010-06-22 23:51:47 +0000883 MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
Eric Christopherc9ada472010-06-15 22:59:05 +0000884 IsPCRel = 1;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000885 FixedValue = (FixupAddress - getSymbolAddress(SD_B, Layout) +
Eric Christopher1008d352010-06-22 23:51:47 +0000886 Target.getConstant());
Chris Lattnerabf8f9c2010-08-16 16:35:20 +0000887 FixedValue += 1ULL << Log2Size;
Eric Christopherbc067372010-06-16 21:32:38 +0000888 } else {
889 FixedValue = 0;
890 }
Jim Grosbach3c384922010-11-11 20:16:23 +0000891
Eric Christopherc9ada472010-06-15 22:59:05 +0000892 // struct relocation_info (8 bytes)
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +0000893 macho::RelocationEntry MRE;
Eric Christopherc9ada472010-06-15 22:59:05 +0000894 MRE.Word0 = Value;
Daniel Dunbare1feeb92010-12-21 15:26:45 +0000895 MRE.Word1 = ((Index << 0) |
896 (IsPCRel << 24) |
897 (Log2Size << 25) |
898 (1 << 27) | // Extern
899 (macho::RIT_Generic_TLV << 28)); // Type
Eric Christopherc9ada472010-06-15 22:59:05 +0000900 Relocations[Fragment->getParent()].push_back(MRE);
901 }
Jim Grosbach3c384922010-11-11 20:16:23 +0000902
Daniel Dunbar294e6782010-12-22 16:19:24 +0000903 static bool getARMFixupKindMachOInfo(unsigned Kind, bool &Is24BitBranch,
904 unsigned &Log2Size) {
Daniel Dunbar36645642010-12-22 16:32:37 +0000905 Is24BitBranch = false;
906 Log2Size = ~0U;
907
Daniel Dunbar294e6782010-12-22 16:19:24 +0000908 switch (Kind) {
909 default:
910 return false;
911
Daniel Dunbar36645642010-12-22 16:32:37 +0000912 case FK_Data_1:
913 Log2Size = llvm::Log2_32(1);
914 return true;
915 case FK_Data_2:
916 Log2Size = llvm::Log2_32(2);
917 return true;
918 case FK_Data_4:
919 Log2Size = llvm::Log2_32(4);
920 return true;
921 case FK_Data_8:
922 Log2Size = llvm::Log2_32(8);
923 return true;
924
Daniel Dunbar294e6782010-12-22 16:19:24 +0000925 // Handle 24-bit branch kinds.
926 case ARM::fixup_arm_ldst_pcrel_12:
927 case ARM::fixup_arm_pcrel_10:
928 case ARM::fixup_arm_adr_pcrel_12:
929 case ARM::fixup_arm_branch:
930 Is24BitBranch = true;
931 // Report as 'long', even though that is not quite accurate.
932 Log2Size = llvm::Log2_32(4);
933 return true;
934 }
935 }
Daniel Dunbar532c4562010-12-22 13:49:43 +0000936 void RecordARMRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
937 const MCFragment *Fragment, const MCFixup &Fixup,
938 MCValue Target, uint64_t &FixedValue) {
Daniel Dunbar4d743052010-12-22 13:50:05 +0000939 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Daniel Dunbar294e6782010-12-22 16:19:24 +0000940 unsigned Log2Size;
941 bool Is24BitBranch;
942 if (!getARMFixupKindMachOInfo(Fixup.getKind(), Is24BitBranch, Log2Size)) {
943 report_fatal_error("unknown ARM fixup kind!");
944 return;
945 }
Daniel Dunbar4d743052010-12-22 13:50:05 +0000946
947 // If this is a difference or a defined symbol plus an offset, then we need
948 // a scattered relocation entry. Differences always require scattered
949 // relocations.
950 if (Target.getSymB())
Daniel Dunbar25bcc9c2010-12-22 16:45:29 +0000951 return RecordARMScatteredRelocation(Asm, Layout, Fragment, Fixup,
952 Target, FixedValue);
Daniel Dunbar4d743052010-12-22 13:50:05 +0000953
954 // Get the symbol data, if any.
955 MCSymbolData *SD = 0;
956 if (Target.getSymA())
957 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
958
959 // FIXME: For other platforms, we need to use scattered relocations for
960 // internal relocations with offsets. If this is an internal relocation
961 // with an offset, it also needs a scattered relocation entry.
962 //
963 // Is this right for ARM?
964 uint32_t Offset = Target.getConstant();
965 if (IsPCRel)
966 Offset += 1 << Log2Size;
967 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
Daniel Dunbar25bcc9c2010-12-22 16:45:29 +0000968 return RecordARMScatteredRelocation(Asm, Layout, Fragment, Fixup,
969 Target, FixedValue);
Daniel Dunbar4d743052010-12-22 13:50:05 +0000970
971 // See <reloc.h>.
972 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
973 unsigned Index = 0;
974 unsigned IsExtern = 0;
975 unsigned Type = 0;
976
977 if (Target.isAbsolute()) { // constant
978 // FIXME!
979 report_fatal_error("FIXME: relocations to absolute targets "
980 "not yet implemented");
981 } else if (SD->getSymbol().isVariable()) {
982 int64_t Res;
983 if (SD->getSymbol().getVariableValue()->EvaluateAsAbsolute(
984 Res, Layout, SectionAddress)) {
985 FixedValue = Res;
986 return;
987 }
988
989 report_fatal_error("unsupported relocation of variable '" +
990 SD->getSymbol().getName() + "'");
991 } else {
992 // Check whether we need an external or internal relocation.
993 if (doesSymbolRequireExternRelocation(SD)) {
994 IsExtern = 1;
995 Index = SD->getIndex();
996 // For external relocations, make sure to offset the fixup value to
997 // compensate for the addend of the symbol address, if it was
998 // undefined. This occurs with weak definitions, for example.
999 if (!SD->Symbol->isUndefined())
1000 FixedValue -= Layout.getSymbolOffset(SD);
1001 } else {
1002 // The index is the section ordinal (1-based).
1003 Index = SD->getFragment()->getParent()->getOrdinal() + 1;
1004 FixedValue += getSectionAddress(SD->getFragment()->getParent());
1005 }
1006 if (IsPCRel)
1007 FixedValue -= getSectionAddress(Fragment->getParent());
1008
Daniel Dunbar294e6782010-12-22 16:19:24 +00001009 // Determine the appropriate type based on the fixup kind.
1010 Type = Is24BitBranch ? macho::RIT_ARM_Branch24Bit : macho::RIT_Vanilla;
Daniel Dunbar4d743052010-12-22 13:50:05 +00001011 }
1012
1013 // struct relocation_info (8 bytes)
1014 macho::RelocationEntry MRE;
1015 MRE.Word0 = FixupOffset;
1016 MRE.Word1 = ((Index << 0) |
1017 (IsPCRel << 24) |
1018 (Log2Size << 25) |
1019 (IsExtern << 27) |
1020 (Type << 28));
1021 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar532c4562010-12-22 13:49:43 +00001022 }
1023
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001024 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +00001025 const MCFragment *Fragment, const MCFixup &Fixup,
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001026 MCValue Target, uint64_t &FixedValue) {
Daniel Dunbar532c4562010-12-22 13:49:43 +00001027 // FIXME: These needs to be factored into the target Mach-O writer.
1028 if (isARM()) {
1029 RecordARMRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
1030 return;
1031 }
Daniel Dunbar5d05d972010-12-16 17:21:02 +00001032 if (is64Bit()) {
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001033 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
Daniel Dunbar602b40f2010-03-19 18:07:55 +00001034 return;
1035 }
1036
Daniel Dunbar7e06af82010-12-16 15:42:31 +00001037 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Daniel Dunbar482ad802010-05-26 15:18:31 +00001038 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001039
Eric Christopherc9ada472010-06-15 22:59:05 +00001040 // If this is a 32-bit TLVP reloc it's handled a bit differently.
Daniel Dunbar23bea412010-09-17 15:21:50 +00001041 if (Target.getSymA() &&
1042 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
Eric Christopherc9ada472010-06-15 22:59:05 +00001043 RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
1044 return;
1045 }
Jim Grosbach3c384922010-11-11 20:16:23 +00001046
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001047 // If this is a difference or a defined symbol plus an offset, then we need
1048 // a scattered relocation entry.
Daniel Dunbara8251fa2010-05-10 23:15:20 +00001049 // Differences always require scattered relocations.
1050 if (Target.getSymB())
1051 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
1052 Target, FixedValue);
1053
1054 // Get the symbol data, if any.
1055 MCSymbolData *SD = 0;
1056 if (Target.getSymA())
1057 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
1058
1059 // If this is an internal relocation with an offset, it also needs a
1060 // scattered relocation entry.
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001061 uint32_t Offset = Target.getConstant();
1062 if (IsPCRel)
1063 Offset += 1 << Log2Size;
Daniel Dunbara8251fa2010-05-10 23:15:20 +00001064 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
1065 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
1066 Target, FixedValue);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001067
1068 // See <reloc.h>.
Daniel Dunbar482ad802010-05-26 15:18:31 +00001069 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001070 unsigned Index = 0;
1071 unsigned IsExtern = 0;
1072 unsigned Type = 0;
1073
1074 if (Target.isAbsolute()) { // constant
1075 // SymbolNum of 0 indicates the absolute section.
1076 //
1077 // FIXME: Currently, these are never generated (see code below). I cannot
1078 // find a case where they are actually emitted.
Daniel Dunbarf52788f2010-11-27 04:59:14 +00001079 Type = macho::RIT_Vanilla;
Rafael Espindola545b77e2010-12-07 17:12:32 +00001080 } else if (SD->getSymbol().isVariable()) {
Rafael Espindola545b77e2010-12-07 17:12:32 +00001081 int64_t Res;
Daniel Dunbar42b52862010-12-22 13:49:56 +00001082 if (SD->getSymbol().getVariableValue()->EvaluateAsAbsolute(
1083 Res, Layout, SectionAddress)) {
Rafael Espindola545b77e2010-12-07 17:12:32 +00001084 FixedValue = Res;
1085 return;
Rafael Espindola545b77e2010-12-07 17:12:32 +00001086 }
Daniel Dunbar42b52862010-12-22 13:49:56 +00001087
1088 report_fatal_error("unsupported relocation of variable '" +
1089 SD->getSymbol().getName() + "'");
Michael J. Spencerb0f3b3e2010-08-10 16:00:49 +00001090 } else {
Daniel Dunbare9460ec2010-05-10 23:15:13 +00001091 // Check whether we need an external or internal relocation.
1092 if (doesSymbolRequireExternRelocation(SD)) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001093 IsExtern = 1;
1094 Index = SD->getIndex();
Daniel Dunbare9460ec2010-05-10 23:15:13 +00001095 // For external relocations, make sure to offset the fixup value to
1096 // compensate for the addend of the symbol address, if it was
1097 // undefined. This occurs with weak definitions, for example.
1098 if (!SD->Symbol->isUndefined())
Rafael Espindola3b3148f2010-12-07 05:57:28 +00001099 FixedValue -= Layout.getSymbolOffset(SD);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001100 } else {
Daniel Dunbar8fb04032010-03-25 08:08:54 +00001101 // The index is the section ordinal (1-based).
1102 Index = SD->getFragment()->getParent()->getOrdinal() + 1;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001103 FixedValue += getSectionAddress(SD->getFragment()->getParent());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001104 }
Rafael Espindolabf60dad2010-12-07 03:50:14 +00001105 if (IsPCRel)
1106 FixedValue -= getSectionAddress(Fragment->getParent());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001107
Daniel Dunbarf52788f2010-11-27 04:59:14 +00001108 Type = macho::RIT_Vanilla;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001109 }
1110
1111 // struct relocation_info (8 bytes)
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +00001112 macho::RelocationEntry MRE;
Daniel Dunbar640e9482010-05-11 23:53:07 +00001113 MRE.Word0 = FixupOffset;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001114 MRE.Word1 = ((Index << 0) |
1115 (IsPCRel << 24) |
1116 (Log2Size << 25) |
1117 (IsExtern << 27) |
1118 (Type << 28));
Daniel Dunbarb7514182010-03-22 20:35:50 +00001119 Relocations[Fragment->getParent()].push_back(MRE);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001120 }
1121
1122 void BindIndirectSymbols(MCAssembler &Asm) {
1123 // This is the point where 'as' creates actual symbols for indirect symbols
1124 // (in the following two passes). It would be easier for us to do this
1125 // sooner when we see the attribute, but that makes getting the order in the
1126 // symbol table much more complicated than it is worth.
1127 //
1128 // FIXME: Revisit this when the dust settles.
1129
1130 // Bind non lazy symbol pointers first.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +00001131 unsigned IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001132 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +00001133 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001134 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +00001135 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001136
1137 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
1138 continue;
1139
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +00001140 // Initialize the section indirect symbol base, if necessary.
1141 if (!IndirectSymBase.count(it->SectionData))
1142 IndirectSymBase[it->SectionData] = IndirectIndex;
Jim Grosbach3c384922010-11-11 20:16:23 +00001143
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001144 Asm.getOrCreateSymbolData(*it->Symbol);
1145 }
1146
1147 // Then lazy symbol pointers and symbol stubs.
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +00001148 IndirectIndex = 0;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001149 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +00001150 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001151 const MCSectionMachO &Section =
Daniel Dunbar56279f42010-05-18 17:28:20 +00001152 cast<MCSectionMachO>(it->SectionData->getSection());
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001153
1154 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
1155 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
1156 continue;
1157
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +00001158 // Initialize the section indirect symbol base, if necessary.
1159 if (!IndirectSymBase.count(it->SectionData))
1160 IndirectSymBase[it->SectionData] = IndirectIndex;
1161
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001162 // Set the symbol type to undefined lazy, but only on construction.
1163 //
1164 // FIXME: Do not hardcode.
1165 bool Created;
1166 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
1167 if (Created)
1168 Entry.setFlags(Entry.getFlags() | 0x0001);
1169 }
1170 }
1171
1172 /// ComputeSymbolTable - Compute the symbol table data
1173 ///
1174 /// \param StringTable [out] - The string table data.
1175 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
1176 /// string table.
1177 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
1178 std::vector<MachSymbolData> &LocalSymbolData,
1179 std::vector<MachSymbolData> &ExternalSymbolData,
1180 std::vector<MachSymbolData> &UndefinedSymbolData) {
1181 // Build section lookup table.
1182 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
1183 unsigned Index = 1;
1184 for (MCAssembler::iterator it = Asm.begin(),
1185 ie = Asm.end(); it != ie; ++it, ++Index)
1186 SectionIndexMap[&it->getSection()] = Index;
1187 assert(Index <= 256 && "Too many sections!");
1188
1189 // Index 0 is always the empty string.
1190 StringMap<uint64_t> StringIndexMap;
1191 StringTable += '\x00';
1192
1193 // Build the symbol arrays and the string table, but only for non-local
1194 // symbols.
1195 //
1196 // The particular order that we collect the symbols and create the string
1197 // table, then sort the symbols is chosen to match 'as'. Even though it
1198 // doesn't matter for correctness, this is important for letting us diff .o
1199 // files.
1200 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1201 ie = Asm.symbol_end(); it != ie; ++it) {
1202 const MCSymbol &Symbol = it->getSymbol();
1203
1204 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +00001205 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001206 continue;
1207
1208 if (!it->isExternal() && !Symbol.isUndefined())
1209 continue;
1210
1211 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1212 if (!Entry) {
1213 Entry = StringTable.size();
1214 StringTable += Symbol.getName();
1215 StringTable += '\x00';
1216 }
1217
1218 MachSymbolData MSD;
1219 MSD.SymbolData = it;
1220 MSD.StringIndex = Entry;
1221
1222 if (Symbol.isUndefined()) {
1223 MSD.SectionIndex = 0;
1224 UndefinedSymbolData.push_back(MSD);
1225 } else if (Symbol.isAbsolute()) {
1226 MSD.SectionIndex = 0;
1227 ExternalSymbolData.push_back(MSD);
1228 } else {
1229 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1230 assert(MSD.SectionIndex && "Invalid section index!");
1231 ExternalSymbolData.push_back(MSD);
1232 }
1233 }
1234
1235 // Now add the data for local symbols.
1236 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1237 ie = Asm.symbol_end(); it != ie; ++it) {
1238 const MCSymbol &Symbol = it->getSymbol();
1239
1240 // Ignore non-linker visible symbols.
Daniel Dunbar843aa1f2010-06-16 20:04:29 +00001241 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001242 continue;
1243
1244 if (it->isExternal() || Symbol.isUndefined())
1245 continue;
1246
1247 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1248 if (!Entry) {
1249 Entry = StringTable.size();
1250 StringTable += Symbol.getName();
1251 StringTable += '\x00';
1252 }
1253
1254 MachSymbolData MSD;
1255 MSD.SymbolData = it;
1256 MSD.StringIndex = Entry;
1257
1258 if (Symbol.isAbsolute()) {
1259 MSD.SectionIndex = 0;
1260 LocalSymbolData.push_back(MSD);
1261 } else {
1262 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1263 assert(MSD.SectionIndex && "Invalid section index!");
1264 LocalSymbolData.push_back(MSD);
1265 }
1266 }
1267
1268 // External and undefined symbols are required to be in lexicographic order.
1269 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1270 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1271
1272 // Set the symbol indices.
1273 Index = 0;
1274 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1275 LocalSymbolData[i].SymbolData->setIndex(Index++);
1276 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1277 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1278 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1279 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1280
1281 // The string table is padded to a multiple of 4.
1282 while (StringTable.size() % 4)
1283 StringTable += '\x00';
1284 }
1285
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001286 void computeSectionAddresses(const MCAssembler &Asm,
1287 const MCAsmLayout &Layout) {
1288 uint64_t StartAddress = 0;
1289 const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
1290 for (int i = 0, n = Order.size(); i != n ; ++i) {
1291 const MCSectionData *SD = Order[i];
1292 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
1293 SectionAddress[SD] = StartAddress;
1294 StartAddress += Layout.getSectionAddressSize(SD);
1295 // Explicitly pad the section to match the alignment requirements of the
1296 // following one. This is for 'gas' compatibility, it shouldn't
1297 /// strictly be necessary.
1298 StartAddress += getPaddingSize(SD, Layout);
1299 }
1300 }
1301
1302 void ExecutePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout) {
1303 computeSectionAddresses(Asm, Layout);
1304
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001305 // Create symbol data for any indirect symbols.
1306 BindIndirectSymbols(Asm);
1307
1308 // Compute symbol table information and bind symbol indices.
1309 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1310 UndefinedSymbolData);
1311 }
1312
Daniel Dunbar1f3662a2010-12-17 04:54:54 +00001313 bool IsSymbolRefDifferenceFullyResolved(const MCAssembler &Asm,
1314 const MCSymbolRefExpr *A,
Rafael Espindola31327802010-12-18 06:27:54 +00001315 const MCSymbolRefExpr *B,
1316 bool InSet) const {
1317 if (InSet)
1318 return true;
1319
Daniel Dunbarb8742272010-12-17 05:50:29 +00001320 if (!TargetObjectWriter->useAggressiveSymbolFolding())
1321 return false;
1322
Daniel Dunbar32c1c5a2010-12-17 04:54:58 +00001323 // The effective address is
1324 // addr(atom(A)) + offset(A)
1325 // - addr(atom(B)) - offset(B)
1326 // and the offsets are not relocatable, so the fixup is fully resolved when
1327 // addr(atom(A)) - addr(atom(B)) == 0.
1328 const MCSymbolData *A_Base = 0, *B_Base = 0;
1329
1330 // Modified symbol references cannot be resolved.
1331 if (A->getKind() != MCSymbolRefExpr::VK_None ||
1332 B->getKind() != MCSymbolRefExpr::VK_None)
1333 return false;
1334
1335 A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
1336 if (!A_Base)
1337 return false;
1338
1339 B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
1340 if (!B_Base)
1341 return false;
1342
1343 // If the atoms are the same, they are guaranteed to have the same address.
1344 if (A_Base == B_Base)
1345 return true;
1346
1347 // Otherwise, we can't prove this is fully resolved.
Daniel Dunbar1f3662a2010-12-17 04:54:54 +00001348 return false;
1349 }
1350
Rafael Espindola70703872010-09-30 02:22:20 +00001351 bool IsFixupFullyResolved(const MCAssembler &Asm,
1352 const MCValue Target,
1353 bool IsPCRel,
1354 const MCFragment *DF) const {
Daniel Dunbar7976b882010-11-27 05:18:48 +00001355 // Otherwise, determine whether this value is actually resolved; scattering
1356 // may cause atoms to move.
Rafael Espindola70703872010-09-30 02:22:20 +00001357
Daniel Dunbar7976b882010-11-27 05:18:48 +00001358 // Check if we are using the "simple" resolution algorithm (e.g.,
1359 // i386).
1360 if (!Asm.getBackend().hasReliableSymbolDifference()) {
1361 const MCSection *BaseSection = 0;
1362 if (IsPCRel)
1363 BaseSection = &DF->getParent()->getSection();
1364
1365 return isScatteredFixupFullyResolvedSimple(Asm, Target, BaseSection);
Rafael Espindola70703872010-09-30 02:22:20 +00001366 }
Daniel Dunbar7976b882010-11-27 05:18:48 +00001367
1368 // Otherwise, compute the proper answer as reliably as possible.
1369
1370 // If this is a PCrel relocation, find the base atom (identified by its
1371 // symbol) that the fixup value is relative to.
1372 const MCSymbolData *BaseSymbol = 0;
1373 if (IsPCRel) {
1374 BaseSymbol = DF->getAtom();
1375 if (!BaseSymbol)
1376 return false;
1377 }
1378
1379 return isScatteredFixupFullyResolved(Asm, Target, BaseSymbol);
Rafael Espindola70703872010-09-30 02:22:20 +00001380 }
1381
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001382 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001383 unsigned NumSections = Asm.size();
1384
1385 // The section data starts after the header, the segment load command (and
1386 // section headers) and the symbol table.
1387 unsigned NumLoadCommands = 1;
Daniel Dunbar5d05d972010-12-16 17:21:02 +00001388 uint64_t LoadCommandsSize = is64Bit() ?
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001389 macho::SegmentLoadCommand64Size + NumSections * macho::Section64Size :
1390 macho::SegmentLoadCommand32Size + NumSections * macho::Section32Size;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001391
1392 // Add the symbol table load command sizes, if used.
1393 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1394 UndefinedSymbolData.size();
1395 if (NumSymbols) {
1396 NumLoadCommands += 2;
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001397 LoadCommandsSize += (macho::SymtabLoadCommandSize +
1398 macho::DysymtabLoadCommandSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001399 }
1400
1401 // Compute the total size of the section data, as well as its file size and
1402 // vm size.
Daniel Dunbar5d05d972010-12-16 17:21:02 +00001403 uint64_t SectionDataStart = (is64Bit() ? macho::Header64Size :
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001404 macho::Header32Size) + LoadCommandsSize;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001405 uint64_t SectionDataSize = 0;
1406 uint64_t SectionDataFileSize = 0;
1407 uint64_t VMSize = 0;
1408 for (MCAssembler::const_iterator it = Asm.begin(),
1409 ie = Asm.end(); it != ie; ++it) {
1410 const MCSectionData &SD = *it;
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001411 uint64_t Address = getSectionAddress(&SD);
1412 uint64_t Size = Layout.getSectionAddressSize(&SD);
Daniel Dunbar5d428512010-03-25 02:00:07 +00001413 uint64_t FileSize = Layout.getSectionFileSize(&SD);
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001414 FileSize += getPaddingSize(&SD, Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001415
Daniel Dunbar5d428512010-03-25 02:00:07 +00001416 VMSize = std::max(VMSize, Address + Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001417
Rafael Espindolaf2dc4aa2010-11-17 20:03:54 +00001418 if (SD.getSection().isVirtualSection())
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001419 continue;
1420
Daniel Dunbar5d428512010-03-25 02:00:07 +00001421 SectionDataSize = std::max(SectionDataSize, Address + Size);
1422 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001423 }
1424
1425 // The section data is padded to 4 bytes.
1426 //
1427 // FIXME: Is this machine dependent?
1428 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1429 SectionDataFileSize += SectionDataPadding;
1430
1431 // Write the prolog, starting with the header and load command...
1432 WriteHeader(NumLoadCommands, LoadCommandsSize,
1433 Asm.getSubsectionsViaSymbols());
1434 WriteSegmentLoadCommand(NumSections, VMSize,
1435 SectionDataStart, SectionDataSize);
1436
1437 // ... and then the section headers.
1438 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1439 for (MCAssembler::const_iterator it = Asm.begin(),
1440 ie = Asm.end(); it != ie; ++it) {
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +00001441 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001442 unsigned NumRelocs = Relocs.size();
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001443 uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001444 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001445 RelocTableEnd += NumRelocs * macho::RelocationInfoSize;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001446 }
1447
1448 // Write the symbol table load command, if used.
1449 if (NumSymbols) {
1450 unsigned FirstLocalSymbol = 0;
1451 unsigned NumLocalSymbols = LocalSymbolData.size();
1452 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1453 unsigned NumExternalSymbols = ExternalSymbolData.size();
1454 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1455 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1456 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1457 unsigned NumSymTabSymbols =
1458 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1459 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1460 uint64_t IndirectSymbolOffset = 0;
1461
1462 // If used, the indirect symbols are written after the section data.
1463 if (NumIndirectSymbols)
1464 IndirectSymbolOffset = RelocTableEnd;
1465
1466 // The symbol table is written after the indirect symbol data.
1467 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1468
1469 // The string table is written after symbol table.
1470 uint64_t StringTableOffset =
Daniel Dunbar5d05d972010-12-16 17:21:02 +00001471 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ? macho::Nlist64Size :
Daniel Dunbar821ecd72010-11-27 04:19:38 +00001472 macho::Nlist32Size);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001473 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1474 StringTableOffset, StringTable.size());
1475
1476 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1477 FirstExternalSymbol, NumExternalSymbols,
1478 FirstUndefinedSymbol, NumUndefinedSymbols,
1479 IndirectSymbolOffset, NumIndirectSymbols);
1480 }
1481
1482 // Write the actual section data.
1483 for (MCAssembler::const_iterator it = Asm.begin(),
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001484 ie = Asm.end(); it != ie; ++it) {
Daniel Dunbar5d2477c2010-12-17 02:45:59 +00001485 Asm.WriteSectionData(it, Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001486
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001487 uint64_t Pad = getPaddingSize(it, Layout);
1488 for (unsigned int i = 0; i < Pad; ++i)
1489 Write8(0);
1490 }
1491
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001492 // Write the extra padding.
1493 WriteZeros(SectionDataPadding);
1494
1495 // Write the relocation entries.
1496 for (MCAssembler::const_iterator it = Asm.begin(),
1497 ie = Asm.end(); it != ie; ++it) {
1498 // Write the section relocation entries, in reverse order to match 'as'
1499 // (approximately, the exact algorithm is more complicated than this).
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +00001500 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001501 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1502 Write32(Relocs[e - i - 1].Word0);
1503 Write32(Relocs[e - i - 1].Word1);
1504 }
1505 }
1506
1507 // Write the symbol table data, if used.
1508 if (NumSymbols) {
1509 // Write the indirect symbol entries.
1510 for (MCAssembler::const_indirect_symbol_iterator
1511 it = Asm.indirect_symbol_begin(),
1512 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1513 // Indirect symbols in the non lazy symbol pointer section have some
1514 // special handling.
1515 const MCSectionMachO &Section =
1516 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1517 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1518 // If this symbol is defined and internal, mark it as such.
1519 if (it->Symbol->isDefined() &&
1520 !Asm.getSymbolData(*it->Symbol).isExternal()) {
Daniel Dunbarf52788f2010-11-27 04:59:14 +00001521 uint32_t Flags = macho::ISF_Local;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001522 if (it->Symbol->isAbsolute())
Daniel Dunbarf52788f2010-11-27 04:59:14 +00001523 Flags |= macho::ISF_Absolute;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001524 Write32(Flags);
1525 continue;
1526 }
1527 }
1528
1529 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1530 }
1531
1532 // FIXME: Check that offsets match computed ones.
1533
1534 // Write the symbol table entries.
1535 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001536 WriteNlist(LocalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001537 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001538 WriteNlist(ExternalSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001539 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
Daniel Dunbar207e06e2010-03-24 03:43:40 +00001540 WriteNlist(UndefinedSymbolData[i], Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001541
1542 // Write the string table.
1543 OS << StringTable.str();
1544 }
1545 }
1546};
1547
1548}
1549
Daniel Dunbarae5abd52010-12-16 16:09:19 +00001550MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
Daniel Dunbar5d05d972010-12-16 17:21:02 +00001551 raw_ostream &OS,
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001552 bool IsLittleEndian) {
Daniel Dunbar5d05d972010-12-16 17:21:02 +00001553 return new MachObjectWriter(MOTW, OS, IsLittleEndian);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001554}