blob: 1819c4053ba69f5235e3359bacb66c5442fd706c [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
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000067namespace {
68
Daniel Dunbar115a3dd2010-11-13 07:33:40 +000069class MachObjectWriter : public MCObjectWriter {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000070 /// MachSymbolData - Helper struct for containing some precomputed information
71 /// on symbols.
72 struct MachSymbolData {
73 MCSymbolData *SymbolData;
74 uint64_t StringIndex;
75 uint8_t SectionIndex;
76
77 // Support lexicographic sorting.
78 bool operator<(const MachSymbolData &RHS) const {
Benjamin Kramerc37791e2010-05-20 14:14:22 +000079 return SymbolData->getSymbol().getName() <
80 RHS.SymbolData->getSymbol().getName();
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000081 }
82 };
83
Daniel Dunbarae5abd52010-12-16 16:09:19 +000084 /// The target specific Mach-O writer instance.
85 llvm::OwningPtr<MCMachObjectTargetWriter> TargetObjectWriter;
Daniel Dunbar7e06af82010-12-16 15:42:31 +000086
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000087 /// @name Relocation Data
88 /// @{
89
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000090 llvm::DenseMap<const MCSectionData*,
Daniel Dunbar90e3e3a2010-11-27 13:39:48 +000091 std::vector<macho::RelocationEntry> > Relocations;
Daniel Dunbar2ae4bfd2010-05-18 17:28:24 +000092 llvm::DenseMap<const MCSectionData*, unsigned> IndirectSymBase;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000093
94 /// @}
95 /// @name Symbol Table Data
96 /// @{
97
98 SmallString<256> StringTable;
99 std::vector<MachSymbolData> LocalSymbolData;
100 std::vector<MachSymbolData> ExternalSymbolData;
101 std::vector<MachSymbolData> UndefinedSymbolData;
102
103 /// @}
104
Daniel Dunbarae5abd52010-12-16 16:09:19 +0000105private:
106 /// @name Utility Methods
107 /// @{
108
109 bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
110 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
111 (MCFixupKind) Kind);
112
113 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
114 }
115
116 /// @}
117
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000118 SectionAddrMap SectionAddress;
119 uint64_t getSectionAddress(const MCSectionData* SD) const {
120 return SectionAddress.lookup(SD);
121 }
122 uint64_t getSymbolAddress(const MCSymbolData* SD,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000123 const MCAsmLayout &Layout) const;
Daniel Dunbar173aa9c2011-04-29 18:13:42 +0000124
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000125 uint64_t getFragmentAddress(const MCFragment *Fragment,
126 const MCAsmLayout &Layout) const {
127 return getSectionAddress(Fragment->getParent()) +
128 Layout.getFragmentOffset(Fragment);
129 }
130
131 uint64_t getPaddingSize(const MCSectionData *SD,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000132 const MCAsmLayout &Layout) const;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000133public:
Daniel Dunbarae5abd52010-12-16 16:09:19 +0000134 MachObjectWriter(MCMachObjectTargetWriter *MOTW, raw_ostream &_OS,
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000135 bool _IsLittleEndian)
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000136 : MCObjectWriter(_OS, _IsLittleEndian), TargetObjectWriter(MOTW) {
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000137 }
138
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000139 /// @name Target Writer Proxy Accessors
140 /// @{
141
142 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
Daniel Dunbar532c4562010-12-22 13:49:43 +0000143 bool isARM() const {
Daniel Dunbarfdfbc6a2010-12-22 16:19:20 +0000144 uint32_t CPUType = TargetObjectWriter->getCPUType() & ~mach::CTFM_ArchMask;
Daniel Dunbar532c4562010-12-22 13:49:43 +0000145 return CPUType == mach::CTM_ARM;
146 }
Daniel Dunbar5d05d972010-12-16 17:21:02 +0000147
148 /// @}
149
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000150 void WriteHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000151 bool SubsectionsViaSymbols);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000152
153 /// WriteSegmentLoadCommand - Write a segment load command.
154 ///
155 /// \arg NumSections - The number of sections in this segment.
156 /// \arg SectionDataSize - The total size of the sections.
157 void WriteSegmentLoadCommand(unsigned NumSections,
158 uint64_t VMSize,
159 uint64_t SectionDataStartOffset,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000160 uint64_t SectionDataSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000161
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000162 void WriteSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
163 const MCSectionData &SD, uint64_t FileOffset,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000164 uint64_t RelocationsStart, unsigned NumRelocations);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000165
166 void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
167 uint32_t StringTableOffset,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000168 uint32_t StringTableSize);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000169
170 void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
171 uint32_t NumLocalSymbols,
172 uint32_t FirstExternalSymbol,
173 uint32_t NumExternalSymbols,
174 uint32_t FirstUndefinedSymbol,
175 uint32_t NumUndefinedSymbols,
176 uint32_t IndirectSymbolOffset,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000177 uint32_t NumIndirectSymbols);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000178
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000179 void WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000180
Daniel Dunbar35b06572010-03-22 23:16:43 +0000181 // FIXME: We really need to improve the relocation validation. Basically, we
182 // want to implement a separate computation which evaluates the relocation
183 // entry as the linker would, and verifies that the resultant fixup value is
184 // exactly what the encoder wanted. This will catch several classes of
185 // problems:
186 //
187 // - Relocation entry bugs, the two algorithms are unlikely to have the same
188 // exact bug.
189 //
190 // - Relaxation issues, where we forget to relax something.
191 //
192 // - Input errors, where something cannot be correctly encoded. 'as' allows
193 // these through in many cases.
194
Daniel Dunbar7e06af82010-12-16 15:42:31 +0000195 static bool isFixupKindRIPRel(unsigned Kind) {
196 return Kind == X86::reloc_riprel_4byte ||
197 Kind == X86::reloc_riprel_4byte_movq_load;
198 }
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000199 void RecordX86_64Relocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000200 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000201 const MCFixup &Fixup, MCValue Target,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000202 uint64_t &FixedValue);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000203
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000204 void RecordScatteredRelocation(const MCAssembler &Asm,
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000205 const MCAsmLayout &Layout,
Daniel Dunbarb7514182010-03-22 20:35:50 +0000206 const MCFragment *Fragment,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000207 const MCFixup &Fixup, MCValue Target,
Evan Chengf3eb3bb2011-01-14 02:38:49 +0000208 unsigned Log2Size,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000209 uint64_t &FixedValue);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000210
Daniel Dunbar25bcc9c2010-12-22 16:45:29 +0000211 void RecordARMScatteredRelocation(const MCAssembler &Asm,
212 const MCAsmLayout &Layout,
213 const MCFragment *Fragment,
214 const MCFixup &Fixup, MCValue Target,
Evan Chengf3eb3bb2011-01-14 02:38:49 +0000215 unsigned Log2Size,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000216 uint64_t &FixedValue);
Daniel Dunbar25bcc9c2010-12-22 16:45:29 +0000217
Evan Chengf3eb3bb2011-01-14 02:38:49 +0000218 void RecordARMMovwMovtRelocation(const MCAssembler &Asm,
219 const MCAsmLayout &Layout,
220 const MCFragment *Fragment,
221 const MCFixup &Fixup, MCValue Target,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000222 uint64_t &FixedValue);
Evan Chengf3eb3bb2011-01-14 02:38:49 +0000223
Eric Christopherc9ada472010-06-15 22:59:05 +0000224 void RecordTLVPRelocation(const MCAssembler &Asm,
Eric Christophere48dbf82010-06-16 00:26:36 +0000225 const MCAsmLayout &Layout,
226 const MCFragment *Fragment,
227 const MCFixup &Fixup, MCValue Target,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000228 uint64_t &FixedValue);
Jim Grosbach3c384922010-11-11 20:16:23 +0000229
Daniel Dunbare8624532010-12-27 14:49:49 +0000230 static bool getARMFixupKindMachOInfo(unsigned Kind, unsigned &RelocType,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000231 unsigned &Log2Size);
Daniel Dunbar36645642010-12-22 16:32:37 +0000232
Daniel Dunbar532c4562010-12-22 13:49:43 +0000233 void RecordARMRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
234 const MCFragment *Fragment, const MCFixup &Fixup,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000235 MCValue Target, uint64_t &FixedValue);
Daniel Dunbar532c4562010-12-22 13:49:43 +0000236
Daniel Dunbar207e06e2010-03-24 03:43:40 +0000237 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
Daniel Dunbarc90e30a2010-05-26 15:18:56 +0000238 const MCFragment *Fragment, const MCFixup &Fixup,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000239 MCValue Target, uint64_t &FixedValue);
Daniel Dunbar602b40f2010-03-19 18:07:55 +0000240
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000241 void BindIndirectSymbols(MCAssembler &Asm);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000242
243 /// ComputeSymbolTable - Compute the symbol table data
244 ///
245 /// \param StringTable [out] - The string table data.
246 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
247 /// string table.
248 void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
249 std::vector<MachSymbolData> &LocalSymbolData,
250 std::vector<MachSymbolData> &ExternalSymbolData,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000251 std::vector<MachSymbolData> &UndefinedSymbolData);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000252
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000253 void computeSectionAddresses(const MCAssembler &Asm,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000254 const MCAsmLayout &Layout);
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000255
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000256 void ExecutePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000257
Rafael Espindolafea753b2010-12-24 21:22:02 +0000258 virtual bool IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
259 const MCSymbolData &DataA,
260 const MCFragment &FB,
261 bool InSet,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000262 bool IsPCRel) const;
Rafael Espindola31327802010-12-18 06:27:54 +0000263
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000264 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +0000265};
266
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000267} // end anonymous namespace
268
269uint64_t MachObjectWriter::getSymbolAddress(const MCSymbolData* SD,
270 const MCAsmLayout &Layout) const {
271 const MCSymbol &S = SD->getSymbol();
272
273 // If this is a variable, then recursively evaluate now.
274 if (S.isVariable()) {
275 MCValue Target;
276 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, Layout))
277 report_fatal_error("unable to evaluate offset for variable '" +
278 S.getName() + "'");
279
280 // Verify that any used symbols are defined.
281 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
282 report_fatal_error("unable to evaluate offset to undefined symbol '" +
283 Target.getSymA()->getSymbol().getName() + "'");
284 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
285 report_fatal_error("unable to evaluate offset to undefined symbol '" +
286 Target.getSymB()->getSymbol().getName() + "'");
287
288 uint64_t Address = Target.getConstant();
289 if (Target.getSymA())
290 Address += getSymbolAddress(&Layout.getAssembler().getSymbolData(
291 Target.getSymA()->getSymbol()), Layout);
292 if (Target.getSymB())
293 Address += getSymbolAddress(&Layout.getAssembler().getSymbolData(
294 Target.getSymB()->getSymbol()), Layout);
295 return Address;
296 }
297
298 return getSectionAddress(SD->getFragment()->getParent()) +
299 Layout.getSymbolOffset(SD);
300}
301
302uint64_t MachObjectWriter::getPaddingSize(const MCSectionData *SD,
303 const MCAsmLayout &Layout) const {
304 uint64_t EndAddr = getSectionAddress(SD) + Layout.getSectionAddressSize(SD);
305 unsigned Next = SD->getLayoutOrder() + 1;
306 if (Next >= Layout.getSectionOrder().size())
307 return 0;
308
309 const MCSectionData &NextSD = *Layout.getSectionOrder()[Next];
310 if (NextSD.getSection().isVirtualSection())
311 return 0;
312 return OffsetToAlignment(EndAddr, NextSD.getAlignment());
313}
314
315void MachObjectWriter::WriteHeader(unsigned NumLoadCommands,
316 unsigned LoadCommandsSize,
317 bool SubsectionsViaSymbols) {
318 uint32_t Flags = 0;
319
320 if (SubsectionsViaSymbols)
321 Flags |= macho::HF_SubsectionsViaSymbols;
322
323 // struct mach_header (28 bytes) or
324 // struct mach_header_64 (32 bytes)
325
326 uint64_t Start = OS.tell();
327 (void) Start;
328
329 Write32(is64Bit() ? macho::HM_Object64 : macho::HM_Object32);
330
331 Write32(TargetObjectWriter->getCPUType());
332 Write32(TargetObjectWriter->getCPUSubtype());
333
334 Write32(macho::HFT_Object);
335 Write32(NumLoadCommands);
336 Write32(LoadCommandsSize);
337 Write32(Flags);
338 if (is64Bit())
339 Write32(0); // reserved
340
341 assert(OS.tell() - Start ==
342 (is64Bit() ? macho::Header64Size : macho::Header32Size));
343}
344
345/// WriteSegmentLoadCommand - Write a segment load command.
346///
347/// \arg NumSections - The number of sections in this segment.
348/// \arg SectionDataSize - The total size of the sections.
349void MachObjectWriter::WriteSegmentLoadCommand(unsigned NumSections,
350 uint64_t VMSize,
351 uint64_t SectionDataStartOffset,
352 uint64_t SectionDataSize) {
353 // struct segment_command (56 bytes) or
354 // struct segment_command_64 (72 bytes)
355
356 uint64_t Start = OS.tell();
357 (void) Start;
358
359 unsigned SegmentLoadCommandSize =
360 is64Bit() ? macho::SegmentLoadCommand64Size:
361 macho::SegmentLoadCommand32Size;
362 Write32(is64Bit() ? macho::LCT_Segment64 : macho::LCT_Segment);
363 Write32(SegmentLoadCommandSize +
364 NumSections * (is64Bit() ? macho::Section64Size :
365 macho::Section32Size));
366
367 WriteBytes("", 16);
368 if (is64Bit()) {
369 Write64(0); // vmaddr
370 Write64(VMSize); // vmsize
371 Write64(SectionDataStartOffset); // file offset
372 Write64(SectionDataSize); // file size
373 } else {
374 Write32(0); // vmaddr
375 Write32(VMSize); // vmsize
376 Write32(SectionDataStartOffset); // file offset
377 Write32(SectionDataSize); // file size
378 }
379 Write32(0x7); // maxprot
380 Write32(0x7); // initprot
381 Write32(NumSections);
382 Write32(0); // flags
383
384 assert(OS.tell() - Start == SegmentLoadCommandSize);
385}
386
387void MachObjectWriter::WriteSection(const MCAssembler &Asm,
388 const MCAsmLayout &Layout,
389 const MCSectionData &SD,
390 uint64_t FileOffset,
391 uint64_t RelocationsStart,
392 unsigned NumRelocations) {
393 uint64_t SectionSize = Layout.getSectionAddressSize(&SD);
394
395 // The offset is unused for virtual sections.
396 if (SD.getSection().isVirtualSection()) {
397 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
398 FileOffset = 0;
399 }
400
401 // struct section (68 bytes) or
402 // struct section_64 (80 bytes)
403
404 uint64_t Start = OS.tell();
405 (void) Start;
406
407 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
408 WriteBytes(Section.getSectionName(), 16);
409 WriteBytes(Section.getSegmentName(), 16);
410 if (is64Bit()) {
411 Write64(getSectionAddress(&SD)); // address
412 Write64(SectionSize); // size
413 } else {
414 Write32(getSectionAddress(&SD)); // address
415 Write32(SectionSize); // size
416 }
417 Write32(FileOffset);
418
419 unsigned Flags = Section.getTypeAndAttributes();
420 if (SD.hasInstructions())
421 Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
422
423 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
424 Write32(Log2_32(SD.getAlignment()));
425 Write32(NumRelocations ? RelocationsStart : 0);
426 Write32(NumRelocations);
427 Write32(Flags);
428 Write32(IndirectSymBase.lookup(&SD)); // reserved1
429 Write32(Section.getStubSize()); // reserved2
430 if (is64Bit())
431 Write32(0); // reserved3
432
433 assert(OS.tell() - Start == (is64Bit() ? macho::Section64Size :
434 macho::Section32Size));
435}
436
437void MachObjectWriter::WriteSymtabLoadCommand(uint32_t SymbolOffset,
438 uint32_t NumSymbols,
439 uint32_t StringTableOffset,
440 uint32_t StringTableSize) {
441 // struct symtab_command (24 bytes)
442
443 uint64_t Start = OS.tell();
444 (void) Start;
445
446 Write32(macho::LCT_Symtab);
447 Write32(macho::SymtabLoadCommandSize);
448 Write32(SymbolOffset);
449 Write32(NumSymbols);
450 Write32(StringTableOffset);
451 Write32(StringTableSize);
452
453 assert(OS.tell() - Start == macho::SymtabLoadCommandSize);
454}
455
456void MachObjectWriter::WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
457 uint32_t NumLocalSymbols,
458 uint32_t FirstExternalSymbol,
459 uint32_t NumExternalSymbols,
460 uint32_t FirstUndefinedSymbol,
461 uint32_t NumUndefinedSymbols,
462 uint32_t IndirectSymbolOffset,
463 uint32_t NumIndirectSymbols) {
464 // struct dysymtab_command (80 bytes)
465
466 uint64_t Start = OS.tell();
467 (void) Start;
468
469 Write32(macho::LCT_Dysymtab);
470 Write32(macho::DysymtabLoadCommandSize);
471 Write32(FirstLocalSymbol);
472 Write32(NumLocalSymbols);
473 Write32(FirstExternalSymbol);
474 Write32(NumExternalSymbols);
475 Write32(FirstUndefinedSymbol);
476 Write32(NumUndefinedSymbols);
477 Write32(0); // tocoff
478 Write32(0); // ntoc
479 Write32(0); // modtaboff
480 Write32(0); // nmodtab
481 Write32(0); // extrefsymoff
482 Write32(0); // nextrefsyms
483 Write32(IndirectSymbolOffset);
484 Write32(NumIndirectSymbols);
485 Write32(0); // extreloff
486 Write32(0); // nextrel
487 Write32(0); // locreloff
488 Write32(0); // nlocrel
489
490 assert(OS.tell() - Start == macho::DysymtabLoadCommandSize);
491}
492
493void MachObjectWriter::WriteNlist(MachSymbolData &MSD, const MCAsmLayout &Layout) {
494 MCSymbolData &Data = *MSD.SymbolData;
495 const MCSymbol &Symbol = Data.getSymbol();
496 uint8_t Type = 0;
497 uint16_t Flags = Data.getFlags();
498 uint32_t Address = 0;
499
500 // Set the N_TYPE bits. See <mach-o/nlist.h>.
501 //
502 // FIXME: Are the prebound or indirect fields possible here?
503 if (Symbol.isUndefined())
504 Type = macho::STT_Undefined;
505 else if (Symbol.isAbsolute())
506 Type = macho::STT_Absolute;
507 else
508 Type = macho::STT_Section;
509
510 // FIXME: Set STAB bits.
511
512 if (Data.isPrivateExtern())
513 Type |= macho::STF_PrivateExtern;
514
515 // Set external bit.
516 if (Data.isExternal() || Symbol.isUndefined())
517 Type |= macho::STF_External;
518
519 // Compute the symbol address.
520 if (Symbol.isDefined()) {
521 if (Symbol.isAbsolute()) {
522 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
523 } else {
524 Address = getSymbolAddress(&Data, Layout);
525 }
526 } else if (Data.isCommon()) {
527 // Common symbols are encoded with the size in the address
528 // field, and their alignment in the flags.
529 Address = Data.getCommonSize();
530
531 // Common alignment is packed into the 'desc' bits.
532 if (unsigned Align = Data.getCommonAlignment()) {
533 unsigned Log2Size = Log2_32(Align);
534 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
535 if (Log2Size > 15)
536 report_fatal_error("invalid 'common' alignment '" +
537 Twine(Align) + "'");
538 // FIXME: Keep this mask with the SymbolFlags enumeration.
539 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
540 }
541 }
542
543 // struct nlist (12 bytes)
544
545 Write32(MSD.StringIndex);
546 Write8(Type);
547 Write8(MSD.SectionIndex);
548
549 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
550 // value.
551 Write16(Flags);
552 if (is64Bit())
553 Write64(Address);
554 else
555 Write32(Address);
556}
557
558void MachObjectWriter::RecordX86_64Relocation(const MCAssembler &Asm,
559 const MCAsmLayout &Layout,
560 const MCFragment *Fragment,
561 const MCFixup &Fixup,
562 MCValue Target,
563 uint64_t &FixedValue) {
564 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
565 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
566 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
567
568 // See <reloc.h>.
569 uint32_t FixupOffset =
570 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
571 uint32_t FixupAddress =
572 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
573 int64_t Value = 0;
574 unsigned Index = 0;
575 unsigned IsExtern = 0;
576 unsigned Type = 0;
577
578 Value = Target.getConstant();
579
580 if (IsPCRel) {
581 // Compensate for the relocation offset, Darwin x86_64 relocations only have
582 // the addend and appear to have attempted to define it to be the actual
583 // expression addend without the PCrel bias. However, instructions with data
584 // following the relocation are not accommodated for (see comment below
585 // regarding SIGNED{1,2,4}), so it isn't exactly that either.
586 Value += 1LL << Log2Size;
587 }
588
589 if (Target.isAbsolute()) { // constant
590 // SymbolNum of 0 indicates the absolute section.
591 Type = macho::RIT_X86_64_Unsigned;
592 Index = 0;
593
594 // FIXME: I believe this is broken, I don't think the linker can understand
595 // it. I think it would require a local relocation, but I'm not sure if that
596 // would work either. The official way to get an absolute PCrel relocation
597 // is to use an absolute symbol (which we don't support yet).
598 if (IsPCRel) {
599 IsExtern = 1;
600 Type = macho::RIT_X86_64_Branch;
601 }
602 } else if (Target.getSymB()) { // A - B + constant
603 const MCSymbol *A = &Target.getSymA()->getSymbol();
604 MCSymbolData &A_SD = Asm.getSymbolData(*A);
605 const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
606
607 const MCSymbol *B = &Target.getSymB()->getSymbol();
608 MCSymbolData &B_SD = Asm.getSymbolData(*B);
609 const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
610
611 // Neither symbol can be modified.
612 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
613 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
614 report_fatal_error("unsupported relocation of modified symbol");
615
616 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
617 // implement most of these correctly.
618 if (IsPCRel)
619 report_fatal_error("unsupported pc-relative relocation of difference");
620
621 // The support for the situation where one or both of the symbols would
622 // require a local relocation is handled just like if the symbols were
623 // external. This is certainly used in the case of debug sections where the
624 // section has only temporary symbols and thus the symbols don't have base
625 // symbols. This is encoded using the section ordinal and non-extern
626 // relocation entries.
627
628 // Darwin 'as' doesn't emit correct relocations for this (it ends up with a
629 // single SIGNED relocation); reject it for now. Except the case where both
630 // symbols don't have a base, equal but both NULL.
631 if (A_Base == B_Base && A_Base)
632 report_fatal_error("unsupported relocation with identical base");
633
634 Value += getSymbolAddress(&A_SD, Layout) -
635 (A_Base == NULL ? 0 : getSymbolAddress(A_Base, Layout));
636 Value -= getSymbolAddress(&B_SD, Layout) -
637 (B_Base == NULL ? 0 : getSymbolAddress(B_Base, Layout));
638
639 if (A_Base) {
640 Index = A_Base->getIndex();
641 IsExtern = 1;
642 }
643 else {
644 Index = A_SD.getFragment()->getParent()->getOrdinal() + 1;
645 IsExtern = 0;
646 }
647 Type = macho::RIT_X86_64_Unsigned;
648
649 macho::RelocationEntry MRE;
650 MRE.Word0 = FixupOffset;
651 MRE.Word1 = ((Index << 0) |
652 (IsPCRel << 24) |
653 (Log2Size << 25) |
654 (IsExtern << 27) |
655 (Type << 28));
656 Relocations[Fragment->getParent()].push_back(MRE);
657
658 if (B_Base) {
659 Index = B_Base->getIndex();
660 IsExtern = 1;
661 }
662 else {
663 Index = B_SD.getFragment()->getParent()->getOrdinal() + 1;
664 IsExtern = 0;
665 }
666 Type = macho::RIT_X86_64_Subtractor;
667 } else {
668 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
669 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
670 const MCSymbolData *Base = Asm.getAtom(&SD);
671
672 // Relocations inside debug sections always use local relocations when
673 // possible. This seems to be done because the debugger doesn't fully
674 // understand x86_64 relocation entries, and expects to find values that
675 // have already been fixed up.
676 if (Symbol->isInSection()) {
677 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
678 Fragment->getParent()->getSection());
679 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
680 Base = 0;
681 }
682
683 // x86_64 almost always uses external relocations, except when there is no
684 // symbol to use as a base address (a local symbol with no preceding
685 // non-local symbol).
686 if (Base) {
687 Index = Base->getIndex();
688 IsExtern = 1;
689
690 // Add the local offset, if needed.
691 if (Base != &SD)
692 Value += Layout.getSymbolOffset(&SD) - Layout.getSymbolOffset(Base);
693 } else if (Symbol->isInSection() && !Symbol->isVariable()) {
694 // The index is the section ordinal (1-based).
695 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
696 IsExtern = 0;
697 Value += getSymbolAddress(&SD, Layout);
698
699 if (IsPCRel)
700 Value -= FixupAddress + (1 << Log2Size);
701 } else if (Symbol->isVariable()) {
702 const MCExpr *Value = Symbol->getVariableValue();
703 int64_t Res;
704 bool isAbs = Value->EvaluateAsAbsolute(Res, Layout, SectionAddress);
705 if (isAbs) {
706 FixedValue = Res;
707 return;
708 } else {
709 report_fatal_error("unsupported relocation of variable '" +
710 Symbol->getName() + "'");
711 }
712 } else {
713 report_fatal_error("unsupported relocation of undefined symbol '" +
714 Symbol->getName() + "'");
715 }
716
717 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
718 if (IsPCRel) {
719 if (IsRIPRel) {
720 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
721 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
722 // rewrite the movq to an leaq at link time if the symbol ends up in
723 // the same linkage unit.
724 if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
725 Type = macho::RIT_X86_64_GOTLoad;
726 else
727 Type = macho::RIT_X86_64_GOT;
728 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
729 Type = macho::RIT_X86_64_TLV;
730 } else if (Modifier != MCSymbolRefExpr::VK_None) {
731 report_fatal_error("unsupported symbol modifier in relocation");
732 } else {
733 Type = macho::RIT_X86_64_Signed;
734
735 // The Darwin x86_64 relocation format has a problem where it cannot
736 // encode an address (L<foo> + <constant>) which is outside the atom
737 // containing L<foo>. Generally, this shouldn't occur but it does
738 // happen when we have a RIPrel instruction with data following the
739 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
740 // adjustment Darwin x86_64 uses, the offset is still negative and the
741 // linker has no way to recognize this.
742 //
743 // To work around this, Darwin uses several special relocation types
744 // to indicate the offsets. However, the specification or
745 // implementation of these seems to also be incomplete; they should
746 // adjust the addend as well based on the actual encoded instruction
747 // (the additional bias), but instead appear to just look at the final
748 // offset.
749 switch (-(Target.getConstant() + (1LL << Log2Size))) {
750 case 1: Type = macho::RIT_X86_64_Signed1; break;
751 case 2: Type = macho::RIT_X86_64_Signed2; break;
752 case 4: Type = macho::RIT_X86_64_Signed4; break;
753 }
754 }
755 } else {
756 if (Modifier != MCSymbolRefExpr::VK_None)
757 report_fatal_error("unsupported symbol modifier in branch "
758 "relocation");
759
760 Type = macho::RIT_X86_64_Branch;
761 }
762 } else {
763 if (Modifier == MCSymbolRefExpr::VK_GOT) {
764 Type = macho::RIT_X86_64_GOT;
765 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
766 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in which
767 // case all we do is set the PCrel bit in the relocation entry; this is
768 // used with exception handling, for example. The source is required to
769 // include any necessary offset directly.
770 Type = macho::RIT_X86_64_GOT;
771 IsPCRel = 1;
772 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
773 report_fatal_error("TLVP symbol modifier should have been rip-rel");
774 } else if (Modifier != MCSymbolRefExpr::VK_None)
775 report_fatal_error("unsupported symbol modifier in relocation");
776 else
777 Type = macho::RIT_X86_64_Unsigned;
778 }
779 }
780
781 // x86_64 always writes custom values into the fixups.
782 FixedValue = Value;
783
784 // struct relocation_info (8 bytes)
785 macho::RelocationEntry MRE;
786 MRE.Word0 = FixupOffset;
787 MRE.Word1 = ((Index << 0) |
788 (IsPCRel << 24) |
789 (Log2Size << 25) |
790 (IsExtern << 27) |
791 (Type << 28));
792 Relocations[Fragment->getParent()].push_back(MRE);
793}
794
795void MachObjectWriter::RecordScatteredRelocation(const MCAssembler &Asm,
796 const MCAsmLayout &Layout,
797 const MCFragment *Fragment,
798 const MCFixup &Fixup,
799 MCValue Target,
800 unsigned Log2Size,
801 uint64_t &FixedValue) {
802 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
803 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
804 unsigned Type = macho::RIT_Vanilla;
805
806 // See <reloc.h>.
807 const MCSymbol *A = &Target.getSymA()->getSymbol();
808 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
809
810 if (!A_SD->getFragment())
811 report_fatal_error("symbol '" + A->getName() +
812 "' can not be undefined in a subtraction expression");
813
814 uint32_t Value = getSymbolAddress(A_SD, Layout);
815 uint64_t SecAddr = getSectionAddress(A_SD->getFragment()->getParent());
816 FixedValue += SecAddr;
817 uint32_t Value2 = 0;
818
819 if (const MCSymbolRefExpr *B = Target.getSymB()) {
820 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
821
822 if (!B_SD->getFragment())
823 report_fatal_error("symbol '" + B->getSymbol().getName() +
824 "' can not be undefined in a subtraction expression");
825
826 // Select the appropriate difference relocation type.
827 //
828 // Note that there is no longer any semantic difference between these two
829 // relocation types from the linkers point of view, this is done solely for
830 // pedantic compatibility with 'as'.
831 Type = A_SD->isExternal() ? (unsigned)macho::RIT_Difference :
832 (unsigned)macho::RIT_Generic_LocalDifference;
833 Value2 = getSymbolAddress(B_SD, Layout);
834 FixedValue -= getSectionAddress(B_SD->getFragment()->getParent());
835 }
836
837 // Relocations are written out in reverse order, so the PAIR comes first.
838 if (Type == macho::RIT_Difference ||
839 Type == macho::RIT_Generic_LocalDifference) {
840 macho::RelocationEntry MRE;
841 MRE.Word0 = ((0 << 0) |
842 (macho::RIT_Pair << 24) |
843 (Log2Size << 28) |
844 (IsPCRel << 30) |
845 macho::RF_Scattered);
846 MRE.Word1 = Value2;
847 Relocations[Fragment->getParent()].push_back(MRE);
848 }
849
850 macho::RelocationEntry MRE;
851 MRE.Word0 = ((FixupOffset << 0) |
852 (Type << 24) |
853 (Log2Size << 28) |
854 (IsPCRel << 30) |
855 macho::RF_Scattered);
856 MRE.Word1 = Value;
857 Relocations[Fragment->getParent()].push_back(MRE);
858}
859
860void MachObjectWriter::RecordARMScatteredRelocation(const MCAssembler &Asm,
861 const MCAsmLayout &Layout,
862 const MCFragment *Fragment,
863 const MCFixup &Fixup,
864 MCValue Target,
865 unsigned Log2Size,
866 uint64_t &FixedValue) {
867 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
868 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
869 unsigned Type = macho::RIT_Vanilla;
870
871 // See <reloc.h>.
872 const MCSymbol *A = &Target.getSymA()->getSymbol();
873 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
874
875 if (!A_SD->getFragment())
876 report_fatal_error("symbol '" + A->getName() +
877 "' can not be undefined in a subtraction expression");
878
879 uint32_t Value = getSymbolAddress(A_SD, Layout);
880 uint64_t SecAddr = getSectionAddress(A_SD->getFragment()->getParent());
881 FixedValue += SecAddr;
882 uint32_t Value2 = 0;
883
884 if (const MCSymbolRefExpr *B = Target.getSymB()) {
885 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
886
887 if (!B_SD->getFragment())
888 report_fatal_error("symbol '" + B->getSymbol().getName() +
889 "' can not be undefined in a subtraction expression");
890
891 // Select the appropriate difference relocation type.
892 Type = macho::RIT_Difference;
893 Value2 = getSymbolAddress(B_SD, Layout);
894 FixedValue -= getSectionAddress(B_SD->getFragment()->getParent());
895 }
896
897 // Relocations are written out in reverse order, so the PAIR comes first.
898 if (Type == macho::RIT_Difference ||
899 Type == macho::RIT_Generic_LocalDifference) {
900 macho::RelocationEntry MRE;
901 MRE.Word0 = ((0 << 0) |
902 (macho::RIT_Pair << 24) |
903 (Log2Size << 28) |
904 (IsPCRel << 30) |
905 macho::RF_Scattered);
906 MRE.Word1 = Value2;
907 Relocations[Fragment->getParent()].push_back(MRE);
908 }
909
910 macho::RelocationEntry MRE;
911 MRE.Word0 = ((FixupOffset << 0) |
912 (Type << 24) |
913 (Log2Size << 28) |
914 (IsPCRel << 30) |
915 macho::RF_Scattered);
916 MRE.Word1 = Value;
917 Relocations[Fragment->getParent()].push_back(MRE);
918}
919
920void MachObjectWriter::RecordARMMovwMovtRelocation(const MCAssembler &Asm,
921 const MCAsmLayout &Layout,
922 const MCFragment *Fragment,
923 const MCFixup &Fixup,
924 MCValue Target,
925 uint64_t &FixedValue) {
926 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
927 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
928 unsigned Type = macho::RIT_ARM_Half;
929
930 // See <reloc.h>.
931 const MCSymbol *A = &Target.getSymA()->getSymbol();
932 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
933
934 if (!A_SD->getFragment())
935 report_fatal_error("symbol '" + A->getName() +
936 "' can not be undefined in a subtraction expression");
937
938 uint32_t Value = getSymbolAddress(A_SD, Layout);
939 uint32_t Value2 = 0;
940 uint64_t SecAddr = getSectionAddress(A_SD->getFragment()->getParent());
941 FixedValue += SecAddr;
942
943 if (const MCSymbolRefExpr *B = Target.getSymB()) {
944 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
945
946 if (!B_SD->getFragment())
947 report_fatal_error("symbol '" + B->getSymbol().getName() +
948 "' can not be undefined in a subtraction expression");
949
950 // Select the appropriate difference relocation type.
951 Type = macho::RIT_ARM_HalfDifference;
952 Value2 = getSymbolAddress(B_SD, Layout);
953 FixedValue -= getSectionAddress(B_SD->getFragment()->getParent());
954 }
955
956 // Relocations are written out in reverse order, so the PAIR comes first.
957 // ARM_RELOC_HALF and ARM_RELOC_HALF_SECTDIFF abuse the r_length field:
958 //
959 // For these two r_type relocations they always have a pair following them and
960 // the r_length bits are used differently. The encoding of the r_length is as
961 // follows:
962 // low bit of r_length:
963 // 0 - :lower16: for movw instructions
964 // 1 - :upper16: for movt instructions
965 // high bit of r_length:
966 // 0 - arm instructions
967 // 1 - thumb instructions
968 // the other half of the relocated expression is in the following pair
969 // relocation entry in the the low 16 bits of r_address field.
970 unsigned ThumbBit = 0;
971 unsigned MovtBit = 0;
972 switch ((unsigned)Fixup.getKind()) {
973 default: break;
974 case ARM::fixup_arm_movt_hi16:
975 case ARM::fixup_arm_movt_hi16_pcrel:
976 MovtBit = 1;
977 break;
978 case ARM::fixup_t2_movt_hi16:
979 case ARM::fixup_t2_movt_hi16_pcrel:
980 MovtBit = 1;
981 // Fallthrough
982 case ARM::fixup_t2_movw_lo16:
983 case ARM::fixup_t2_movw_lo16_pcrel:
984 ThumbBit = 1;
985 break;
986 }
987
988
989 if (Type == macho::RIT_ARM_HalfDifference) {
990 uint32_t OtherHalf = MovtBit
991 ? (FixedValue & 0xffff) : ((FixedValue & 0xffff0000) >> 16);
992
993 macho::RelocationEntry MRE;
994 MRE.Word0 = ((OtherHalf << 0) |
995 (macho::RIT_Pair << 24) |
996 (MovtBit << 28) |
997 (ThumbBit << 29) |
998 (IsPCRel << 30) |
999 macho::RF_Scattered);
1000 MRE.Word1 = Value2;
1001 Relocations[Fragment->getParent()].push_back(MRE);
1002 }
1003
1004 macho::RelocationEntry MRE;
1005 MRE.Word0 = ((FixupOffset << 0) |
1006 (Type << 24) |
1007 (MovtBit << 28) |
1008 (ThumbBit << 29) |
1009 (IsPCRel << 30) |
1010 macho::RF_Scattered);
1011 MRE.Word1 = Value;
1012 Relocations[Fragment->getParent()].push_back(MRE);
1013}
1014
1015void MachObjectWriter::RecordTLVPRelocation(const MCAssembler &Asm,
1016 const MCAsmLayout &Layout,
1017 const MCFragment *Fragment,
1018 const MCFixup &Fixup,
1019 MCValue Target,
1020 uint64_t &FixedValue) {
1021 assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
1022 !is64Bit() &&
1023 "Should only be called with a 32-bit TLVP relocation!");
1024
1025 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
1026 uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
1027 unsigned IsPCRel = 0;
1028
1029 // Get the symbol data.
1030 MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
1031 unsigned Index = SD_A->getIndex();
1032
1033 // We're only going to have a second symbol in pic mode and it'll be a
1034 // subtraction from the picbase. For 32-bit pic the addend is the difference
1035 // between the picbase and the next address. For 32-bit static the addend is
1036 // zero.
1037 if (Target.getSymB()) {
1038 // If this is a subtraction then we're pcrel.
1039 uint32_t FixupAddress =
1040 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
1041 MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
1042 IsPCRel = 1;
1043 FixedValue = (FixupAddress - getSymbolAddress(SD_B, Layout) +
1044 Target.getConstant());
1045 FixedValue += 1ULL << Log2Size;
1046 } else {
1047 FixedValue = 0;
1048 }
1049
1050 // struct relocation_info (8 bytes)
1051 macho::RelocationEntry MRE;
1052 MRE.Word0 = Value;
1053 MRE.Word1 = ((Index << 0) |
1054 (IsPCRel << 24) |
1055 (Log2Size << 25) |
1056 (1 << 27) | // Extern
1057 (macho::RIT_Generic_TLV << 28)); // Type
1058 Relocations[Fragment->getParent()].push_back(MRE);
1059}
1060
1061bool MachObjectWriter::getARMFixupKindMachOInfo(unsigned Kind, unsigned &RelocType,
1062 unsigned &Log2Size) {
1063 RelocType = unsigned(macho::RIT_Vanilla);
1064 Log2Size = ~0U;
1065
1066 switch (Kind) {
1067 default:
1068 return false;
1069
1070 case FK_Data_1:
1071 Log2Size = llvm::Log2_32(1);
1072 return true;
1073 case FK_Data_2:
1074 Log2Size = llvm::Log2_32(2);
1075 return true;
1076 case FK_Data_4:
1077 Log2Size = llvm::Log2_32(4);
1078 return true;
1079 case FK_Data_8:
1080 Log2Size = llvm::Log2_32(8);
1081 return true;
1082
1083 // Handle 24-bit branch kinds.
1084 case ARM::fixup_arm_ldst_pcrel_12:
1085 case ARM::fixup_arm_pcrel_10:
1086 case ARM::fixup_arm_adr_pcrel_12:
1087 case ARM::fixup_arm_condbranch:
1088 case ARM::fixup_arm_uncondbranch:
1089 RelocType = unsigned(macho::RIT_ARM_Branch24Bit);
1090 // Report as 'long', even though that is not quite accurate.
1091 Log2Size = llvm::Log2_32(4);
1092 return true;
1093
1094 // Handle Thumb branches.
1095 case ARM::fixup_arm_thumb_br:
1096 RelocType = unsigned(macho::RIT_ARM_ThumbBranch22Bit);
1097 Log2Size = llvm::Log2_32(2);
1098 return true;
1099
1100 case ARM::fixup_arm_thumb_bl:
1101 case ARM::fixup_arm_thumb_blx:
1102 RelocType = unsigned(macho::RIT_ARM_ThumbBranch22Bit);
1103 Log2Size = llvm::Log2_32(4);
1104 return true;
1105
1106 case ARM::fixup_arm_movt_hi16:
1107 case ARM::fixup_arm_movt_hi16_pcrel:
1108 case ARM::fixup_t2_movt_hi16:
1109 case ARM::fixup_t2_movt_hi16_pcrel:
1110 RelocType = unsigned(macho::RIT_ARM_HalfDifference);
1111 // Report as 'long', even though that is not quite accurate.
1112 Log2Size = llvm::Log2_32(4);
1113 return true;
1114
1115 case ARM::fixup_arm_movw_lo16:
1116 case ARM::fixup_arm_movw_lo16_pcrel:
1117 case ARM::fixup_t2_movw_lo16:
1118 case ARM::fixup_t2_movw_lo16_pcrel:
1119 RelocType = unsigned(macho::RIT_ARM_Half);
1120 // Report as 'long', even though that is not quite accurate.
1121 Log2Size = llvm::Log2_32(4);
1122 return true;
1123 }
1124}
1125void MachObjectWriter::RecordARMRelocation(const MCAssembler &Asm,
1126 const MCAsmLayout &Layout,
1127 const MCFragment *Fragment,
1128 const MCFixup &Fixup,
1129 MCValue Target,
1130 uint64_t &FixedValue) {
1131 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
1132 unsigned Log2Size;
1133 unsigned RelocType = macho::RIT_Vanilla;
1134 if (!getARMFixupKindMachOInfo(Fixup.getKind(), RelocType, Log2Size)) {
1135 report_fatal_error("unknown ARM fixup kind!");
1136 return;
1137 }
1138
1139 // If this is a difference or a defined symbol plus an offset, then we need a
1140 // scattered relocation entry. Differences always require scattered
1141 // relocations.
1142 if (Target.getSymB()) {
1143 if (RelocType == macho::RIT_ARM_Half ||
1144 RelocType == macho::RIT_ARM_HalfDifference)
1145 return RecordARMMovwMovtRelocation(Asm, Layout, Fragment, Fixup,
1146 Target, FixedValue);
1147 return RecordARMScatteredRelocation(Asm, Layout, Fragment, Fixup,
1148 Target, Log2Size, FixedValue);
1149 }
1150
1151 // Get the symbol data, if any.
1152 MCSymbolData *SD = 0;
1153 if (Target.getSymA())
1154 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
1155
1156 // FIXME: For other platforms, we need to use scattered relocations for
1157 // internal relocations with offsets. If this is an internal relocation with
1158 // an offset, it also needs a scattered relocation entry.
1159 //
1160 // Is this right for ARM?
1161 uint32_t Offset = Target.getConstant();
1162 if (IsPCRel && RelocType == macho::RIT_Vanilla)
1163 Offset += 1 << Log2Size;
1164 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
1165 return RecordARMScatteredRelocation(Asm, Layout, Fragment, Fixup, Target,
1166 Log2Size, FixedValue);
1167
1168 // See <reloc.h>.
1169 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
1170 unsigned Index = 0;
1171 unsigned IsExtern = 0;
1172 unsigned Type = 0;
1173
1174 if (Target.isAbsolute()) { // constant
1175 // FIXME!
1176 report_fatal_error("FIXME: relocations to absolute targets "
1177 "not yet implemented");
1178 } else {
1179 // Resolve constant variables.
1180 if (SD->getSymbol().isVariable()) {
1181 int64_t Res;
1182 if (SD->getSymbol().getVariableValue()->EvaluateAsAbsolute(
1183 Res, Layout, SectionAddress)) {
1184 FixedValue = Res;
1185 return;
1186 }
1187 }
1188
1189 // Check whether we need an external or internal relocation.
1190 if (doesSymbolRequireExternRelocation(SD)) {
1191 IsExtern = 1;
1192 Index = SD->getIndex();
1193
1194 // For external relocations, make sure to offset the fixup value to
1195 // compensate for the addend of the symbol address, if it was
1196 // undefined. This occurs with weak definitions, for example.
1197 if (!SD->Symbol->isUndefined())
1198 FixedValue -= Layout.getSymbolOffset(SD);
1199 } else {
1200 // The index is the section ordinal (1-based).
1201 const MCSectionData &SymSD = Asm.getSectionData(
1202 SD->getSymbol().getSection());
1203 Index = SymSD.getOrdinal() + 1;
1204 FixedValue += getSectionAddress(&SymSD);
1205 }
1206 if (IsPCRel)
1207 FixedValue -= getSectionAddress(Fragment->getParent());
1208
1209 // The type is determined by the fixup kind.
1210 Type = RelocType;
1211 }
1212
1213 // struct relocation_info (8 bytes)
1214 macho::RelocationEntry MRE;
1215 MRE.Word0 = FixupOffset;
1216 MRE.Word1 = ((Index << 0) |
1217 (IsPCRel << 24) |
1218 (Log2Size << 25) |
1219 (IsExtern << 27) |
1220 (Type << 28));
1221 Relocations[Fragment->getParent()].push_back(MRE);
1222}
1223
1224void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
1225 const MCAsmLayout &Layout,
1226 const MCFragment *Fragment,
1227 const MCFixup &Fixup,
1228 MCValue Target,
1229 uint64_t &FixedValue) {
1230 // FIXME: These needs to be factored into the target Mach-O writer.
1231 if (isARM()) {
1232 RecordARMRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
1233 return;
1234 }
1235 if (is64Bit()) {
1236 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
1237 return;
1238 }
1239
1240 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
1241 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
1242
1243 // If this is a 32-bit TLVP reloc it's handled a bit differently.
1244 if (Target.getSymA() &&
1245 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
1246 RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
1247 return;
1248 }
1249
1250 // If this is a difference or a defined symbol plus an offset, then we need a
1251 // scattered relocation entry. Differences always require scattered
1252 // relocations.
1253 if (Target.getSymB())
1254 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
1255 Target, Log2Size, FixedValue);
1256
1257 // Get the symbol data, if any.
1258 MCSymbolData *SD = 0;
1259 if (Target.getSymA())
1260 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
1261
1262 // If this is an internal relocation with an offset, it also needs a scattered
1263 // relocation entry.
1264 uint32_t Offset = Target.getConstant();
1265 if (IsPCRel)
1266 Offset += 1 << Log2Size;
1267 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
1268 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
1269 Target, Log2Size, FixedValue);
1270
1271 // See <reloc.h>.
1272 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
1273 unsigned Index = 0;
1274 unsigned IsExtern = 0;
1275 unsigned Type = 0;
1276
1277 if (Target.isAbsolute()) { // constant
1278 // SymbolNum of 0 indicates the absolute section.
1279 //
1280 // FIXME: Currently, these are never generated (see code below). I cannot
1281 // find a case where they are actually emitted.
1282 Type = macho::RIT_Vanilla;
1283 } else {
1284 // Resolve constant variables.
1285 if (SD->getSymbol().isVariable()) {
1286 int64_t Res;
1287 if (SD->getSymbol().getVariableValue()->EvaluateAsAbsolute(
1288 Res, Layout, SectionAddress)) {
1289 FixedValue = Res;
1290 return;
1291 }
1292 }
1293
1294 // Check whether we need an external or internal relocation.
1295 if (doesSymbolRequireExternRelocation(SD)) {
1296 IsExtern = 1;
1297 Index = SD->getIndex();
1298 // For external relocations, make sure to offset the fixup value to
1299 // compensate for the addend of the symbol address, if it was
1300 // undefined. This occurs with weak definitions, for example.
1301 if (!SD->Symbol->isUndefined())
1302 FixedValue -= Layout.getSymbolOffset(SD);
1303 } else {
1304 // The index is the section ordinal (1-based).
1305 const MCSectionData &SymSD = Asm.getSectionData(
1306 SD->getSymbol().getSection());
1307 Index = SymSD.getOrdinal() + 1;
1308 FixedValue += getSectionAddress(&SymSD);
1309 }
1310 if (IsPCRel)
1311 FixedValue -= getSectionAddress(Fragment->getParent());
1312
1313 Type = macho::RIT_Vanilla;
1314 }
1315
1316 // struct relocation_info (8 bytes)
1317 macho::RelocationEntry MRE;
1318 MRE.Word0 = FixupOffset;
1319 MRE.Word1 = ((Index << 0) |
1320 (IsPCRel << 24) |
1321 (Log2Size << 25) |
1322 (IsExtern << 27) |
1323 (Type << 28));
1324 Relocations[Fragment->getParent()].push_back(MRE);
1325}
1326
1327void MachObjectWriter::BindIndirectSymbols(MCAssembler &Asm) {
1328 // This is the point where 'as' creates actual symbols for indirect symbols
1329 // (in the following two passes). It would be easier for us to do this sooner
1330 // when we see the attribute, but that makes getting the order in the symbol
1331 // table much more complicated than it is worth.
1332 //
1333 // FIXME: Revisit this when the dust settles.
1334
1335 // Bind non lazy symbol pointers first.
1336 unsigned IndirectIndex = 0;
1337 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
1338 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
1339 const MCSectionMachO &Section =
1340 cast<MCSectionMachO>(it->SectionData->getSection());
1341
1342 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
1343 continue;
1344
1345 // Initialize the section indirect symbol base, if necessary.
1346 if (!IndirectSymBase.count(it->SectionData))
1347 IndirectSymBase[it->SectionData] = IndirectIndex;
1348
1349 Asm.getOrCreateSymbolData(*it->Symbol);
1350 }
1351
1352 // Then lazy symbol pointers and symbol stubs.
1353 IndirectIndex = 0;
1354 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
1355 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
1356 const MCSectionMachO &Section =
1357 cast<MCSectionMachO>(it->SectionData->getSection());
1358
1359 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
1360 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
1361 continue;
1362
1363 // Initialize the section indirect symbol base, if necessary.
1364 if (!IndirectSymBase.count(it->SectionData))
1365 IndirectSymBase[it->SectionData] = IndirectIndex;
1366
1367 // Set the symbol type to undefined lazy, but only on construction.
1368 //
1369 // FIXME: Do not hardcode.
1370 bool Created;
1371 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
1372 if (Created)
1373 Entry.setFlags(Entry.getFlags() | 0x0001);
1374 }
1375}
1376
1377/// ComputeSymbolTable - Compute the symbol table data
1378///
1379/// \param StringTable [out] - The string table data.
1380/// \param StringIndexMap [out] - Map from symbol names to offsets in the
1381/// string table.
1382void MachObjectWriter::ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
1383 std::vector<MachSymbolData> &LocalSymbolData,
1384 std::vector<MachSymbolData> &ExternalSymbolData,
1385 std::vector<MachSymbolData> &UndefinedSymbolData) {
1386 // Build section lookup table.
1387 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
1388 unsigned Index = 1;
1389 for (MCAssembler::iterator it = Asm.begin(),
1390 ie = Asm.end(); it != ie; ++it, ++Index)
1391 SectionIndexMap[&it->getSection()] = Index;
1392 assert(Index <= 256 && "Too many sections!");
1393
1394 // Index 0 is always the empty string.
1395 StringMap<uint64_t> StringIndexMap;
1396 StringTable += '\x00';
1397
1398 // Build the symbol arrays and the string table, but only for non-local
1399 // symbols.
1400 //
1401 // The particular order that we collect the symbols and create the string
1402 // table, then sort the symbols is chosen to match 'as'. Even though it
1403 // doesn't matter for correctness, this is important for letting us diff .o
1404 // files.
1405 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1406 ie = Asm.symbol_end(); it != ie; ++it) {
1407 const MCSymbol &Symbol = it->getSymbol();
1408
1409 // Ignore non-linker visible symbols.
1410 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1411 continue;
1412
1413 if (!it->isExternal() && !Symbol.isUndefined())
1414 continue;
1415
1416 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1417 if (!Entry) {
1418 Entry = StringTable.size();
1419 StringTable += Symbol.getName();
1420 StringTable += '\x00';
1421 }
1422
1423 MachSymbolData MSD;
1424 MSD.SymbolData = it;
1425 MSD.StringIndex = Entry;
1426
1427 if (Symbol.isUndefined()) {
1428 MSD.SectionIndex = 0;
1429 UndefinedSymbolData.push_back(MSD);
1430 } else if (Symbol.isAbsolute()) {
1431 MSD.SectionIndex = 0;
1432 ExternalSymbolData.push_back(MSD);
1433 } else {
1434 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1435 assert(MSD.SectionIndex && "Invalid section index!");
1436 ExternalSymbolData.push_back(MSD);
1437 }
1438 }
1439
1440 // Now add the data for local symbols.
1441 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1442 ie = Asm.symbol_end(); it != ie; ++it) {
1443 const MCSymbol &Symbol = it->getSymbol();
1444
1445 // Ignore non-linker visible symbols.
1446 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1447 continue;
1448
1449 if (it->isExternal() || Symbol.isUndefined())
1450 continue;
1451
1452 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1453 if (!Entry) {
1454 Entry = StringTable.size();
1455 StringTable += Symbol.getName();
1456 StringTable += '\x00';
1457 }
1458
1459 MachSymbolData MSD;
1460 MSD.SymbolData = it;
1461 MSD.StringIndex = Entry;
1462
1463 if (Symbol.isAbsolute()) {
1464 MSD.SectionIndex = 0;
1465 LocalSymbolData.push_back(MSD);
1466 } else {
1467 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1468 assert(MSD.SectionIndex && "Invalid section index!");
1469 LocalSymbolData.push_back(MSD);
1470 }
1471 }
1472
1473 // External and undefined symbols are required to be in lexicographic order.
1474 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1475 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1476
1477 // Set the symbol indices.
1478 Index = 0;
1479 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1480 LocalSymbolData[i].SymbolData->setIndex(Index++);
1481 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1482 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1483 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1484 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1485
1486 // The string table is padded to a multiple of 4.
1487 while (StringTable.size() % 4)
1488 StringTable += '\x00';
1489}
1490
1491void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
1492 const MCAsmLayout &Layout) {
1493 uint64_t StartAddress = 0;
1494 const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
1495 for (int i = 0, n = Order.size(); i != n ; ++i) {
1496 const MCSectionData *SD = Order[i];
1497 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
1498 SectionAddress[SD] = StartAddress;
1499 StartAddress += Layout.getSectionAddressSize(SD);
1500
1501 // Explicitly pad the section to match the alignment requirements of the
1502 // following one. This is for 'gas' compatibility, it shouldn't
1503 /// strictly be necessary.
1504 StartAddress += getPaddingSize(SD, Layout);
1505 }
1506}
1507
1508void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout) {
1509 computeSectionAddresses(Asm, Layout);
1510
1511 // Create symbol data for any indirect symbols.
1512 BindIndirectSymbols(Asm);
1513
1514 // Compute symbol table information and bind symbol indices.
1515 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1516 UndefinedSymbolData);
1517}
1518
1519bool MachObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1520 const MCSymbolData &DataA,
1521 const MCFragment &FB,
1522 bool InSet,
1523 bool IsPCRel) const {
1524 if (InSet)
1525 return true;
1526
1527 // The effective address is
1528 // addr(atom(A)) + offset(A)
1529 // - addr(atom(B)) - offset(B)
1530 // and the offsets are not relocatable, so the fixup is fully resolved when
1531 // addr(atom(A)) - addr(atom(B)) == 0.
1532 const MCSymbolData *A_Base = 0, *B_Base = 0;
1533
1534 const MCSymbol &SA = DataA.getSymbol().AliasedSymbol();
1535 const MCSection &SecA = SA.getSection();
1536 const MCSection &SecB = FB.getParent()->getSection();
1537
1538 if (IsPCRel) {
1539 // The simple (Darwin, except on x86_64) way of dealing with this was to
1540 // assume that any reference to a temporary symbol *must* be a temporary
1541 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
1542 // relocation to a temporary symbol (in the same section) is fully
1543 // resolved. This also works in conjunction with absolutized .set, which
1544 // requires the compiler to use .set to absolutize the differences between
1545 // symbols which the compiler knows to be assembly time constants, so we
1546 // don't need to worry about considering symbol differences fully resolved.
1547
1548 if (!Asm.getBackend().hasReliableSymbolDifference()) {
1549 if (!SA.isTemporary() || !SA.isInSection() || &SecA != &SecB)
1550 return false;
1551 return true;
1552 }
1553 } else {
1554 if (!TargetObjectWriter->useAggressiveSymbolFolding())
1555 return false;
1556 }
1557
1558 const MCFragment &FA = *Asm.getSymbolData(SA).getFragment();
1559
1560 A_Base = FA.getAtom();
1561 if (!A_Base)
1562 return false;
1563
1564 B_Base = FB.getAtom();
1565 if (!B_Base)
1566 return false;
1567
1568 // If the atoms are the same, they are guaranteed to have the same address.
1569 if (A_Base == B_Base)
1570 return true;
1571
1572 // Otherwise, we can't prove this is fully resolved.
1573 return false;
1574}
1575
1576void MachObjectWriter::WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
1577 unsigned NumSections = Asm.size();
1578
1579 // The section data starts after the header, the segment load command (and
1580 // section headers) and the symbol table.
1581 unsigned NumLoadCommands = 1;
1582 uint64_t LoadCommandsSize = is64Bit() ?
1583 macho::SegmentLoadCommand64Size + NumSections * macho::Section64Size :
1584 macho::SegmentLoadCommand32Size + NumSections * macho::Section32Size;
1585
1586 // Add the symbol table load command sizes, if used.
1587 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1588 UndefinedSymbolData.size();
1589 if (NumSymbols) {
1590 NumLoadCommands += 2;
1591 LoadCommandsSize += (macho::SymtabLoadCommandSize +
1592 macho::DysymtabLoadCommandSize);
1593 }
1594
1595 // Compute the total size of the section data, as well as its file size and vm
1596 // size.
1597 uint64_t SectionDataStart = (is64Bit() ? macho::Header64Size :
1598 macho::Header32Size) + LoadCommandsSize;
1599 uint64_t SectionDataSize = 0;
1600 uint64_t SectionDataFileSize = 0;
1601 uint64_t VMSize = 0;
1602 for (MCAssembler::const_iterator it = Asm.begin(),
1603 ie = Asm.end(); it != ie; ++it) {
1604 const MCSectionData &SD = *it;
1605 uint64_t Address = getSectionAddress(&SD);
1606 uint64_t Size = Layout.getSectionAddressSize(&SD);
1607 uint64_t FileSize = Layout.getSectionFileSize(&SD);
1608 FileSize += getPaddingSize(&SD, Layout);
1609
1610 VMSize = std::max(VMSize, Address + Size);
1611
1612 if (SD.getSection().isVirtualSection())
1613 continue;
1614
1615 SectionDataSize = std::max(SectionDataSize, Address + Size);
1616 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
1617 }
1618
1619 // The section data is padded to 4 bytes.
1620 //
1621 // FIXME: Is this machine dependent?
1622 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1623 SectionDataFileSize += SectionDataPadding;
1624
1625 // Write the prolog, starting with the header and load command...
1626 WriteHeader(NumLoadCommands, LoadCommandsSize,
1627 Asm.getSubsectionsViaSymbols());
1628 WriteSegmentLoadCommand(NumSections, VMSize,
1629 SectionDataStart, SectionDataSize);
1630
1631 // ... and then the section headers.
1632 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1633 for (MCAssembler::const_iterator it = Asm.begin(),
1634 ie = Asm.end(); it != ie; ++it) {
1635 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
1636 unsigned NumRelocs = Relocs.size();
1637 uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
1638 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
1639 RelocTableEnd += NumRelocs * macho::RelocationInfoSize;
1640 }
1641
1642 // Write the symbol table load command, if used.
1643 if (NumSymbols) {
1644 unsigned FirstLocalSymbol = 0;
1645 unsigned NumLocalSymbols = LocalSymbolData.size();
1646 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1647 unsigned NumExternalSymbols = ExternalSymbolData.size();
1648 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1649 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1650 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1651 unsigned NumSymTabSymbols =
1652 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1653 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1654 uint64_t IndirectSymbolOffset = 0;
1655
1656 // If used, the indirect symbols are written after the section data.
1657 if (NumIndirectSymbols)
1658 IndirectSymbolOffset = RelocTableEnd;
1659
1660 // The symbol table is written after the indirect symbol data.
1661 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1662
1663 // The string table is written after symbol table.
1664 uint64_t StringTableOffset =
1665 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ? macho::Nlist64Size :
1666 macho::Nlist32Size);
1667 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1668 StringTableOffset, StringTable.size());
1669
1670 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1671 FirstExternalSymbol, NumExternalSymbols,
1672 FirstUndefinedSymbol, NumUndefinedSymbols,
1673 IndirectSymbolOffset, NumIndirectSymbols);
1674 }
1675
1676 // Write the actual section data.
1677 for (MCAssembler::const_iterator it = Asm.begin(),
1678 ie = Asm.end(); it != ie; ++it) {
1679 Asm.WriteSectionData(it, Layout);
1680
1681 uint64_t Pad = getPaddingSize(it, Layout);
1682 for (unsigned int i = 0; i < Pad; ++i)
1683 Write8(0);
1684 }
1685
1686 // Write the extra padding.
1687 WriteZeros(SectionDataPadding);
1688
1689 // Write the relocation entries.
1690 for (MCAssembler::const_iterator it = Asm.begin(),
1691 ie = Asm.end(); it != ie; ++it) {
1692 // Write the section relocation entries, in reverse order to match 'as'
1693 // (approximately, the exact algorithm is more complicated than this).
1694 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
1695 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1696 Write32(Relocs[e - i - 1].Word0);
1697 Write32(Relocs[e - i - 1].Word1);
1698 }
1699 }
1700
1701 // Write the symbol table data, if used.
1702 if (NumSymbols) {
1703 // Write the indirect symbol entries.
1704 for (MCAssembler::const_indirect_symbol_iterator
1705 it = Asm.indirect_symbol_begin(),
1706 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1707 // Indirect symbols in the non lazy symbol pointer section have some
1708 // special handling.
1709 const MCSectionMachO &Section =
1710 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1711 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1712 // If this symbol is defined and internal, mark it as such.
1713 if (it->Symbol->isDefined() &&
1714 !Asm.getSymbolData(*it->Symbol).isExternal()) {
1715 uint32_t Flags = macho::ISF_Local;
1716 if (it->Symbol->isAbsolute())
1717 Flags |= macho::ISF_Absolute;
1718 Write32(Flags);
1719 continue;
1720 }
1721 }
1722
1723 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1724 }
1725
1726 // FIXME: Check that offsets match computed ones.
1727
1728 // Write the symbol table entries.
1729 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1730 WriteNlist(LocalSymbolData[i], Layout);
1731 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1732 WriteNlist(ExternalSymbolData[i], Layout);
1733 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1734 WriteNlist(UndefinedSymbolData[i], Layout);
1735
1736 // Write the string table.
1737 OS << StringTable.str();
1738 }
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001739}
1740
Daniel Dunbarae5abd52010-12-16 16:09:19 +00001741MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
Daniel Dunbar5d05d972010-12-16 17:21:02 +00001742 raw_ostream &OS,
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001743 bool IsLittleEndian) {
Daniel Dunbar5d05d972010-12-16 17:21:02 +00001744 return new MachObjectWriter(MOTW, OS, IsLittleEndian);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001745}