blob: 2e49a2871f9f66d150a3c3ef6ac5ed807e2e968c [file] [log] [blame]
Daniel Dunbar79e0e5a2010-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 Dunbar8888a962010-12-16 16:09:19 +000010#include "llvm/MC/MCMachObjectWriter.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000011#include "llvm/ADT/StringMap.h"
12#include "llvm/ADT/Twine.h"
Evan Cheng5928e692011-07-25 23:24:55 +000013#include "llvm/MC/MCAsmBackend.h"
Daniel Dunbar7c969552010-03-24 03:43:40 +000014#include "llvm/MC/MCAsmLayout.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/MC/MCAssembler.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000016#include "llvm/MC/MCExpr.h"
Craig Topper6e80c282012-03-26 06:58:25 +000017#include "llvm/MC/MCFixupKindInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/MC/MCMachOSymbolFlags.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000019#include "llvm/MC/MCObjectWriter.h"
20#include "llvm/MC/MCSectionMachO.h"
21#include "llvm/MC/MCSymbol.h"
22#include "llvm/MC/MCValue.h"
Jim Grosbach4b63d2a2012-05-18 19:12:01 +000023#include "llvm/Support/Debug.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000024#include "llvm/Support/ErrorHandling.h"
Charles Davis8bdfafd2013-09-01 04:28:48 +000025#include "llvm/Support/MachO.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000026#include <vector>
27using namespace llvm;
28
Pedro Artigasb95c53e2012-12-14 18:52:11 +000029void MachObjectWriter::reset() {
30 Relocations.clear();
31 IndirectSymBase.clear();
32 StringTable.clear();
33 LocalSymbolData.clear();
34 ExternalSymbolData.clear();
35 UndefinedSymbolData.clear();
36 MCObjectWriter::reset();
37}
38
Jim Grosbach28fcafb2011-06-24 23:44:37 +000039bool MachObjectWriter::
40doesSymbolRequireExternRelocation(const MCSymbolData *SD) {
Daniel Dunbar7de31062010-05-10 23:15:13 +000041 // Undefined symbols are always extern.
42 if (SD->Symbol->isUndefined())
43 return true;
44
45 // References to weak definitions require external relocation entries; the
46 // definition may not always be the one in the same object file.
47 if (SD->getFlags() & SF_WeakDefinition)
48 return true;
49
50 // Otherwise, we can use an internal relocation.
51 return false;
52}
53
Jim Grosbach28fcafb2011-06-24 23:44:37 +000054bool MachObjectWriter::
55MachSymbolData::operator<(const MachSymbolData &RHS) const {
56 return SymbolData->getSymbol().getName() <
57 RHS.SymbolData->getSymbol().getName();
58}
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000059
Jim Grosbach28fcafb2011-06-24 23:44:37 +000060bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
61 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
62 (MCFixupKind) Kind);
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000063
Jim Grosbach28fcafb2011-06-24 23:44:37 +000064 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
65}
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000066
Jim Grosbach28fcafb2011-06-24 23:44:37 +000067uint64_t MachObjectWriter::getFragmentAddress(const MCFragment *Fragment,
68 const MCAsmLayout &Layout) const {
69 return getSectionAddress(Fragment->getParent()) +
70 Layout.getFragmentOffset(Fragment);
71}
Bill Wendlingeb872e02011-06-22 21:07:27 +000072
73uint64_t MachObjectWriter::getSymbolAddress(const MCSymbolData* SD,
74 const MCAsmLayout &Layout) const {
75 const MCSymbol &S = SD->getSymbol();
76
77 // If this is a variable, then recursively evaluate now.
78 if (S.isVariable()) {
Jim Grosbachd96ef192012-09-13 23:11:25 +000079 if (const MCConstantExpr *C =
80 dyn_cast<const MCConstantExpr>(S.getVariableValue()))
81 return C->getValue();
82
83
Bill Wendlingeb872e02011-06-22 21:07:27 +000084 MCValue Target;
Rafael Espindola3d5d4642014-03-12 16:55:59 +000085 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, &Layout))
Bill Wendlingeb872e02011-06-22 21:07:27 +000086 report_fatal_error("unable to evaluate offset for variable '" +
87 S.getName() + "'");
88
89 // Verify that any used symbols are defined.
90 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
91 report_fatal_error("unable to evaluate offset to undefined symbol '" +
92 Target.getSymA()->getSymbol().getName() + "'");
93 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
94 report_fatal_error("unable to evaluate offset to undefined symbol '" +
95 Target.getSymB()->getSymbol().getName() + "'");
96
97 uint64_t Address = Target.getConstant();
98 if (Target.getSymA())
99 Address += getSymbolAddress(&Layout.getAssembler().getSymbolData(
100 Target.getSymA()->getSymbol()), Layout);
101 if (Target.getSymB())
102 Address += getSymbolAddress(&Layout.getAssembler().getSymbolData(
103 Target.getSymB()->getSymbol()), Layout);
104 return Address;
105 }
106
107 return getSectionAddress(SD->getFragment()->getParent()) +
108 Layout.getSymbolOffset(SD);
109}
110
111uint64_t MachObjectWriter::getPaddingSize(const MCSectionData *SD,
112 const MCAsmLayout &Layout) const {
113 uint64_t EndAddr = getSectionAddress(SD) + Layout.getSectionAddressSize(SD);
114 unsigned Next = SD->getLayoutOrder() + 1;
115 if (Next >= Layout.getSectionOrder().size())
116 return 0;
117
118 const MCSectionData &NextSD = *Layout.getSectionOrder()[Next];
119 if (NextSD.getSection().isVirtualSection())
120 return 0;
121 return OffsetToAlignment(EndAddr, NextSD.getAlignment());
122}
123
124void MachObjectWriter::WriteHeader(unsigned NumLoadCommands,
125 unsigned LoadCommandsSize,
126 bool SubsectionsViaSymbols) {
127 uint32_t Flags = 0;
128
129 if (SubsectionsViaSymbols)
Charles Davis8bdfafd2013-09-01 04:28:48 +0000130 Flags |= MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000131
132 // struct mach_header (28 bytes) or
133 // struct mach_header_64 (32 bytes)
134
135 uint64_t Start = OS.tell();
136 (void) Start;
137
Charles Davis8bdfafd2013-09-01 04:28:48 +0000138 Write32(is64Bit() ? MachO::MH_MAGIC_64 : MachO::MH_MAGIC);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000139
140 Write32(TargetObjectWriter->getCPUType());
141 Write32(TargetObjectWriter->getCPUSubtype());
142
Charles Davis8bdfafd2013-09-01 04:28:48 +0000143 Write32(MachO::MH_OBJECT);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000144 Write32(NumLoadCommands);
145 Write32(LoadCommandsSize);
146 Write32(Flags);
147 if (is64Bit())
148 Write32(0); // reserved
149
150 assert(OS.tell() - Start ==
Charles Davis8bdfafd2013-09-01 04:28:48 +0000151 (is64Bit()?sizeof(MachO::mach_header_64): sizeof(MachO::mach_header)));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000152}
153
154/// WriteSegmentLoadCommand - Write a segment load command.
155///
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000156/// \param NumSections The number of sections in this segment.
157/// \param SectionDataSize The total size of the sections.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000158void MachObjectWriter::WriteSegmentLoadCommand(unsigned NumSections,
159 uint64_t VMSize,
160 uint64_t SectionDataStartOffset,
161 uint64_t SectionDataSize) {
162 // struct segment_command (56 bytes) or
163 // struct segment_command_64 (72 bytes)
164
165 uint64_t Start = OS.tell();
166 (void) Start;
167
168 unsigned SegmentLoadCommandSize =
Charles Davis8bdfafd2013-09-01 04:28:48 +0000169 is64Bit() ? sizeof(MachO::segment_command_64):
170 sizeof(MachO::segment_command);
171 Write32(is64Bit() ? MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000172 Write32(SegmentLoadCommandSize +
Charles Davis8bdfafd2013-09-01 04:28:48 +0000173 NumSections * (is64Bit() ? sizeof(MachO::section_64) :
174 sizeof(MachO::section)));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000175
176 WriteBytes("", 16);
177 if (is64Bit()) {
178 Write64(0); // vmaddr
179 Write64(VMSize); // vmsize
180 Write64(SectionDataStartOffset); // file offset
181 Write64(SectionDataSize); // file size
182 } else {
183 Write32(0); // vmaddr
184 Write32(VMSize); // vmsize
185 Write32(SectionDataStartOffset); // file offset
186 Write32(SectionDataSize); // file size
187 }
Nick Kledzikfe6813f2013-09-04 23:53:44 +0000188 // maxprot
189 Write32(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE);
190 // initprot
191 Write32(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000192 Write32(NumSections);
193 Write32(0); // flags
194
195 assert(OS.tell() - Start == SegmentLoadCommandSize);
196}
197
198void MachObjectWriter::WriteSection(const MCAssembler &Asm,
199 const MCAsmLayout &Layout,
200 const MCSectionData &SD,
201 uint64_t FileOffset,
202 uint64_t RelocationsStart,
203 unsigned NumRelocations) {
204 uint64_t SectionSize = Layout.getSectionAddressSize(&SD);
205
206 // The offset is unused for virtual sections.
207 if (SD.getSection().isVirtualSection()) {
208 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
209 FileOffset = 0;
210 }
211
212 // struct section (68 bytes) or
213 // struct section_64 (80 bytes)
214
215 uint64_t Start = OS.tell();
216 (void) Start;
217
218 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
219 WriteBytes(Section.getSectionName(), 16);
220 WriteBytes(Section.getSegmentName(), 16);
221 if (is64Bit()) {
222 Write64(getSectionAddress(&SD)); // address
223 Write64(SectionSize); // size
224 } else {
225 Write32(getSectionAddress(&SD)); // address
226 Write32(SectionSize); // size
227 }
228 Write32(FileOffset);
229
230 unsigned Flags = Section.getTypeAndAttributes();
231 if (SD.hasInstructions())
David Majnemer7b583052014-03-07 07:36:05 +0000232 Flags |= MachO::S_ATTR_SOME_INSTRUCTIONS;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000233
234 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
235 Write32(Log2_32(SD.getAlignment()));
236 Write32(NumRelocations ? RelocationsStart : 0);
237 Write32(NumRelocations);
238 Write32(Flags);
239 Write32(IndirectSymBase.lookup(&SD)); // reserved1
240 Write32(Section.getStubSize()); // reserved2
241 if (is64Bit())
242 Write32(0); // reserved3
243
Charles Davis8bdfafd2013-09-01 04:28:48 +0000244 assert(OS.tell() - Start == (is64Bit() ? sizeof(MachO::section_64) :
245 sizeof(MachO::section)));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000246}
247
248void MachObjectWriter::WriteSymtabLoadCommand(uint32_t SymbolOffset,
249 uint32_t NumSymbols,
250 uint32_t StringTableOffset,
251 uint32_t StringTableSize) {
252 // struct symtab_command (24 bytes)
253
254 uint64_t Start = OS.tell();
255 (void) Start;
256
Charles Davis8bdfafd2013-09-01 04:28:48 +0000257 Write32(MachO::LC_SYMTAB);
258 Write32(sizeof(MachO::symtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000259 Write32(SymbolOffset);
260 Write32(NumSymbols);
261 Write32(StringTableOffset);
262 Write32(StringTableSize);
263
Charles Davis8bdfafd2013-09-01 04:28:48 +0000264 assert(OS.tell() - Start == sizeof(MachO::symtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000265}
266
267void MachObjectWriter::WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
268 uint32_t NumLocalSymbols,
269 uint32_t FirstExternalSymbol,
270 uint32_t NumExternalSymbols,
271 uint32_t FirstUndefinedSymbol,
272 uint32_t NumUndefinedSymbols,
273 uint32_t IndirectSymbolOffset,
274 uint32_t NumIndirectSymbols) {
275 // struct dysymtab_command (80 bytes)
276
277 uint64_t Start = OS.tell();
278 (void) Start;
279
Charles Davis8bdfafd2013-09-01 04:28:48 +0000280 Write32(MachO::LC_DYSYMTAB);
281 Write32(sizeof(MachO::dysymtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000282 Write32(FirstLocalSymbol);
283 Write32(NumLocalSymbols);
284 Write32(FirstExternalSymbol);
285 Write32(NumExternalSymbols);
286 Write32(FirstUndefinedSymbol);
287 Write32(NumUndefinedSymbols);
288 Write32(0); // tocoff
289 Write32(0); // ntoc
290 Write32(0); // modtaboff
291 Write32(0); // nmodtab
292 Write32(0); // extrefsymoff
293 Write32(0); // nextrefsyms
294 Write32(IndirectSymbolOffset);
295 Write32(NumIndirectSymbols);
296 Write32(0); // extreloff
297 Write32(0); // nextrel
298 Write32(0); // locreloff
299 Write32(0); // nlocrel
300
Charles Davis8bdfafd2013-09-01 04:28:48 +0000301 assert(OS.tell() - Start == sizeof(MachO::dysymtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000302}
303
Bill Wendling21162212011-06-23 00:09:43 +0000304void MachObjectWriter::WriteNlist(MachSymbolData &MSD,
305 const MCAsmLayout &Layout) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000306 MCSymbolData &Data = *MSD.SymbolData;
307 const MCSymbol &Symbol = Data.getSymbol();
308 uint8_t Type = 0;
309 uint16_t Flags = Data.getFlags();
Jim Grosbacha3171602011-08-09 22:12:37 +0000310 uint64_t Address = 0;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000311
312 // Set the N_TYPE bits. See <mach-o/nlist.h>.
313 //
314 // FIXME: Are the prebound or indirect fields possible here?
315 if (Symbol.isUndefined())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000316 Type = MachO::N_UNDF;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000317 else if (Symbol.isAbsolute())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000318 Type = MachO::N_ABS;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000319 else
Charles Davis8bdfafd2013-09-01 04:28:48 +0000320 Type = MachO::N_SECT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000321
322 // FIXME: Set STAB bits.
323
324 if (Data.isPrivateExtern())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000325 Type |= MachO::N_PEXT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000326
327 // Set external bit.
328 if (Data.isExternal() || Symbol.isUndefined())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000329 Type |= MachO::N_EXT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000330
331 // Compute the symbol address.
332 if (Symbol.isDefined()) {
Jim Grosbachd96ef192012-09-13 23:11:25 +0000333 Address = getSymbolAddress(&Data, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000334 } else if (Data.isCommon()) {
335 // Common symbols are encoded with the size in the address
336 // field, and their alignment in the flags.
337 Address = Data.getCommonSize();
338
339 // Common alignment is packed into the 'desc' bits.
340 if (unsigned Align = Data.getCommonAlignment()) {
341 unsigned Log2Size = Log2_32(Align);
342 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
343 if (Log2Size > 15)
344 report_fatal_error("invalid 'common' alignment '" +
Jim Grosbachaff6a0c2013-09-24 23:56:31 +0000345 Twine(Align) + "' for '" + Symbol.getName() + "'",
346 false);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000347 // FIXME: Keep this mask with the SymbolFlags enumeration.
348 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
349 }
350 }
351
352 // struct nlist (12 bytes)
353
354 Write32(MSD.StringIndex);
355 Write8(Type);
356 Write8(MSD.SectionIndex);
357
358 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
359 // value.
360 Write16(Flags);
361 if (is64Bit())
362 Write64(Address);
363 else
364 Write32(Address);
365}
366
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000367void MachObjectWriter::WriteLinkeditLoadCommand(uint32_t Type,
368 uint32_t DataOffset,
369 uint32_t DataSize) {
370 uint64_t Start = OS.tell();
371 (void) Start;
372
373 Write32(Type);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000374 Write32(sizeof(MachO::linkedit_data_command));
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000375 Write32(DataOffset);
376 Write32(DataSize);
377
Charles Davis8bdfafd2013-09-01 04:28:48 +0000378 assert(OS.tell() - Start == sizeof(MachO::linkedit_data_command));
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000379}
380
Daniel Dunbareec0f322013-01-18 01:26:07 +0000381static unsigned ComputeLinkerOptionsLoadCommandSize(
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000382 const std::vector<std::string> &Options, bool is64Bit)
Daniel Dunbareec0f322013-01-18 01:26:07 +0000383{
Charles Davis8bdfafd2013-09-01 04:28:48 +0000384 unsigned Size = sizeof(MachO::linker_options_command);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000385 for (unsigned i = 0, e = Options.size(); i != e; ++i)
386 Size += Options[i].size() + 1;
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000387 return RoundUpToAlignment(Size, is64Bit ? 8 : 4);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000388}
389
390void MachObjectWriter::WriteLinkerOptionsLoadCommand(
391 const std::vector<std::string> &Options)
392{
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000393 unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit());
Daniel Dunbareec0f322013-01-18 01:26:07 +0000394 uint64_t Start = OS.tell();
395 (void) Start;
396
Charles Davis8bdfafd2013-09-01 04:28:48 +0000397 Write32(MachO::LC_LINKER_OPTIONS);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000398 Write32(Size);
399 Write32(Options.size());
Charles Davis8bdfafd2013-09-01 04:28:48 +0000400 uint64_t BytesWritten = sizeof(MachO::linker_options_command);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000401 for (unsigned i = 0, e = Options.size(); i != e; ++i) {
402 // Write each string, including the null byte.
403 const std::string &Option = Options[i];
404 WriteBytes(Option.c_str(), Option.size() + 1);
405 BytesWritten += Option.size() + 1;
406 }
407
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000408 // Pad to a multiple of the pointer size.
409 WriteBytes("", OffsetToAlignment(BytesWritten, is64Bit() ? 8 : 4));
Daniel Dunbareec0f322013-01-18 01:26:07 +0000410
411 assert(OS.tell() - Start == Size);
412}
413
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000414
Bill Wendlingeb872e02011-06-22 21:07:27 +0000415void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
416 const MCAsmLayout &Layout,
417 const MCFragment *Fragment,
418 const MCFixup &Fixup,
419 MCValue Target,
Rafael Espindola5904e122014-03-29 06:26:49 +0000420 bool &IsPCRel,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000421 uint64_t &FixedValue) {
Jim Grosbach28fcafb2011-06-24 23:44:37 +0000422 TargetObjectWriter->RecordRelocation(this, Asm, Layout, Fragment, Fixup,
423 Target, FixedValue);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000424}
425
426void MachObjectWriter::BindIndirectSymbols(MCAssembler &Asm) {
427 // This is the point where 'as' creates actual symbols for indirect symbols
428 // (in the following two passes). It would be easier for us to do this sooner
429 // when we see the attribute, but that makes getting the order in the symbol
430 // table much more complicated than it is worth.
431 //
432 // FIXME: Revisit this when the dust settles.
433
Kevin Enderby3aeada22013-08-28 17:50:59 +0000434 // Report errors for use of .indirect_symbol not in a symbol pointer section
435 // or stub section.
436 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
437 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
438 const MCSectionMachO &Section =
439 cast<MCSectionMachO>(it->SectionData->getSection());
440
David Majnemer7b583052014-03-07 07:36:05 +0000441 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
442 Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
443 Section.getType() != MachO::S_SYMBOL_STUBS) {
Kevin Enderby3aeada22013-08-28 17:50:59 +0000444 MCSymbol &Symbol = *it->Symbol;
445 report_fatal_error("indirect symbol '" + Symbol.getName() +
446 "' not in a symbol pointer or stub section");
447 }
448 }
449
Alp Tokerf907b892013-12-05 05:44:44 +0000450 // Bind non-lazy symbol pointers first.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000451 unsigned IndirectIndex = 0;
452 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
453 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
454 const MCSectionMachO &Section =
455 cast<MCSectionMachO>(it->SectionData->getSection());
456
David Majnemer7b583052014-03-07 07:36:05 +0000457 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS)
Bill Wendlingeb872e02011-06-22 21:07:27 +0000458 continue;
459
460 // Initialize the section indirect symbol base, if necessary.
Benjamin Kramerf29db272012-08-22 15:37:57 +0000461 IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000462
463 Asm.getOrCreateSymbolData(*it->Symbol);
464 }
465
466 // Then lazy symbol pointers and symbol stubs.
467 IndirectIndex = 0;
468 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
469 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
470 const MCSectionMachO &Section =
471 cast<MCSectionMachO>(it->SectionData->getSection());
472
David Majnemer7b583052014-03-07 07:36:05 +0000473 if (Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
474 Section.getType() != MachO::S_SYMBOL_STUBS)
Bill Wendlingeb872e02011-06-22 21:07:27 +0000475 continue;
476
477 // Initialize the section indirect symbol base, if necessary.
Benjamin Kramerf29db272012-08-22 15:37:57 +0000478 IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000479
480 // Set the symbol type to undefined lazy, but only on construction.
481 //
482 // FIXME: Do not hardcode.
483 bool Created;
484 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
485 if (Created)
486 Entry.setFlags(Entry.getFlags() | 0x0001);
487 }
488}
489
490/// ComputeSymbolTable - Compute the symbol table data
491///
492/// \param StringTable [out] - The string table data.
493/// \param StringIndexMap [out] - Map from symbol names to offsets in the
494/// string table.
Bill Wendling21162212011-06-23 00:09:43 +0000495void MachObjectWriter::
496ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
497 std::vector<MachSymbolData> &LocalSymbolData,
498 std::vector<MachSymbolData> &ExternalSymbolData,
499 std::vector<MachSymbolData> &UndefinedSymbolData) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000500 // Build section lookup table.
501 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
502 unsigned Index = 1;
503 for (MCAssembler::iterator it = Asm.begin(),
504 ie = Asm.end(); it != ie; ++it, ++Index)
505 SectionIndexMap[&it->getSection()] = Index;
506 assert(Index <= 256 && "Too many sections!");
507
508 // Index 0 is always the empty string.
509 StringMap<uint64_t> StringIndexMap;
510 StringTable += '\x00';
511
512 // Build the symbol arrays and the string table, but only for non-local
513 // symbols.
514 //
515 // The particular order that we collect the symbols and create the string
516 // table, then sort the symbols is chosen to match 'as'. Even though it
517 // doesn't matter for correctness, this is important for letting us diff .o
518 // files.
David Blaikie583a31c2014-04-18 18:24:25 +0000519 for (MCSymbolData &SD : Asm.symbols()) {
520 const MCSymbol &Symbol = SD.getSymbol();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000521
522 // Ignore non-linker visible symbols.
David Blaikie583a31c2014-04-18 18:24:25 +0000523 if (!Asm.isSymbolLinkerVisible(SD.getSymbol()))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000524 continue;
525
David Blaikie583a31c2014-04-18 18:24:25 +0000526 if (!SD.isExternal() && !Symbol.isUndefined())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000527 continue;
528
529 uint64_t &Entry = StringIndexMap[Symbol.getName()];
530 if (!Entry) {
531 Entry = StringTable.size();
532 StringTable += Symbol.getName();
533 StringTable += '\x00';
534 }
535
536 MachSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +0000537 MSD.SymbolData = &SD;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000538 MSD.StringIndex = Entry;
539
540 if (Symbol.isUndefined()) {
541 MSD.SectionIndex = 0;
542 UndefinedSymbolData.push_back(MSD);
543 } else if (Symbol.isAbsolute()) {
544 MSD.SectionIndex = 0;
545 ExternalSymbolData.push_back(MSD);
546 } else {
547 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
548 assert(MSD.SectionIndex && "Invalid section index!");
549 ExternalSymbolData.push_back(MSD);
550 }
551 }
552
553 // Now add the data for local symbols.
David Blaikie583a31c2014-04-18 18:24:25 +0000554 for (MCSymbolData &SD : Asm.symbols()) {
555 const MCSymbol &Symbol = SD.getSymbol();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000556
557 // Ignore non-linker visible symbols.
David Blaikie583a31c2014-04-18 18:24:25 +0000558 if (!Asm.isSymbolLinkerVisible(SD.getSymbol()))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000559 continue;
560
David Blaikie583a31c2014-04-18 18:24:25 +0000561 if (SD.isExternal() || Symbol.isUndefined())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000562 continue;
563
564 uint64_t &Entry = StringIndexMap[Symbol.getName()];
565 if (!Entry) {
566 Entry = StringTable.size();
567 StringTable += Symbol.getName();
568 StringTable += '\x00';
569 }
570
571 MachSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +0000572 MSD.SymbolData = &SD;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000573 MSD.StringIndex = Entry;
574
575 if (Symbol.isAbsolute()) {
576 MSD.SectionIndex = 0;
577 LocalSymbolData.push_back(MSD);
578 } else {
579 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
580 assert(MSD.SectionIndex && "Invalid section index!");
581 LocalSymbolData.push_back(MSD);
582 }
583 }
584
585 // External and undefined symbols are required to be in lexicographic order.
586 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
587 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
588
589 // Set the symbol indices.
590 Index = 0;
591 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
592 LocalSymbolData[i].SymbolData->setIndex(Index++);
593 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
594 ExternalSymbolData[i].SymbolData->setIndex(Index++);
595 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
596 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
597
598 // The string table is padded to a multiple of 4.
599 while (StringTable.size() % 4)
600 StringTable += '\x00';
601}
602
603void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
604 const MCAsmLayout &Layout) {
605 uint64_t StartAddress = 0;
606 const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
607 for (int i = 0, n = Order.size(); i != n ; ++i) {
608 const MCSectionData *SD = Order[i];
609 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
610 SectionAddress[SD] = StartAddress;
611 StartAddress += Layout.getSectionAddressSize(SD);
612
613 // Explicitly pad the section to match the alignment requirements of the
614 // following one. This is for 'gas' compatibility, it shouldn't
615 /// strictly be necessary.
616 StartAddress += getPaddingSize(SD, Layout);
617 }
618}
619
Jim Grosbachd96ef192012-09-13 23:11:25 +0000620void MachObjectWriter::markAbsoluteVariableSymbols(MCAssembler &Asm,
621 const MCAsmLayout &Layout) {
David Blaikie583a31c2014-04-18 18:24:25 +0000622 for (MCSymbolData &SD : Asm.symbols()) {
Jim Grosbachd96ef192012-09-13 23:11:25 +0000623 if (!SD.getSymbol().isVariable())
624 continue;
625
626 // Is the variable is a symbol difference (SA - SB + C) expression,
627 // and neither symbol is external, mark the variable as absolute.
628 const MCExpr *Expr = SD.getSymbol().getVariableValue();
629 MCValue Value;
Rafael Espindola3d5d4642014-03-12 16:55:59 +0000630 if (Expr->EvaluateAsRelocatable(Value, &Layout)) {
Jim Grosbachd96ef192012-09-13 23:11:25 +0000631 if (Value.getSymA() && Value.getSymB())
632 const_cast<MCSymbol*>(&SD.getSymbol())->setAbsolute();
633 }
634 }
635}
636
Bill Wendling21162212011-06-23 00:09:43 +0000637void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
638 const MCAsmLayout &Layout) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000639 computeSectionAddresses(Asm, Layout);
640
641 // Create symbol data for any indirect symbols.
642 BindIndirectSymbols(Asm);
643
Jim Grosbachd96ef192012-09-13 23:11:25 +0000644 // Mark symbol difference expressions in variables (from .set or = directives)
645 // as absolute.
646 markAbsoluteVariableSymbols(Asm, Layout);
647
Bill Wendlingeb872e02011-06-22 21:07:27 +0000648 // Compute symbol table information and bind symbol indices.
649 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
650 UndefinedSymbolData);
651}
652
Bill Wendling21162212011-06-23 00:09:43 +0000653bool MachObjectWriter::
654IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
655 const MCSymbolData &DataA,
656 const MCFragment &FB,
657 bool InSet,
658 bool IsPCRel) const {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000659 if (InSet)
660 return true;
661
662 // The effective address is
663 // addr(atom(A)) + offset(A)
664 // - addr(atom(B)) - offset(B)
665 // and the offsets are not relocatable, so the fixup is fully resolved when
666 // addr(atom(A)) - addr(atom(B)) == 0.
Craig Topperbb694de2014-04-13 04:57:38 +0000667 const MCSymbolData *A_Base = nullptr, *B_Base = nullptr;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000668
669 const MCSymbol &SA = DataA.getSymbol().AliasedSymbol();
670 const MCSection &SecA = SA.getSection();
671 const MCSection &SecB = FB.getParent()->getSection();
672
673 if (IsPCRel) {
674 // The simple (Darwin, except on x86_64) way of dealing with this was to
675 // assume that any reference to a temporary symbol *must* be a temporary
676 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
677 // relocation to a temporary symbol (in the same section) is fully
678 // resolved. This also works in conjunction with absolutized .set, which
679 // requires the compiler to use .set to absolutize the differences between
680 // symbols which the compiler knows to be assembly time constants, so we
681 // don't need to worry about considering symbol differences fully resolved.
Jim Grosbachd6ae4ba2011-12-07 19:46:59 +0000682 //
683 // If the file isn't using sub-sections-via-symbols, we can make the
684 // same assumptions about any symbol that we normally make about
685 // assembler locals.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000686
Rafael Espindolaa063bdd2014-03-11 21:22:57 +0000687 bool hasReliableSymbolDifference = isX86_64();
688 if (!hasReliableSymbolDifference) {
Jim Grosbach40455072012-01-17 22:14:39 +0000689 if (!SA.isInSection() || &SecA != &SecB ||
Jim Grosbachd4dbd092012-01-18 21:54:12 +0000690 (!SA.isTemporary() &&
Jim Grosbach35bc8f92012-01-24 21:45:25 +0000691 FB.getAtom() != Asm.getSymbolData(SA).getFragment()->getAtom() &&
692 Asm.getSubsectionsViaSymbols()))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000693 return false;
694 return true;
695 }
Kevin Enderby7b46bb82011-09-08 20:53:44 +0000696 // For Darwin x86_64, there is one special case when the reference IsPCRel.
697 // If the fragment with the reference does not have a base symbol but meets
698 // the simple way of dealing with this, in that it is a temporary symbol in
699 // the same atom then it is assumed to be fully resolved. This is needed so
Eric Christopher460be992011-09-08 22:17:40 +0000700 // a relocation entry is not created and so the static linker does not
Kevin Enderby7b46bb82011-09-08 20:53:44 +0000701 // mess up the reference later.
702 else if(!FB.getAtom() &&
703 SA.isTemporary() && SA.isInSection() && &SecA == &SecB){
704 return true;
705 }
Bill Wendlingeb872e02011-06-22 21:07:27 +0000706 } else {
707 if (!TargetObjectWriter->useAggressiveSymbolFolding())
708 return false;
709 }
710
Benjamin Kramer91ea5112011-08-12 01:51:29 +0000711 const MCFragment *FA = Asm.getSymbolData(SA).getFragment();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000712
Benjamin Kramer91ea5112011-08-12 01:51:29 +0000713 // Bail if the symbol has no fragment.
714 if (!FA)
715 return false;
716
717 A_Base = FA->getAtom();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000718 if (!A_Base)
719 return false;
720
721 B_Base = FB.getAtom();
722 if (!B_Base)
723 return false;
724
725 // If the atoms are the same, they are guaranteed to have the same address.
726 if (A_Base == B_Base)
727 return true;
728
729 // Otherwise, we can't prove this is fully resolved.
730 return false;
731}
732
Eric Christopher460be992011-09-08 22:17:40 +0000733void MachObjectWriter::WriteObject(MCAssembler &Asm,
Jim Grosbach46be3012011-12-06 00:13:09 +0000734 const MCAsmLayout &Layout) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000735 unsigned NumSections = Asm.size();
Jim Grosbach448334a2014-03-18 22:09:05 +0000736 const MCAssembler::VersionMinInfoType &VersionInfo =
737 Layout.getAssembler().getVersionMinInfo();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000738
739 // The section data starts after the header, the segment load command (and
740 // section headers) and the symbol table.
741 unsigned NumLoadCommands = 1;
742 uint64_t LoadCommandsSize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +0000743 sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64):
744 sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000745
Jim Grosbach448334a2014-03-18 22:09:05 +0000746 // Add the deployment target version info load command size, if used.
747 if (VersionInfo.Major != 0) {
748 ++NumLoadCommands;
749 LoadCommandsSize += sizeof(MachO::version_min_command);
750 }
751
Daniel Dunbareec0f322013-01-18 01:26:07 +0000752 // Add the data-in-code load command size, if used.
753 unsigned NumDataRegions = Asm.getDataRegions().size();
754 if (NumDataRegions) {
755 ++NumLoadCommands;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000756 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000757 }
758
Tim Northover53d32512014-03-29 07:34:53 +0000759 // Add the loh load command size, if used.
760 uint64_t LOHRawSize = Asm.getLOHContainer().getEmitSize(*this, Layout);
761 uint64_t LOHSize = RoundUpToAlignment(LOHRawSize, is64Bit() ? 8 : 4);
762 if (LOHSize) {
763 ++NumLoadCommands;
764 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
765 }
766
Bill Wendlingeb872e02011-06-22 21:07:27 +0000767 // Add the symbol table load command sizes, if used.
768 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
769 UndefinedSymbolData.size();
770 if (NumSymbols) {
771 NumLoadCommands += 2;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000772 LoadCommandsSize += (sizeof(MachO::symtab_command) +
773 sizeof(MachO::dysymtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000774 }
775
Daniel Dunbareec0f322013-01-18 01:26:07 +0000776 // Add the linker option load commands sizes.
777 const std::vector<std::vector<std::string> > &LinkerOptions =
778 Asm.getLinkerOptions();
779 for (unsigned i = 0, e = LinkerOptions.size(); i != e; ++i) {
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000780 ++NumLoadCommands;
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000781 LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(LinkerOptions[i],
782 is64Bit());
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000783 }
Daniel Dunbareec0f322013-01-18 01:26:07 +0000784
Bill Wendlingeb872e02011-06-22 21:07:27 +0000785 // Compute the total size of the section data, as well as its file size and vm
786 // size.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000787 uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) :
788 sizeof(MachO::mach_header)) + LoadCommandsSize;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000789 uint64_t SectionDataSize = 0;
790 uint64_t SectionDataFileSize = 0;
791 uint64_t VMSize = 0;
792 for (MCAssembler::const_iterator it = Asm.begin(),
793 ie = Asm.end(); it != ie; ++it) {
794 const MCSectionData &SD = *it;
795 uint64_t Address = getSectionAddress(&SD);
796 uint64_t Size = Layout.getSectionAddressSize(&SD);
797 uint64_t FileSize = Layout.getSectionFileSize(&SD);
798 FileSize += getPaddingSize(&SD, Layout);
799
800 VMSize = std::max(VMSize, Address + Size);
801
802 if (SD.getSection().isVirtualSection())
803 continue;
804
805 SectionDataSize = std::max(SectionDataSize, Address + Size);
806 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
807 }
808
809 // The section data is padded to 4 bytes.
810 //
811 // FIXME: Is this machine dependent?
812 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
813 SectionDataFileSize += SectionDataPadding;
814
815 // Write the prolog, starting with the header and load command...
816 WriteHeader(NumLoadCommands, LoadCommandsSize,
817 Asm.getSubsectionsViaSymbols());
818 WriteSegmentLoadCommand(NumSections, VMSize,
819 SectionDataStart, SectionDataSize);
820
821 // ... and then the section headers.
822 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
823 for (MCAssembler::const_iterator it = Asm.begin(),
824 ie = Asm.end(); it != ie; ++it) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000825 std::vector<MachO::any_relocation_info> &Relocs = Relocations[it];
Bill Wendlingeb872e02011-06-22 21:07:27 +0000826 unsigned NumRelocs = Relocs.size();
827 uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
828 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000829 RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000830 }
831
Jim Grosbach448334a2014-03-18 22:09:05 +0000832 // Write out the deployment target information, if it's available.
833 if (VersionInfo.Major != 0) {
834 assert(VersionInfo.Update < 256 && "unencodable update target version");
835 assert(VersionInfo.Minor < 256 && "unencodable minor target version");
836 assert(VersionInfo.Major < 65536 && "unencodable major target version");
837 uint32_t EncodedVersion = VersionInfo.Update | (VersionInfo.Minor << 8) |
838 (VersionInfo.Major << 16);
839 Write32(VersionInfo.Kind == MCVM_OSXVersionMin ? MachO::LC_VERSION_MIN_MACOSX :
840 MachO::LC_VERSION_MIN_IPHONEOS);
841 Write32(sizeof(MachO::version_min_command));
842 Write32(EncodedVersion);
843 Write32(0); // reserved.
844 }
845
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000846 // Write the data-in-code load command, if used.
847 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
848 if (NumDataRegions) {
849 uint64_t DataRegionsOffset = RelocTableEnd;
850 uint64_t DataRegionsSize = NumDataRegions * 8;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000851 WriteLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset,
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000852 DataRegionsSize);
853 }
854
Tim Northover53d32512014-03-29 07:34:53 +0000855 // Write the loh load command, if used.
856 uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize;
857 if (LOHSize)
858 WriteLinkeditLoadCommand(MachO::LC_LINKER_OPTIMIZATION_HINT,
859 DataInCodeTableEnd, LOHSize);
860
Bill Wendlingeb872e02011-06-22 21:07:27 +0000861 // Write the symbol table load command, if used.
862 if (NumSymbols) {
863 unsigned FirstLocalSymbol = 0;
864 unsigned NumLocalSymbols = LocalSymbolData.size();
865 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
866 unsigned NumExternalSymbols = ExternalSymbolData.size();
867 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
868 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
869 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
870 unsigned NumSymTabSymbols =
871 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
872 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
873 uint64_t IndirectSymbolOffset = 0;
874
875 // If used, the indirect symbols are written after the section data.
876 if (NumIndirectSymbols)
Tim Northover53d32512014-03-29 07:34:53 +0000877 IndirectSymbolOffset = LOHTableEnd;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000878
879 // The symbol table is written after the indirect symbol data.
Tim Northover53d32512014-03-29 07:34:53 +0000880 uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000881
882 // The string table is written after symbol table.
883 uint64_t StringTableOffset =
Charles Davis8bdfafd2013-09-01 04:28:48 +0000884 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ?
885 sizeof(MachO::nlist_64) :
886 sizeof(MachO::nlist));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000887 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
888 StringTableOffset, StringTable.size());
889
890 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
891 FirstExternalSymbol, NumExternalSymbols,
892 FirstUndefinedSymbol, NumUndefinedSymbols,
893 IndirectSymbolOffset, NumIndirectSymbols);
894 }
895
Daniel Dunbareec0f322013-01-18 01:26:07 +0000896 // Write the linker options load commands.
897 for (unsigned i = 0, e = LinkerOptions.size(); i != e; ++i) {
898 WriteLinkerOptionsLoadCommand(LinkerOptions[i]);
899 }
900
Bill Wendlingeb872e02011-06-22 21:07:27 +0000901 // Write the actual section data.
902 for (MCAssembler::const_iterator it = Asm.begin(),
903 ie = Asm.end(); it != ie; ++it) {
Jim Grosbach18e2fe42011-12-06 00:03:48 +0000904 Asm.writeSectionData(it, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000905
906 uint64_t Pad = getPaddingSize(it, Layout);
907 for (unsigned int i = 0; i < Pad; ++i)
908 Write8(0);
909 }
910
911 // Write the extra padding.
912 WriteZeros(SectionDataPadding);
913
914 // Write the relocation entries.
915 for (MCAssembler::const_iterator it = Asm.begin(),
916 ie = Asm.end(); it != ie; ++it) {
917 // Write the section relocation entries, in reverse order to match 'as'
918 // (approximately, the exact algorithm is more complicated than this).
Charles Davis8bdfafd2013-09-01 04:28:48 +0000919 std::vector<MachO::any_relocation_info> &Relocs = Relocations[it];
Bill Wendlingeb872e02011-06-22 21:07:27 +0000920 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000921 Write32(Relocs[e - i - 1].r_word0);
922 Write32(Relocs[e - i - 1].r_word1);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000923 }
924 }
925
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000926 // Write out the data-in-code region payload, if there is one.
927 for (MCAssembler::const_data_region_iterator
928 it = Asm.data_region_begin(), ie = Asm.data_region_end();
929 it != ie; ++it) {
930 const DataRegionData *Data = &(*it);
Jim Grosbachb12b71a2012-09-18 23:05:12 +0000931 uint64_t Start =
932 getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->Start),
933 Layout);
934 uint64_t End =
935 getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->End),
936 Layout);
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000937 DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
938 << " start: " << Start << "(" << Data->Start->getName() << ")"
939 << " end: " << End << "(" << Data->End->getName() << ")"
940 << " size: " << End - Start
941 << "\n");
942 Write32(Start);
943 Write16(End - Start);
944 Write16(Data->Kind);
945 }
946
Tim Northover53d32512014-03-29 07:34:53 +0000947 // Write out the loh commands, if there is one.
948 if (LOHSize) {
949#ifndef NDEBUG
950 unsigned Start = OS.tell();
951#endif
952 Asm.getLOHContainer().Emit(*this, Layout);
953 // Pad to a multiple of the pointer size.
954 WriteBytes("", OffsetToAlignment(LOHRawSize, is64Bit() ? 8 : 4));
955 assert(OS.tell() - Start == LOHSize);
956 }
957
Bill Wendlingeb872e02011-06-22 21:07:27 +0000958 // Write the symbol table data, if used.
959 if (NumSymbols) {
960 // Write the indirect symbol entries.
961 for (MCAssembler::const_indirect_symbol_iterator
962 it = Asm.indirect_symbol_begin(),
963 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
Alp Tokerf907b892013-12-05 05:44:44 +0000964 // Indirect symbols in the non-lazy symbol pointer section have some
Bill Wendlingeb872e02011-06-22 21:07:27 +0000965 // special handling.
966 const MCSectionMachO &Section =
967 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
David Majnemer7b583052014-03-07 07:36:05 +0000968 if (Section.getType() == MachO::S_NON_LAZY_SYMBOL_POINTERS) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000969 // If this symbol is defined and internal, mark it as such.
970 if (it->Symbol->isDefined() &&
971 !Asm.getSymbolData(*it->Symbol).isExternal()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000972 uint32_t Flags = MachO::INDIRECT_SYMBOL_LOCAL;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000973 if (it->Symbol->isAbsolute())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000974 Flags |= MachO::INDIRECT_SYMBOL_ABS;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000975 Write32(Flags);
976 continue;
977 }
978 }
979
980 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
981 }
982
983 // FIXME: Check that offsets match computed ones.
984
985 // Write the symbol table entries.
986 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
987 WriteNlist(LocalSymbolData[i], Layout);
988 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
989 WriteNlist(ExternalSymbolData[i], Layout);
990 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
991 WriteNlist(UndefinedSymbolData[i], Layout);
992
993 // Write the string table.
994 OS << StringTable.str();
995 }
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +0000996}
997
Daniel Dunbar8888a962010-12-16 16:09:19 +0000998MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
Daniel Dunbar03fcccb2010-12-16 17:21:02 +0000999 raw_ostream &OS,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001000 bool IsLittleEndian) {
Daniel Dunbar03fcccb2010-12-16 17:21:02 +00001001 return new MachObjectWriter(MOTW, OS, IsLittleEndian);
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +00001002}