blob: e11b9df82b714ea3b8e83a1612a4e7a8c2c744cd [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,
Jim Grosbach0edb05b2011-06-23 22:29:00 +0000126 const MCAsmLayout &Layout) const {
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000127 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
Bill Wendling3f2ea822011-06-23 00:09:43 +0000493void MachObjectWriter::WriteNlist(MachSymbolData &MSD,
494 const MCAsmLayout &Layout) {
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000495 MCSymbolData &Data = *MSD.SymbolData;
496 const MCSymbol &Symbol = Data.getSymbol();
497 uint8_t Type = 0;
498 uint16_t Flags = Data.getFlags();
499 uint32_t Address = 0;
500
501 // Set the N_TYPE bits. See <mach-o/nlist.h>.
502 //
503 // FIXME: Are the prebound or indirect fields possible here?
504 if (Symbol.isUndefined())
505 Type = macho::STT_Undefined;
506 else if (Symbol.isAbsolute())
507 Type = macho::STT_Absolute;
508 else
509 Type = macho::STT_Section;
510
511 // FIXME: Set STAB bits.
512
513 if (Data.isPrivateExtern())
514 Type |= macho::STF_PrivateExtern;
515
516 // Set external bit.
517 if (Data.isExternal() || Symbol.isUndefined())
518 Type |= macho::STF_External;
519
520 // Compute the symbol address.
521 if (Symbol.isDefined()) {
522 if (Symbol.isAbsolute()) {
523 Address = cast<MCConstantExpr>(Symbol.getVariableValue())->getValue();
524 } else {
525 Address = getSymbolAddress(&Data, Layout);
526 }
527 } else if (Data.isCommon()) {
528 // Common symbols are encoded with the size in the address
529 // field, and their alignment in the flags.
530 Address = Data.getCommonSize();
531
532 // Common alignment is packed into the 'desc' bits.
533 if (unsigned Align = Data.getCommonAlignment()) {
534 unsigned Log2Size = Log2_32(Align);
535 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
536 if (Log2Size > 15)
537 report_fatal_error("invalid 'common' alignment '" +
538 Twine(Align) + "'");
539 // FIXME: Keep this mask with the SymbolFlags enumeration.
540 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
541 }
542 }
543
544 // struct nlist (12 bytes)
545
546 Write32(MSD.StringIndex);
547 Write8(Type);
548 Write8(MSD.SectionIndex);
549
550 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
551 // value.
552 Write16(Flags);
553 if (is64Bit())
554 Write64(Address);
555 else
556 Write32(Address);
557}
558
559void MachObjectWriter::RecordX86_64Relocation(const MCAssembler &Asm,
560 const MCAsmLayout &Layout,
561 const MCFragment *Fragment,
562 const MCFixup &Fixup,
563 MCValue Target,
564 uint64_t &FixedValue) {
565 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
566 unsigned IsRIPRel = isFixupKindRIPRel(Fixup.getKind());
567 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
568
569 // See <reloc.h>.
570 uint32_t FixupOffset =
571 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
572 uint32_t FixupAddress =
573 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
574 int64_t Value = 0;
575 unsigned Index = 0;
576 unsigned IsExtern = 0;
577 unsigned Type = 0;
578
579 Value = Target.getConstant();
580
581 if (IsPCRel) {
582 // Compensate for the relocation offset, Darwin x86_64 relocations only have
583 // the addend and appear to have attempted to define it to be the actual
584 // expression addend without the PCrel bias. However, instructions with data
585 // following the relocation are not accommodated for (see comment below
586 // regarding SIGNED{1,2,4}), so it isn't exactly that either.
587 Value += 1LL << Log2Size;
588 }
589
590 if (Target.isAbsolute()) { // constant
591 // SymbolNum of 0 indicates the absolute section.
592 Type = macho::RIT_X86_64_Unsigned;
593 Index = 0;
594
595 // FIXME: I believe this is broken, I don't think the linker can understand
596 // it. I think it would require a local relocation, but I'm not sure if that
597 // would work either. The official way to get an absolute PCrel relocation
598 // is to use an absolute symbol (which we don't support yet).
599 if (IsPCRel) {
600 IsExtern = 1;
601 Type = macho::RIT_X86_64_Branch;
602 }
603 } else if (Target.getSymB()) { // A - B + constant
604 const MCSymbol *A = &Target.getSymA()->getSymbol();
605 MCSymbolData &A_SD = Asm.getSymbolData(*A);
606 const MCSymbolData *A_Base = Asm.getAtom(&A_SD);
607
608 const MCSymbol *B = &Target.getSymB()->getSymbol();
609 MCSymbolData &B_SD = Asm.getSymbolData(*B);
610 const MCSymbolData *B_Base = Asm.getAtom(&B_SD);
611
612 // Neither symbol can be modified.
613 if (Target.getSymA()->getKind() != MCSymbolRefExpr::VK_None ||
614 Target.getSymB()->getKind() != MCSymbolRefExpr::VK_None)
615 report_fatal_error("unsupported relocation of modified symbol");
616
617 // We don't support PCrel relocations of differences. Darwin 'as' doesn't
618 // implement most of these correctly.
619 if (IsPCRel)
620 report_fatal_error("unsupported pc-relative relocation of difference");
621
622 // The support for the situation where one or both of the symbols would
623 // require a local relocation is handled just like if the symbols were
624 // external. This is certainly used in the case of debug sections where the
625 // section has only temporary symbols and thus the symbols don't have base
626 // symbols. This is encoded using the section ordinal and non-extern
627 // relocation entries.
628
629 // Darwin 'as' doesn't emit correct relocations for this (it ends up with a
630 // single SIGNED relocation); reject it for now. Except the case where both
631 // symbols don't have a base, equal but both NULL.
632 if (A_Base == B_Base && A_Base)
633 report_fatal_error("unsupported relocation with identical base");
634
635 Value += getSymbolAddress(&A_SD, Layout) -
636 (A_Base == NULL ? 0 : getSymbolAddress(A_Base, Layout));
637 Value -= getSymbolAddress(&B_SD, Layout) -
638 (B_Base == NULL ? 0 : getSymbolAddress(B_Base, Layout));
639
640 if (A_Base) {
641 Index = A_Base->getIndex();
642 IsExtern = 1;
643 }
644 else {
645 Index = A_SD.getFragment()->getParent()->getOrdinal() + 1;
646 IsExtern = 0;
647 }
648 Type = macho::RIT_X86_64_Unsigned;
649
650 macho::RelocationEntry MRE;
651 MRE.Word0 = FixupOffset;
652 MRE.Word1 = ((Index << 0) |
653 (IsPCRel << 24) |
654 (Log2Size << 25) |
655 (IsExtern << 27) |
656 (Type << 28));
657 Relocations[Fragment->getParent()].push_back(MRE);
658
659 if (B_Base) {
660 Index = B_Base->getIndex();
661 IsExtern = 1;
662 }
663 else {
664 Index = B_SD.getFragment()->getParent()->getOrdinal() + 1;
665 IsExtern = 0;
666 }
667 Type = macho::RIT_X86_64_Subtractor;
668 } else {
669 const MCSymbol *Symbol = &Target.getSymA()->getSymbol();
670 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
671 const MCSymbolData *Base = Asm.getAtom(&SD);
672
673 // Relocations inside debug sections always use local relocations when
674 // possible. This seems to be done because the debugger doesn't fully
675 // understand x86_64 relocation entries, and expects to find values that
676 // have already been fixed up.
677 if (Symbol->isInSection()) {
678 const MCSectionMachO &Section = static_cast<const MCSectionMachO&>(
679 Fragment->getParent()->getSection());
680 if (Section.hasAttribute(MCSectionMachO::S_ATTR_DEBUG))
681 Base = 0;
682 }
683
684 // x86_64 almost always uses external relocations, except when there is no
685 // symbol to use as a base address (a local symbol with no preceding
686 // non-local symbol).
687 if (Base) {
688 Index = Base->getIndex();
689 IsExtern = 1;
690
691 // Add the local offset, if needed.
692 if (Base != &SD)
693 Value += Layout.getSymbolOffset(&SD) - Layout.getSymbolOffset(Base);
694 } else if (Symbol->isInSection() && !Symbol->isVariable()) {
695 // The index is the section ordinal (1-based).
696 Index = SD.getFragment()->getParent()->getOrdinal() + 1;
697 IsExtern = 0;
698 Value += getSymbolAddress(&SD, Layout);
699
700 if (IsPCRel)
701 Value -= FixupAddress + (1 << Log2Size);
702 } else if (Symbol->isVariable()) {
703 const MCExpr *Value = Symbol->getVariableValue();
704 int64_t Res;
705 bool isAbs = Value->EvaluateAsAbsolute(Res, Layout, SectionAddress);
706 if (isAbs) {
707 FixedValue = Res;
708 return;
709 } else {
710 report_fatal_error("unsupported relocation of variable '" +
711 Symbol->getName() + "'");
712 }
713 } else {
714 report_fatal_error("unsupported relocation of undefined symbol '" +
715 Symbol->getName() + "'");
716 }
717
718 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
719 if (IsPCRel) {
720 if (IsRIPRel) {
721 if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
722 // x86_64 distinguishes movq foo@GOTPCREL so that the linker can
723 // rewrite the movq to an leaq at link time if the symbol ends up in
724 // the same linkage unit.
725 if (unsigned(Fixup.getKind()) == X86::reloc_riprel_4byte_movq_load)
726 Type = macho::RIT_X86_64_GOTLoad;
727 else
728 Type = macho::RIT_X86_64_GOT;
729 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
730 Type = macho::RIT_X86_64_TLV;
731 } else if (Modifier != MCSymbolRefExpr::VK_None) {
732 report_fatal_error("unsupported symbol modifier in relocation");
733 } else {
734 Type = macho::RIT_X86_64_Signed;
735
736 // The Darwin x86_64 relocation format has a problem where it cannot
737 // encode an address (L<foo> + <constant>) which is outside the atom
738 // containing L<foo>. Generally, this shouldn't occur but it does
739 // happen when we have a RIPrel instruction with data following the
740 // relocation entry (e.g., movb $012, L0(%rip)). Even with the PCrel
741 // adjustment Darwin x86_64 uses, the offset is still negative and the
742 // linker has no way to recognize this.
743 //
744 // To work around this, Darwin uses several special relocation types
745 // to indicate the offsets. However, the specification or
746 // implementation of these seems to also be incomplete; they should
747 // adjust the addend as well based on the actual encoded instruction
748 // (the additional bias), but instead appear to just look at the final
749 // offset.
750 switch (-(Target.getConstant() + (1LL << Log2Size))) {
751 case 1: Type = macho::RIT_X86_64_Signed1; break;
752 case 2: Type = macho::RIT_X86_64_Signed2; break;
753 case 4: Type = macho::RIT_X86_64_Signed4; break;
754 }
755 }
756 } else {
757 if (Modifier != MCSymbolRefExpr::VK_None)
758 report_fatal_error("unsupported symbol modifier in branch "
759 "relocation");
760
761 Type = macho::RIT_X86_64_Branch;
762 }
763 } else {
764 if (Modifier == MCSymbolRefExpr::VK_GOT) {
765 Type = macho::RIT_X86_64_GOT;
766 } else if (Modifier == MCSymbolRefExpr::VK_GOTPCREL) {
767 // GOTPCREL is allowed as a modifier on non-PCrel instructions, in which
768 // case all we do is set the PCrel bit in the relocation entry; this is
769 // used with exception handling, for example. The source is required to
770 // include any necessary offset directly.
771 Type = macho::RIT_X86_64_GOT;
772 IsPCRel = 1;
773 } else if (Modifier == MCSymbolRefExpr::VK_TLVP) {
774 report_fatal_error("TLVP symbol modifier should have been rip-rel");
775 } else if (Modifier != MCSymbolRefExpr::VK_None)
776 report_fatal_error("unsupported symbol modifier in relocation");
777 else
778 Type = macho::RIT_X86_64_Unsigned;
779 }
780 }
781
782 // x86_64 always writes custom values into the fixups.
783 FixedValue = Value;
784
785 // struct relocation_info (8 bytes)
786 macho::RelocationEntry MRE;
787 MRE.Word0 = FixupOffset;
788 MRE.Word1 = ((Index << 0) |
789 (IsPCRel << 24) |
790 (Log2Size << 25) |
791 (IsExtern << 27) |
792 (Type << 28));
793 Relocations[Fragment->getParent()].push_back(MRE);
794}
795
796void MachObjectWriter::RecordScatteredRelocation(const MCAssembler &Asm,
797 const MCAsmLayout &Layout,
798 const MCFragment *Fragment,
799 const MCFixup &Fixup,
800 MCValue Target,
801 unsigned Log2Size,
802 uint64_t &FixedValue) {
803 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
804 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
805 unsigned Type = macho::RIT_Vanilla;
806
807 // See <reloc.h>.
808 const MCSymbol *A = &Target.getSymA()->getSymbol();
809 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
810
811 if (!A_SD->getFragment())
812 report_fatal_error("symbol '" + A->getName() +
813 "' can not be undefined in a subtraction expression");
814
815 uint32_t Value = getSymbolAddress(A_SD, Layout);
816 uint64_t SecAddr = getSectionAddress(A_SD->getFragment()->getParent());
817 FixedValue += SecAddr;
818 uint32_t Value2 = 0;
819
820 if (const MCSymbolRefExpr *B = Target.getSymB()) {
821 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
822
823 if (!B_SD->getFragment())
824 report_fatal_error("symbol '" + B->getSymbol().getName() +
825 "' can not be undefined in a subtraction expression");
826
827 // Select the appropriate difference relocation type.
828 //
829 // Note that there is no longer any semantic difference between these two
830 // relocation types from the linkers point of view, this is done solely for
831 // pedantic compatibility with 'as'.
832 Type = A_SD->isExternal() ? (unsigned)macho::RIT_Difference :
833 (unsigned)macho::RIT_Generic_LocalDifference;
834 Value2 = getSymbolAddress(B_SD, Layout);
835 FixedValue -= getSectionAddress(B_SD->getFragment()->getParent());
836 }
837
838 // Relocations are written out in reverse order, so the PAIR comes first.
839 if (Type == macho::RIT_Difference ||
840 Type == macho::RIT_Generic_LocalDifference) {
841 macho::RelocationEntry MRE;
842 MRE.Word0 = ((0 << 0) |
843 (macho::RIT_Pair << 24) |
844 (Log2Size << 28) |
845 (IsPCRel << 30) |
846 macho::RF_Scattered);
847 MRE.Word1 = Value2;
848 Relocations[Fragment->getParent()].push_back(MRE);
849 }
850
851 macho::RelocationEntry MRE;
852 MRE.Word0 = ((FixupOffset << 0) |
853 (Type << 24) |
854 (Log2Size << 28) |
855 (IsPCRel << 30) |
856 macho::RF_Scattered);
857 MRE.Word1 = Value;
858 Relocations[Fragment->getParent()].push_back(MRE);
859}
860
861void MachObjectWriter::RecordARMScatteredRelocation(const MCAssembler &Asm,
862 const MCAsmLayout &Layout,
863 const MCFragment *Fragment,
864 const MCFixup &Fixup,
865 MCValue Target,
866 unsigned Log2Size,
867 uint64_t &FixedValue) {
868 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
869 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
870 unsigned Type = macho::RIT_Vanilla;
871
872 // See <reloc.h>.
873 const MCSymbol *A = &Target.getSymA()->getSymbol();
874 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
875
876 if (!A_SD->getFragment())
877 report_fatal_error("symbol '" + A->getName() +
878 "' can not be undefined in a subtraction expression");
879
880 uint32_t Value = getSymbolAddress(A_SD, Layout);
881 uint64_t SecAddr = getSectionAddress(A_SD->getFragment()->getParent());
882 FixedValue += SecAddr;
883 uint32_t Value2 = 0;
884
885 if (const MCSymbolRefExpr *B = Target.getSymB()) {
886 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
887
888 if (!B_SD->getFragment())
889 report_fatal_error("symbol '" + B->getSymbol().getName() +
890 "' can not be undefined in a subtraction expression");
891
892 // Select the appropriate difference relocation type.
893 Type = macho::RIT_Difference;
894 Value2 = getSymbolAddress(B_SD, Layout);
895 FixedValue -= getSectionAddress(B_SD->getFragment()->getParent());
896 }
897
898 // Relocations are written out in reverse order, so the PAIR comes first.
899 if (Type == macho::RIT_Difference ||
900 Type == macho::RIT_Generic_LocalDifference) {
901 macho::RelocationEntry MRE;
902 MRE.Word0 = ((0 << 0) |
903 (macho::RIT_Pair << 24) |
904 (Log2Size << 28) |
905 (IsPCRel << 30) |
906 macho::RF_Scattered);
907 MRE.Word1 = Value2;
908 Relocations[Fragment->getParent()].push_back(MRE);
909 }
910
911 macho::RelocationEntry MRE;
912 MRE.Word0 = ((FixupOffset << 0) |
913 (Type << 24) |
914 (Log2Size << 28) |
915 (IsPCRel << 30) |
916 macho::RF_Scattered);
917 MRE.Word1 = Value;
918 Relocations[Fragment->getParent()].push_back(MRE);
919}
920
921void MachObjectWriter::RecordARMMovwMovtRelocation(const MCAssembler &Asm,
922 const MCAsmLayout &Layout,
923 const MCFragment *Fragment,
924 const MCFixup &Fixup,
925 MCValue Target,
926 uint64_t &FixedValue) {
927 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
928 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
929 unsigned Type = macho::RIT_ARM_Half;
930
931 // See <reloc.h>.
932 const MCSymbol *A = &Target.getSymA()->getSymbol();
933 MCSymbolData *A_SD = &Asm.getSymbolData(*A);
934
935 if (!A_SD->getFragment())
936 report_fatal_error("symbol '" + A->getName() +
937 "' can not be undefined in a subtraction expression");
938
939 uint32_t Value = getSymbolAddress(A_SD, Layout);
940 uint32_t Value2 = 0;
941 uint64_t SecAddr = getSectionAddress(A_SD->getFragment()->getParent());
942 FixedValue += SecAddr;
943
944 if (const MCSymbolRefExpr *B = Target.getSymB()) {
945 MCSymbolData *B_SD = &Asm.getSymbolData(B->getSymbol());
946
947 if (!B_SD->getFragment())
948 report_fatal_error("symbol '" + B->getSymbol().getName() +
949 "' can not be undefined in a subtraction expression");
950
951 // Select the appropriate difference relocation type.
952 Type = macho::RIT_ARM_HalfDifference;
953 Value2 = getSymbolAddress(B_SD, Layout);
954 FixedValue -= getSectionAddress(B_SD->getFragment()->getParent());
955 }
956
957 // Relocations are written out in reverse order, so the PAIR comes first.
958 // ARM_RELOC_HALF and ARM_RELOC_HALF_SECTDIFF abuse the r_length field:
959 //
960 // For these two r_type relocations they always have a pair following them and
961 // the r_length bits are used differently. The encoding of the r_length is as
962 // follows:
963 // low bit of r_length:
964 // 0 - :lower16: for movw instructions
965 // 1 - :upper16: for movt instructions
966 // high bit of r_length:
967 // 0 - arm instructions
968 // 1 - thumb instructions
969 // the other half of the relocated expression is in the following pair
970 // relocation entry in the the low 16 bits of r_address field.
971 unsigned ThumbBit = 0;
972 unsigned MovtBit = 0;
973 switch ((unsigned)Fixup.getKind()) {
974 default: break;
975 case ARM::fixup_arm_movt_hi16:
976 case ARM::fixup_arm_movt_hi16_pcrel:
977 MovtBit = 1;
978 break;
979 case ARM::fixup_t2_movt_hi16:
980 case ARM::fixup_t2_movt_hi16_pcrel:
981 MovtBit = 1;
982 // Fallthrough
983 case ARM::fixup_t2_movw_lo16:
984 case ARM::fixup_t2_movw_lo16_pcrel:
985 ThumbBit = 1;
986 break;
987 }
988
989
990 if (Type == macho::RIT_ARM_HalfDifference) {
991 uint32_t OtherHalf = MovtBit
992 ? (FixedValue & 0xffff) : ((FixedValue & 0xffff0000) >> 16);
993
994 macho::RelocationEntry MRE;
995 MRE.Word0 = ((OtherHalf << 0) |
996 (macho::RIT_Pair << 24) |
997 (MovtBit << 28) |
998 (ThumbBit << 29) |
999 (IsPCRel << 30) |
1000 macho::RF_Scattered);
1001 MRE.Word1 = Value2;
1002 Relocations[Fragment->getParent()].push_back(MRE);
1003 }
1004
1005 macho::RelocationEntry MRE;
1006 MRE.Word0 = ((FixupOffset << 0) |
1007 (Type << 24) |
1008 (MovtBit << 28) |
1009 (ThumbBit << 29) |
1010 (IsPCRel << 30) |
1011 macho::RF_Scattered);
1012 MRE.Word1 = Value;
1013 Relocations[Fragment->getParent()].push_back(MRE);
1014}
1015
1016void MachObjectWriter::RecordTLVPRelocation(const MCAssembler &Asm,
1017 const MCAsmLayout &Layout,
1018 const MCFragment *Fragment,
1019 const MCFixup &Fixup,
1020 MCValue Target,
1021 uint64_t &FixedValue) {
1022 assert(Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP &&
1023 !is64Bit() &&
1024 "Should only be called with a 32-bit TLVP relocation!");
1025
1026 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
1027 uint32_t Value = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
1028 unsigned IsPCRel = 0;
1029
1030 // Get the symbol data.
1031 MCSymbolData *SD_A = &Asm.getSymbolData(Target.getSymA()->getSymbol());
1032 unsigned Index = SD_A->getIndex();
1033
1034 // We're only going to have a second symbol in pic mode and it'll be a
1035 // subtraction from the picbase. For 32-bit pic the addend is the difference
1036 // between the picbase and the next address. For 32-bit static the addend is
1037 // zero.
1038 if (Target.getSymB()) {
1039 // If this is a subtraction then we're pcrel.
1040 uint32_t FixupAddress =
1041 getFragmentAddress(Fragment, Layout) + Fixup.getOffset();
1042 MCSymbolData *SD_B = &Asm.getSymbolData(Target.getSymB()->getSymbol());
1043 IsPCRel = 1;
1044 FixedValue = (FixupAddress - getSymbolAddress(SD_B, Layout) +
1045 Target.getConstant());
1046 FixedValue += 1ULL << Log2Size;
1047 } else {
1048 FixedValue = 0;
1049 }
1050
1051 // struct relocation_info (8 bytes)
1052 macho::RelocationEntry MRE;
1053 MRE.Word0 = Value;
1054 MRE.Word1 = ((Index << 0) |
1055 (IsPCRel << 24) |
1056 (Log2Size << 25) |
1057 (1 << 27) | // Extern
1058 (macho::RIT_Generic_TLV << 28)); // Type
1059 Relocations[Fragment->getParent()].push_back(MRE);
1060}
1061
Bill Wendling3f2ea822011-06-23 00:09:43 +00001062bool MachObjectWriter::getARMFixupKindMachOInfo(unsigned Kind,
1063 unsigned &RelocType,
Bill Wendlingbbdffa92011-06-22 21:07:27 +00001064 unsigned &Log2Size) {
1065 RelocType = unsigned(macho::RIT_Vanilla);
1066 Log2Size = ~0U;
1067
1068 switch (Kind) {
1069 default:
1070 return false;
1071
1072 case FK_Data_1:
1073 Log2Size = llvm::Log2_32(1);
1074 return true;
1075 case FK_Data_2:
1076 Log2Size = llvm::Log2_32(2);
1077 return true;
1078 case FK_Data_4:
1079 Log2Size = llvm::Log2_32(4);
1080 return true;
1081 case FK_Data_8:
1082 Log2Size = llvm::Log2_32(8);
1083 return true;
1084
1085 // Handle 24-bit branch kinds.
1086 case ARM::fixup_arm_ldst_pcrel_12:
1087 case ARM::fixup_arm_pcrel_10:
1088 case ARM::fixup_arm_adr_pcrel_12:
1089 case ARM::fixup_arm_condbranch:
1090 case ARM::fixup_arm_uncondbranch:
1091 RelocType = unsigned(macho::RIT_ARM_Branch24Bit);
1092 // Report as 'long', even though that is not quite accurate.
1093 Log2Size = llvm::Log2_32(4);
1094 return true;
1095
1096 // Handle Thumb branches.
1097 case ARM::fixup_arm_thumb_br:
1098 RelocType = unsigned(macho::RIT_ARM_ThumbBranch22Bit);
1099 Log2Size = llvm::Log2_32(2);
1100 return true;
Jim Grosbach32e7abd2011-06-24 19:43:27 +00001101
Jim Grosbach535e58b2011-06-24 18:48:32 +00001102 case ARM::fixup_t2_uncondbranch:
Bill Wendlingbbdffa92011-06-22 21:07:27 +00001103 case ARM::fixup_arm_thumb_bl:
1104 case ARM::fixup_arm_thumb_blx:
1105 RelocType = unsigned(macho::RIT_ARM_ThumbBranch22Bit);
1106 Log2Size = llvm::Log2_32(4);
1107 return true;
1108
1109 case ARM::fixup_arm_movt_hi16:
1110 case ARM::fixup_arm_movt_hi16_pcrel:
1111 case ARM::fixup_t2_movt_hi16:
1112 case ARM::fixup_t2_movt_hi16_pcrel:
1113 RelocType = unsigned(macho::RIT_ARM_HalfDifference);
1114 // Report as 'long', even though that is not quite accurate.
1115 Log2Size = llvm::Log2_32(4);
1116 return true;
1117
1118 case ARM::fixup_arm_movw_lo16:
1119 case ARM::fixup_arm_movw_lo16_pcrel:
1120 case ARM::fixup_t2_movw_lo16:
1121 case ARM::fixup_t2_movw_lo16_pcrel:
1122 RelocType = unsigned(macho::RIT_ARM_Half);
1123 // Report as 'long', even though that is not quite accurate.
1124 Log2Size = llvm::Log2_32(4);
1125 return true;
1126 }
1127}
1128void MachObjectWriter::RecordARMRelocation(const MCAssembler &Asm,
1129 const MCAsmLayout &Layout,
1130 const MCFragment *Fragment,
1131 const MCFixup &Fixup,
1132 MCValue Target,
1133 uint64_t &FixedValue) {
1134 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
1135 unsigned Log2Size;
1136 unsigned RelocType = macho::RIT_Vanilla;
1137 if (!getARMFixupKindMachOInfo(Fixup.getKind(), RelocType, Log2Size)) {
1138 report_fatal_error("unknown ARM fixup kind!");
1139 return;
1140 }
1141
1142 // If this is a difference or a defined symbol plus an offset, then we need a
1143 // scattered relocation entry. Differences always require scattered
1144 // relocations.
1145 if (Target.getSymB()) {
1146 if (RelocType == macho::RIT_ARM_Half ||
1147 RelocType == macho::RIT_ARM_HalfDifference)
1148 return RecordARMMovwMovtRelocation(Asm, Layout, Fragment, Fixup,
1149 Target, FixedValue);
1150 return RecordARMScatteredRelocation(Asm, Layout, Fragment, Fixup,
1151 Target, Log2Size, FixedValue);
1152 }
1153
1154 // Get the symbol data, if any.
1155 MCSymbolData *SD = 0;
1156 if (Target.getSymA())
1157 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
1158
1159 // FIXME: For other platforms, we need to use scattered relocations for
1160 // internal relocations with offsets. If this is an internal relocation with
1161 // an offset, it also needs a scattered relocation entry.
1162 //
1163 // Is this right for ARM?
1164 uint32_t Offset = Target.getConstant();
1165 if (IsPCRel && RelocType == macho::RIT_Vanilla)
1166 Offset += 1 << Log2Size;
1167 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
1168 return RecordARMScatteredRelocation(Asm, Layout, Fragment, Fixup, Target,
1169 Log2Size, FixedValue);
1170
1171 // See <reloc.h>.
1172 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
1173 unsigned Index = 0;
1174 unsigned IsExtern = 0;
1175 unsigned Type = 0;
1176
1177 if (Target.isAbsolute()) { // constant
1178 // FIXME!
1179 report_fatal_error("FIXME: relocations to absolute targets "
1180 "not yet implemented");
1181 } else {
1182 // Resolve constant variables.
1183 if (SD->getSymbol().isVariable()) {
1184 int64_t Res;
1185 if (SD->getSymbol().getVariableValue()->EvaluateAsAbsolute(
1186 Res, Layout, SectionAddress)) {
1187 FixedValue = Res;
1188 return;
1189 }
1190 }
1191
1192 // Check whether we need an external or internal relocation.
1193 if (doesSymbolRequireExternRelocation(SD)) {
1194 IsExtern = 1;
1195 Index = SD->getIndex();
1196
1197 // For external relocations, make sure to offset the fixup value to
1198 // compensate for the addend of the symbol address, if it was
1199 // undefined. This occurs with weak definitions, for example.
1200 if (!SD->Symbol->isUndefined())
1201 FixedValue -= Layout.getSymbolOffset(SD);
1202 } else {
1203 // The index is the section ordinal (1-based).
1204 const MCSectionData &SymSD = Asm.getSectionData(
1205 SD->getSymbol().getSection());
1206 Index = SymSD.getOrdinal() + 1;
1207 FixedValue += getSectionAddress(&SymSD);
1208 }
1209 if (IsPCRel)
1210 FixedValue -= getSectionAddress(Fragment->getParent());
1211
1212 // The type is determined by the fixup kind.
1213 Type = RelocType;
1214 }
1215
1216 // struct relocation_info (8 bytes)
1217 macho::RelocationEntry MRE;
1218 MRE.Word0 = FixupOffset;
1219 MRE.Word1 = ((Index << 0) |
1220 (IsPCRel << 24) |
1221 (Log2Size << 25) |
1222 (IsExtern << 27) |
1223 (Type << 28));
1224 Relocations[Fragment->getParent()].push_back(MRE);
1225}
1226
1227void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
1228 const MCAsmLayout &Layout,
1229 const MCFragment *Fragment,
1230 const MCFixup &Fixup,
1231 MCValue Target,
1232 uint64_t &FixedValue) {
1233 // FIXME: These needs to be factored into the target Mach-O writer.
1234 if (isARM()) {
1235 RecordARMRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
1236 return;
1237 }
1238 if (is64Bit()) {
1239 RecordX86_64Relocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
1240 return;
1241 }
1242
1243 unsigned IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
1244 unsigned Log2Size = getFixupKindLog2Size(Fixup.getKind());
1245
1246 // If this is a 32-bit TLVP reloc it's handled a bit differently.
1247 if (Target.getSymA() &&
1248 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_TLVP) {
1249 RecordTLVPRelocation(Asm, Layout, Fragment, Fixup, Target, FixedValue);
1250 return;
1251 }
1252
1253 // If this is a difference or a defined symbol plus an offset, then we need a
1254 // scattered relocation entry. Differences always require scattered
1255 // relocations.
1256 if (Target.getSymB())
1257 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
1258 Target, Log2Size, FixedValue);
1259
1260 // Get the symbol data, if any.
1261 MCSymbolData *SD = 0;
1262 if (Target.getSymA())
1263 SD = &Asm.getSymbolData(Target.getSymA()->getSymbol());
1264
1265 // If this is an internal relocation with an offset, it also needs a scattered
1266 // relocation entry.
1267 uint32_t Offset = Target.getConstant();
1268 if (IsPCRel)
1269 Offset += 1 << Log2Size;
1270 if (Offset && SD && !doesSymbolRequireExternRelocation(SD))
1271 return RecordScatteredRelocation(Asm, Layout, Fragment, Fixup,
1272 Target, Log2Size, FixedValue);
1273
1274 // See <reloc.h>.
1275 uint32_t FixupOffset = Layout.getFragmentOffset(Fragment)+Fixup.getOffset();
1276 unsigned Index = 0;
1277 unsigned IsExtern = 0;
1278 unsigned Type = 0;
1279
1280 if (Target.isAbsolute()) { // constant
1281 // SymbolNum of 0 indicates the absolute section.
1282 //
1283 // FIXME: Currently, these are never generated (see code below). I cannot
1284 // find a case where they are actually emitted.
1285 Type = macho::RIT_Vanilla;
1286 } else {
1287 // Resolve constant variables.
1288 if (SD->getSymbol().isVariable()) {
1289 int64_t Res;
1290 if (SD->getSymbol().getVariableValue()->EvaluateAsAbsolute(
1291 Res, Layout, SectionAddress)) {
1292 FixedValue = Res;
1293 return;
1294 }
1295 }
1296
1297 // Check whether we need an external or internal relocation.
1298 if (doesSymbolRequireExternRelocation(SD)) {
1299 IsExtern = 1;
1300 Index = SD->getIndex();
1301 // For external relocations, make sure to offset the fixup value to
1302 // compensate for the addend of the symbol address, if it was
1303 // undefined. This occurs with weak definitions, for example.
1304 if (!SD->Symbol->isUndefined())
1305 FixedValue -= Layout.getSymbolOffset(SD);
1306 } else {
1307 // The index is the section ordinal (1-based).
1308 const MCSectionData &SymSD = Asm.getSectionData(
1309 SD->getSymbol().getSection());
1310 Index = SymSD.getOrdinal() + 1;
1311 FixedValue += getSectionAddress(&SymSD);
1312 }
1313 if (IsPCRel)
1314 FixedValue -= getSectionAddress(Fragment->getParent());
1315
1316 Type = macho::RIT_Vanilla;
1317 }
1318
1319 // struct relocation_info (8 bytes)
1320 macho::RelocationEntry MRE;
1321 MRE.Word0 = FixupOffset;
1322 MRE.Word1 = ((Index << 0) |
1323 (IsPCRel << 24) |
1324 (Log2Size << 25) |
1325 (IsExtern << 27) |
1326 (Type << 28));
1327 Relocations[Fragment->getParent()].push_back(MRE);
1328}
1329
1330void MachObjectWriter::BindIndirectSymbols(MCAssembler &Asm) {
1331 // This is the point where 'as' creates actual symbols for indirect symbols
1332 // (in the following two passes). It would be easier for us to do this sooner
1333 // when we see the attribute, but that makes getting the order in the symbol
1334 // table much more complicated than it is worth.
1335 //
1336 // FIXME: Revisit this when the dust settles.
1337
1338 // Bind non lazy symbol pointers first.
1339 unsigned IndirectIndex = 0;
1340 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
1341 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
1342 const MCSectionMachO &Section =
1343 cast<MCSectionMachO>(it->SectionData->getSection());
1344
1345 if (Section.getType() != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
1346 continue;
1347
1348 // Initialize the section indirect symbol base, if necessary.
1349 if (!IndirectSymBase.count(it->SectionData))
1350 IndirectSymBase[it->SectionData] = IndirectIndex;
1351
1352 Asm.getOrCreateSymbolData(*it->Symbol);
1353 }
1354
1355 // Then lazy symbol pointers and symbol stubs.
1356 IndirectIndex = 0;
1357 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
1358 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
1359 const MCSectionMachO &Section =
1360 cast<MCSectionMachO>(it->SectionData->getSection());
1361
1362 if (Section.getType() != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
1363 Section.getType() != MCSectionMachO::S_SYMBOL_STUBS)
1364 continue;
1365
1366 // Initialize the section indirect symbol base, if necessary.
1367 if (!IndirectSymBase.count(it->SectionData))
1368 IndirectSymBase[it->SectionData] = IndirectIndex;
1369
1370 // Set the symbol type to undefined lazy, but only on construction.
1371 //
1372 // FIXME: Do not hardcode.
1373 bool Created;
1374 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
1375 if (Created)
1376 Entry.setFlags(Entry.getFlags() | 0x0001);
1377 }
1378}
1379
1380/// ComputeSymbolTable - Compute the symbol table data
1381///
1382/// \param StringTable [out] - The string table data.
1383/// \param StringIndexMap [out] - Map from symbol names to offsets in the
1384/// string table.
Bill Wendling3f2ea822011-06-23 00:09:43 +00001385void MachObjectWriter::
1386ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
1387 std::vector<MachSymbolData> &LocalSymbolData,
1388 std::vector<MachSymbolData> &ExternalSymbolData,
1389 std::vector<MachSymbolData> &UndefinedSymbolData) {
Bill Wendlingbbdffa92011-06-22 21:07:27 +00001390 // Build section lookup table.
1391 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
1392 unsigned Index = 1;
1393 for (MCAssembler::iterator it = Asm.begin(),
1394 ie = Asm.end(); it != ie; ++it, ++Index)
1395 SectionIndexMap[&it->getSection()] = Index;
1396 assert(Index <= 256 && "Too many sections!");
1397
1398 // Index 0 is always the empty string.
1399 StringMap<uint64_t> StringIndexMap;
1400 StringTable += '\x00';
1401
1402 // Build the symbol arrays and the string table, but only for non-local
1403 // symbols.
1404 //
1405 // The particular order that we collect the symbols and create the string
1406 // table, then sort the symbols is chosen to match 'as'. Even though it
1407 // doesn't matter for correctness, this is important for letting us diff .o
1408 // files.
1409 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1410 ie = Asm.symbol_end(); it != ie; ++it) {
1411 const MCSymbol &Symbol = it->getSymbol();
1412
1413 // Ignore non-linker visible symbols.
1414 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1415 continue;
1416
1417 if (!it->isExternal() && !Symbol.isUndefined())
1418 continue;
1419
1420 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1421 if (!Entry) {
1422 Entry = StringTable.size();
1423 StringTable += Symbol.getName();
1424 StringTable += '\x00';
1425 }
1426
1427 MachSymbolData MSD;
1428 MSD.SymbolData = it;
1429 MSD.StringIndex = Entry;
1430
1431 if (Symbol.isUndefined()) {
1432 MSD.SectionIndex = 0;
1433 UndefinedSymbolData.push_back(MSD);
1434 } else if (Symbol.isAbsolute()) {
1435 MSD.SectionIndex = 0;
1436 ExternalSymbolData.push_back(MSD);
1437 } else {
1438 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1439 assert(MSD.SectionIndex && "Invalid section index!");
1440 ExternalSymbolData.push_back(MSD);
1441 }
1442 }
1443
1444 // Now add the data for local symbols.
1445 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
1446 ie = Asm.symbol_end(); it != ie; ++it) {
1447 const MCSymbol &Symbol = it->getSymbol();
1448
1449 // Ignore non-linker visible symbols.
1450 if (!Asm.isSymbolLinkerVisible(it->getSymbol()))
1451 continue;
1452
1453 if (it->isExternal() || Symbol.isUndefined())
1454 continue;
1455
1456 uint64_t &Entry = StringIndexMap[Symbol.getName()];
1457 if (!Entry) {
1458 Entry = StringTable.size();
1459 StringTable += Symbol.getName();
1460 StringTable += '\x00';
1461 }
1462
1463 MachSymbolData MSD;
1464 MSD.SymbolData = it;
1465 MSD.StringIndex = Entry;
1466
1467 if (Symbol.isAbsolute()) {
1468 MSD.SectionIndex = 0;
1469 LocalSymbolData.push_back(MSD);
1470 } else {
1471 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
1472 assert(MSD.SectionIndex && "Invalid section index!");
1473 LocalSymbolData.push_back(MSD);
1474 }
1475 }
1476
1477 // External and undefined symbols are required to be in lexicographic order.
1478 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1479 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1480
1481 // Set the symbol indices.
1482 Index = 0;
1483 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1484 LocalSymbolData[i].SymbolData->setIndex(Index++);
1485 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1486 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1487 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1488 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1489
1490 // The string table is padded to a multiple of 4.
1491 while (StringTable.size() % 4)
1492 StringTable += '\x00';
1493}
1494
1495void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
1496 const MCAsmLayout &Layout) {
1497 uint64_t StartAddress = 0;
1498 const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
1499 for (int i = 0, n = Order.size(); i != n ; ++i) {
1500 const MCSectionData *SD = Order[i];
1501 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
1502 SectionAddress[SD] = StartAddress;
1503 StartAddress += Layout.getSectionAddressSize(SD);
1504
1505 // Explicitly pad the section to match the alignment requirements of the
1506 // following one. This is for 'gas' compatibility, it shouldn't
1507 /// strictly be necessary.
1508 StartAddress += getPaddingSize(SD, Layout);
1509 }
1510}
1511
Bill Wendling3f2ea822011-06-23 00:09:43 +00001512void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
1513 const MCAsmLayout &Layout) {
Bill Wendlingbbdffa92011-06-22 21:07:27 +00001514 computeSectionAddresses(Asm, Layout);
1515
1516 // Create symbol data for any indirect symbols.
1517 BindIndirectSymbols(Asm);
1518
1519 // Compute symbol table information and bind symbol indices.
1520 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
1521 UndefinedSymbolData);
1522}
1523
Bill Wendling3f2ea822011-06-23 00:09:43 +00001524bool MachObjectWriter::
1525IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1526 const MCSymbolData &DataA,
1527 const MCFragment &FB,
1528 bool InSet,
1529 bool IsPCRel) const {
Bill Wendlingbbdffa92011-06-22 21:07:27 +00001530 if (InSet)
1531 return true;
1532
1533 // The effective address is
1534 // addr(atom(A)) + offset(A)
1535 // - addr(atom(B)) - offset(B)
1536 // and the offsets are not relocatable, so the fixup is fully resolved when
1537 // addr(atom(A)) - addr(atom(B)) == 0.
1538 const MCSymbolData *A_Base = 0, *B_Base = 0;
1539
1540 const MCSymbol &SA = DataA.getSymbol().AliasedSymbol();
1541 const MCSection &SecA = SA.getSection();
1542 const MCSection &SecB = FB.getParent()->getSection();
1543
1544 if (IsPCRel) {
1545 // The simple (Darwin, except on x86_64) way of dealing with this was to
1546 // assume that any reference to a temporary symbol *must* be a temporary
1547 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
1548 // relocation to a temporary symbol (in the same section) is fully
1549 // resolved. This also works in conjunction with absolutized .set, which
1550 // requires the compiler to use .set to absolutize the differences between
1551 // symbols which the compiler knows to be assembly time constants, so we
1552 // don't need to worry about considering symbol differences fully resolved.
1553
1554 if (!Asm.getBackend().hasReliableSymbolDifference()) {
1555 if (!SA.isTemporary() || !SA.isInSection() || &SecA != &SecB)
1556 return false;
1557 return true;
1558 }
1559 } else {
1560 if (!TargetObjectWriter->useAggressiveSymbolFolding())
1561 return false;
1562 }
1563
1564 const MCFragment &FA = *Asm.getSymbolData(SA).getFragment();
1565
1566 A_Base = FA.getAtom();
1567 if (!A_Base)
1568 return false;
1569
1570 B_Base = FB.getAtom();
1571 if (!B_Base)
1572 return false;
1573
1574 // If the atoms are the same, they are guaranteed to have the same address.
1575 if (A_Base == B_Base)
1576 return true;
1577
1578 // Otherwise, we can't prove this is fully resolved.
1579 return false;
1580}
1581
1582void MachObjectWriter::WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) {
1583 unsigned NumSections = Asm.size();
1584
1585 // The section data starts after the header, the segment load command (and
1586 // section headers) and the symbol table.
1587 unsigned NumLoadCommands = 1;
1588 uint64_t LoadCommandsSize = is64Bit() ?
1589 macho::SegmentLoadCommand64Size + NumSections * macho::Section64Size :
1590 macho::SegmentLoadCommand32Size + NumSections * macho::Section32Size;
1591
1592 // Add the symbol table load command sizes, if used.
1593 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
1594 UndefinedSymbolData.size();
1595 if (NumSymbols) {
1596 NumLoadCommands += 2;
1597 LoadCommandsSize += (macho::SymtabLoadCommandSize +
1598 macho::DysymtabLoadCommandSize);
1599 }
1600
1601 // Compute the total size of the section data, as well as its file size and vm
1602 // size.
1603 uint64_t SectionDataStart = (is64Bit() ? macho::Header64Size :
1604 macho::Header32Size) + LoadCommandsSize;
1605 uint64_t SectionDataSize = 0;
1606 uint64_t SectionDataFileSize = 0;
1607 uint64_t VMSize = 0;
1608 for (MCAssembler::const_iterator it = Asm.begin(),
1609 ie = Asm.end(); it != ie; ++it) {
1610 const MCSectionData &SD = *it;
1611 uint64_t Address = getSectionAddress(&SD);
1612 uint64_t Size = Layout.getSectionAddressSize(&SD);
1613 uint64_t FileSize = Layout.getSectionFileSize(&SD);
1614 FileSize += getPaddingSize(&SD, Layout);
1615
1616 VMSize = std::max(VMSize, Address + Size);
1617
1618 if (SD.getSection().isVirtualSection())
1619 continue;
1620
1621 SectionDataSize = std::max(SectionDataSize, Address + Size);
1622 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
1623 }
1624
1625 // The section data is padded to 4 bytes.
1626 //
1627 // FIXME: Is this machine dependent?
1628 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
1629 SectionDataFileSize += SectionDataPadding;
1630
1631 // Write the prolog, starting with the header and load command...
1632 WriteHeader(NumLoadCommands, LoadCommandsSize,
1633 Asm.getSubsectionsViaSymbols());
1634 WriteSegmentLoadCommand(NumSections, VMSize,
1635 SectionDataStart, SectionDataSize);
1636
1637 // ... and then the section headers.
1638 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
1639 for (MCAssembler::const_iterator it = Asm.begin(),
1640 ie = Asm.end(); it != ie; ++it) {
1641 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
1642 unsigned NumRelocs = Relocs.size();
1643 uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
1644 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
1645 RelocTableEnd += NumRelocs * macho::RelocationInfoSize;
1646 }
1647
1648 // Write the symbol table load command, if used.
1649 if (NumSymbols) {
1650 unsigned FirstLocalSymbol = 0;
1651 unsigned NumLocalSymbols = LocalSymbolData.size();
1652 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
1653 unsigned NumExternalSymbols = ExternalSymbolData.size();
1654 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
1655 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
1656 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
1657 unsigned NumSymTabSymbols =
1658 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
1659 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
1660 uint64_t IndirectSymbolOffset = 0;
1661
1662 // If used, the indirect symbols are written after the section data.
1663 if (NumIndirectSymbols)
1664 IndirectSymbolOffset = RelocTableEnd;
1665
1666 // The symbol table is written after the indirect symbol data.
1667 uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
1668
1669 // The string table is written after symbol table.
1670 uint64_t StringTableOffset =
1671 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ? macho::Nlist64Size :
1672 macho::Nlist32Size);
1673 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1674 StringTableOffset, StringTable.size());
1675
1676 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1677 FirstExternalSymbol, NumExternalSymbols,
1678 FirstUndefinedSymbol, NumUndefinedSymbols,
1679 IndirectSymbolOffset, NumIndirectSymbols);
1680 }
1681
1682 // Write the actual section data.
1683 for (MCAssembler::const_iterator it = Asm.begin(),
1684 ie = Asm.end(); it != ie; ++it) {
1685 Asm.WriteSectionData(it, Layout);
1686
1687 uint64_t Pad = getPaddingSize(it, Layout);
1688 for (unsigned int i = 0; i < Pad; ++i)
1689 Write8(0);
1690 }
1691
1692 // Write the extra padding.
1693 WriteZeros(SectionDataPadding);
1694
1695 // Write the relocation entries.
1696 for (MCAssembler::const_iterator it = Asm.begin(),
1697 ie = Asm.end(); it != ie; ++it) {
1698 // Write the section relocation entries, in reverse order to match 'as'
1699 // (approximately, the exact algorithm is more complicated than this).
1700 std::vector<macho::RelocationEntry> &Relocs = Relocations[it];
1701 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1702 Write32(Relocs[e - i - 1].Word0);
1703 Write32(Relocs[e - i - 1].Word1);
1704 }
1705 }
1706
1707 // Write the symbol table data, if used.
1708 if (NumSymbols) {
1709 // Write the indirect symbol entries.
1710 for (MCAssembler::const_indirect_symbol_iterator
1711 it = Asm.indirect_symbol_begin(),
1712 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
1713 // Indirect symbols in the non lazy symbol pointer section have some
1714 // special handling.
1715 const MCSectionMachO &Section =
1716 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
1717 if (Section.getType() == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
1718 // If this symbol is defined and internal, mark it as such.
1719 if (it->Symbol->isDefined() &&
1720 !Asm.getSymbolData(*it->Symbol).isExternal()) {
1721 uint32_t Flags = macho::ISF_Local;
1722 if (it->Symbol->isAbsolute())
1723 Flags |= macho::ISF_Absolute;
1724 Write32(Flags);
1725 continue;
1726 }
1727 }
1728
1729 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1730 }
1731
1732 // FIXME: Check that offsets match computed ones.
1733
1734 // Write the symbol table entries.
1735 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1736 WriteNlist(LocalSymbolData[i], Layout);
1737 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1738 WriteNlist(ExternalSymbolData[i], Layout);
1739 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1740 WriteNlist(UndefinedSymbolData[i], Layout);
1741
1742 // Write the string table.
1743 OS << StringTable.str();
1744 }
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001745}
1746
Daniel Dunbarae5abd52010-12-16 16:09:19 +00001747MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
Daniel Dunbar5d05d972010-12-16 17:21:02 +00001748 raw_ostream &OS,
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001749 bool IsLittleEndian) {
Daniel Dunbar5d05d972010-12-16 17:21:02 +00001750 return new MachObjectWriter(MOTW, OS, IsLittleEndian);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001751}