blob: cbaf0b87d6e29ce98792c262c4f8c85c88ada8a2 [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
Chandler Carruthe96dd892014-04-21 22:55:11 +000029#define DEBUG_TYPE "mc"
30
Pedro Artigasb95c53e2012-12-14 18:52:11 +000031void MachObjectWriter::reset() {
32 Relocations.clear();
33 IndirectSymBase.clear();
34 StringTable.clear();
35 LocalSymbolData.clear();
36 ExternalSymbolData.clear();
37 UndefinedSymbolData.clear();
38 MCObjectWriter::reset();
39}
40
Jim Grosbach28fcafb2011-06-24 23:44:37 +000041bool MachObjectWriter::
42doesSymbolRequireExternRelocation(const MCSymbolData *SD) {
Daniel Dunbar7de31062010-05-10 23:15:13 +000043 // Undefined symbols are always extern.
44 if (SD->Symbol->isUndefined())
45 return true;
46
47 // References to weak definitions require external relocation entries; the
48 // definition may not always be the one in the same object file.
49 if (SD->getFlags() & SF_WeakDefinition)
50 return true;
51
52 // Otherwise, we can use an internal relocation.
53 return false;
54}
55
Jim Grosbach28fcafb2011-06-24 23:44:37 +000056bool MachObjectWriter::
57MachSymbolData::operator<(const MachSymbolData &RHS) const {
58 return SymbolData->getSymbol().getName() <
59 RHS.SymbolData->getSymbol().getName();
60}
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000061
Jim Grosbach28fcafb2011-06-24 23:44:37 +000062bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
63 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
64 (MCFixupKind) Kind);
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000065
Jim Grosbach28fcafb2011-06-24 23:44:37 +000066 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
67}
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000068
Jim Grosbach28fcafb2011-06-24 23:44:37 +000069uint64_t MachObjectWriter::getFragmentAddress(const MCFragment *Fragment,
70 const MCAsmLayout &Layout) const {
71 return getSectionAddress(Fragment->getParent()) +
72 Layout.getFragmentOffset(Fragment);
73}
Bill Wendlingeb872e02011-06-22 21:07:27 +000074
75uint64_t MachObjectWriter::getSymbolAddress(const MCSymbolData* SD,
76 const MCAsmLayout &Layout) const {
77 const MCSymbol &S = SD->getSymbol();
78
79 // If this is a variable, then recursively evaluate now.
80 if (S.isVariable()) {
Jim Grosbachd96ef192012-09-13 23:11:25 +000081 if (const MCConstantExpr *C =
82 dyn_cast<const MCConstantExpr>(S.getVariableValue()))
83 return C->getValue();
84
85
Bill Wendlingeb872e02011-06-22 21:07:27 +000086 MCValue Target;
Rafael Espindola3d5d4642014-03-12 16:55:59 +000087 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, &Layout))
Bill Wendlingeb872e02011-06-22 21:07:27 +000088 report_fatal_error("unable to evaluate offset for variable '" +
89 S.getName() + "'");
90
91 // Verify that any used symbols are defined.
92 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
93 report_fatal_error("unable to evaluate offset to undefined symbol '" +
94 Target.getSymA()->getSymbol().getName() + "'");
95 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
96 report_fatal_error("unable to evaluate offset to undefined symbol '" +
97 Target.getSymB()->getSymbol().getName() + "'");
98
99 uint64_t Address = Target.getConstant();
100 if (Target.getSymA())
101 Address += getSymbolAddress(&Layout.getAssembler().getSymbolData(
102 Target.getSymA()->getSymbol()), Layout);
103 if (Target.getSymB())
104 Address += getSymbolAddress(&Layout.getAssembler().getSymbolData(
105 Target.getSymB()->getSymbol()), Layout);
106 return Address;
107 }
108
109 return getSectionAddress(SD->getFragment()->getParent()) +
110 Layout.getSymbolOffset(SD);
111}
112
113uint64_t MachObjectWriter::getPaddingSize(const MCSectionData *SD,
114 const MCAsmLayout &Layout) const {
115 uint64_t EndAddr = getSectionAddress(SD) + Layout.getSectionAddressSize(SD);
116 unsigned Next = SD->getLayoutOrder() + 1;
117 if (Next >= Layout.getSectionOrder().size())
118 return 0;
119
120 const MCSectionData &NextSD = *Layout.getSectionOrder()[Next];
121 if (NextSD.getSection().isVirtualSection())
122 return 0;
123 return OffsetToAlignment(EndAddr, NextSD.getAlignment());
124}
125
126void MachObjectWriter::WriteHeader(unsigned NumLoadCommands,
127 unsigned LoadCommandsSize,
128 bool SubsectionsViaSymbols) {
129 uint32_t Flags = 0;
130
131 if (SubsectionsViaSymbols)
Charles Davis8bdfafd2013-09-01 04:28:48 +0000132 Flags |= MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000133
134 // struct mach_header (28 bytes) or
135 // struct mach_header_64 (32 bytes)
136
137 uint64_t Start = OS.tell();
138 (void) Start;
139
Charles Davis8bdfafd2013-09-01 04:28:48 +0000140 Write32(is64Bit() ? MachO::MH_MAGIC_64 : MachO::MH_MAGIC);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000141
142 Write32(TargetObjectWriter->getCPUType());
143 Write32(TargetObjectWriter->getCPUSubtype());
144
Charles Davis8bdfafd2013-09-01 04:28:48 +0000145 Write32(MachO::MH_OBJECT);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000146 Write32(NumLoadCommands);
147 Write32(LoadCommandsSize);
148 Write32(Flags);
149 if (is64Bit())
150 Write32(0); // reserved
151
152 assert(OS.tell() - Start ==
Charles Davis8bdfafd2013-09-01 04:28:48 +0000153 (is64Bit()?sizeof(MachO::mach_header_64): sizeof(MachO::mach_header)));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000154}
155
156/// WriteSegmentLoadCommand - Write a segment load command.
157///
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000158/// \param NumSections The number of sections in this segment.
159/// \param SectionDataSize The total size of the sections.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000160void MachObjectWriter::WriteSegmentLoadCommand(unsigned NumSections,
161 uint64_t VMSize,
162 uint64_t SectionDataStartOffset,
163 uint64_t SectionDataSize) {
164 // struct segment_command (56 bytes) or
165 // struct segment_command_64 (72 bytes)
166
167 uint64_t Start = OS.tell();
168 (void) Start;
169
170 unsigned SegmentLoadCommandSize =
Charles Davis8bdfafd2013-09-01 04:28:48 +0000171 is64Bit() ? sizeof(MachO::segment_command_64):
172 sizeof(MachO::segment_command);
173 Write32(is64Bit() ? MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000174 Write32(SegmentLoadCommandSize +
Charles Davis8bdfafd2013-09-01 04:28:48 +0000175 NumSections * (is64Bit() ? sizeof(MachO::section_64) :
176 sizeof(MachO::section)));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000177
178 WriteBytes("", 16);
179 if (is64Bit()) {
180 Write64(0); // vmaddr
181 Write64(VMSize); // vmsize
182 Write64(SectionDataStartOffset); // file offset
183 Write64(SectionDataSize); // file size
184 } else {
185 Write32(0); // vmaddr
186 Write32(VMSize); // vmsize
187 Write32(SectionDataStartOffset); // file offset
188 Write32(SectionDataSize); // file size
189 }
Nick Kledzikfe6813f2013-09-04 23:53:44 +0000190 // maxprot
191 Write32(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE);
192 // initprot
193 Write32(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000194 Write32(NumSections);
195 Write32(0); // flags
196
197 assert(OS.tell() - Start == SegmentLoadCommandSize);
198}
199
200void MachObjectWriter::WriteSection(const MCAssembler &Asm,
201 const MCAsmLayout &Layout,
202 const MCSectionData &SD,
203 uint64_t FileOffset,
204 uint64_t RelocationsStart,
205 unsigned NumRelocations) {
206 uint64_t SectionSize = Layout.getSectionAddressSize(&SD);
207
208 // The offset is unused for virtual sections.
209 if (SD.getSection().isVirtualSection()) {
210 assert(Layout.getSectionFileSize(&SD) == 0 && "Invalid file size!");
211 FileOffset = 0;
212 }
213
214 // struct section (68 bytes) or
215 // struct section_64 (80 bytes)
216
217 uint64_t Start = OS.tell();
218 (void) Start;
219
220 const MCSectionMachO &Section = cast<MCSectionMachO>(SD.getSection());
221 WriteBytes(Section.getSectionName(), 16);
222 WriteBytes(Section.getSegmentName(), 16);
223 if (is64Bit()) {
224 Write64(getSectionAddress(&SD)); // address
225 Write64(SectionSize); // size
226 } else {
227 Write32(getSectionAddress(&SD)); // address
228 Write32(SectionSize); // size
229 }
230 Write32(FileOffset);
231
232 unsigned Flags = Section.getTypeAndAttributes();
233 if (SD.hasInstructions())
David Majnemer7b583052014-03-07 07:36:05 +0000234 Flags |= MachO::S_ATTR_SOME_INSTRUCTIONS;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000235
236 assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
237 Write32(Log2_32(SD.getAlignment()));
238 Write32(NumRelocations ? RelocationsStart : 0);
239 Write32(NumRelocations);
240 Write32(Flags);
241 Write32(IndirectSymBase.lookup(&SD)); // reserved1
242 Write32(Section.getStubSize()); // reserved2
243 if (is64Bit())
244 Write32(0); // reserved3
245
Charles Davis8bdfafd2013-09-01 04:28:48 +0000246 assert(OS.tell() - Start == (is64Bit() ? sizeof(MachO::section_64) :
247 sizeof(MachO::section)));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000248}
249
250void MachObjectWriter::WriteSymtabLoadCommand(uint32_t SymbolOffset,
251 uint32_t NumSymbols,
252 uint32_t StringTableOffset,
253 uint32_t StringTableSize) {
254 // struct symtab_command (24 bytes)
255
256 uint64_t Start = OS.tell();
257 (void) Start;
258
Charles Davis8bdfafd2013-09-01 04:28:48 +0000259 Write32(MachO::LC_SYMTAB);
260 Write32(sizeof(MachO::symtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000261 Write32(SymbolOffset);
262 Write32(NumSymbols);
263 Write32(StringTableOffset);
264 Write32(StringTableSize);
265
Charles Davis8bdfafd2013-09-01 04:28:48 +0000266 assert(OS.tell() - Start == sizeof(MachO::symtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000267}
268
269void MachObjectWriter::WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
270 uint32_t NumLocalSymbols,
271 uint32_t FirstExternalSymbol,
272 uint32_t NumExternalSymbols,
273 uint32_t FirstUndefinedSymbol,
274 uint32_t NumUndefinedSymbols,
275 uint32_t IndirectSymbolOffset,
276 uint32_t NumIndirectSymbols) {
277 // struct dysymtab_command (80 bytes)
278
279 uint64_t Start = OS.tell();
280 (void) Start;
281
Charles Davis8bdfafd2013-09-01 04:28:48 +0000282 Write32(MachO::LC_DYSYMTAB);
283 Write32(sizeof(MachO::dysymtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000284 Write32(FirstLocalSymbol);
285 Write32(NumLocalSymbols);
286 Write32(FirstExternalSymbol);
287 Write32(NumExternalSymbols);
288 Write32(FirstUndefinedSymbol);
289 Write32(NumUndefinedSymbols);
290 Write32(0); // tocoff
291 Write32(0); // ntoc
292 Write32(0); // modtaboff
293 Write32(0); // nmodtab
294 Write32(0); // extrefsymoff
295 Write32(0); // nextrefsyms
296 Write32(IndirectSymbolOffset);
297 Write32(NumIndirectSymbols);
298 Write32(0); // extreloff
299 Write32(0); // nextrel
300 Write32(0); // locreloff
301 Write32(0); // nlocrel
302
Charles Davis8bdfafd2013-09-01 04:28:48 +0000303 assert(OS.tell() - Start == sizeof(MachO::dysymtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000304}
305
Bill Wendling21162212011-06-23 00:09:43 +0000306void MachObjectWriter::WriteNlist(MachSymbolData &MSD,
307 const MCAsmLayout &Layout) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000308 MCSymbolData &Data = *MSD.SymbolData;
309 const MCSymbol &Symbol = Data.getSymbol();
310 uint8_t Type = 0;
311 uint16_t Flags = Data.getFlags();
Jim Grosbacha3171602011-08-09 22:12:37 +0000312 uint64_t Address = 0;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000313
314 // Set the N_TYPE bits. See <mach-o/nlist.h>.
315 //
316 // FIXME: Are the prebound or indirect fields possible here?
317 if (Symbol.isUndefined())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000318 Type = MachO::N_UNDF;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000319 else if (Symbol.isAbsolute())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000320 Type = MachO::N_ABS;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000321 else
Charles Davis8bdfafd2013-09-01 04:28:48 +0000322 Type = MachO::N_SECT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000323
324 // FIXME: Set STAB bits.
325
326 if (Data.isPrivateExtern())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000327 Type |= MachO::N_PEXT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000328
329 // Set external bit.
330 if (Data.isExternal() || Symbol.isUndefined())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000331 Type |= MachO::N_EXT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000332
333 // Compute the symbol address.
334 if (Symbol.isDefined()) {
Jim Grosbachd96ef192012-09-13 23:11:25 +0000335 Address = getSymbolAddress(&Data, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000336 } else if (Data.isCommon()) {
337 // Common symbols are encoded with the size in the address
338 // field, and their alignment in the flags.
339 Address = Data.getCommonSize();
340
341 // Common alignment is packed into the 'desc' bits.
342 if (unsigned Align = Data.getCommonAlignment()) {
343 unsigned Log2Size = Log2_32(Align);
344 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
345 if (Log2Size > 15)
346 report_fatal_error("invalid 'common' alignment '" +
Jim Grosbachaff6a0c2013-09-24 23:56:31 +0000347 Twine(Align) + "' for '" + Symbol.getName() + "'",
348 false);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000349 // FIXME: Keep this mask with the SymbolFlags enumeration.
350 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
351 }
352 }
353
Rafael Espindolab60c8292014-04-29 12:46:50 +0000354 if (Layout.getAssembler().isThumbFunc(&Symbol))
355 Flags |= SF_ThumbFunc;
356
Bill Wendlingeb872e02011-06-22 21:07:27 +0000357 // struct nlist (12 bytes)
358
359 Write32(MSD.StringIndex);
360 Write8(Type);
361 Write8(MSD.SectionIndex);
362
363 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
364 // value.
365 Write16(Flags);
366 if (is64Bit())
367 Write64(Address);
368 else
369 Write32(Address);
370}
371
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000372void MachObjectWriter::WriteLinkeditLoadCommand(uint32_t Type,
373 uint32_t DataOffset,
374 uint32_t DataSize) {
375 uint64_t Start = OS.tell();
376 (void) Start;
377
378 Write32(Type);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000379 Write32(sizeof(MachO::linkedit_data_command));
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000380 Write32(DataOffset);
381 Write32(DataSize);
382
Charles Davis8bdfafd2013-09-01 04:28:48 +0000383 assert(OS.tell() - Start == sizeof(MachO::linkedit_data_command));
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000384}
385
Daniel Dunbareec0f322013-01-18 01:26:07 +0000386static unsigned ComputeLinkerOptionsLoadCommandSize(
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000387 const std::vector<std::string> &Options, bool is64Bit)
Daniel Dunbareec0f322013-01-18 01:26:07 +0000388{
Charles Davis8bdfafd2013-09-01 04:28:48 +0000389 unsigned Size = sizeof(MachO::linker_options_command);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000390 for (unsigned i = 0, e = Options.size(); i != e; ++i)
391 Size += Options[i].size() + 1;
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000392 return RoundUpToAlignment(Size, is64Bit ? 8 : 4);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000393}
394
395void MachObjectWriter::WriteLinkerOptionsLoadCommand(
396 const std::vector<std::string> &Options)
397{
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000398 unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit());
Daniel Dunbareec0f322013-01-18 01:26:07 +0000399 uint64_t Start = OS.tell();
400 (void) Start;
401
Charles Davis8bdfafd2013-09-01 04:28:48 +0000402 Write32(MachO::LC_LINKER_OPTIONS);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000403 Write32(Size);
404 Write32(Options.size());
Charles Davis8bdfafd2013-09-01 04:28:48 +0000405 uint64_t BytesWritten = sizeof(MachO::linker_options_command);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000406 for (unsigned i = 0, e = Options.size(); i != e; ++i) {
407 // Write each string, including the null byte.
408 const std::string &Option = Options[i];
409 WriteBytes(Option.c_str(), Option.size() + 1);
410 BytesWritten += Option.size() + 1;
411 }
412
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000413 // Pad to a multiple of the pointer size.
414 WriteBytes("", OffsetToAlignment(BytesWritten, is64Bit() ? 8 : 4));
Daniel Dunbareec0f322013-01-18 01:26:07 +0000415
416 assert(OS.tell() - Start == Size);
417}
418
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000419
Bill Wendlingeb872e02011-06-22 21:07:27 +0000420void MachObjectWriter::RecordRelocation(const MCAssembler &Asm,
421 const MCAsmLayout &Layout,
422 const MCFragment *Fragment,
423 const MCFixup &Fixup,
424 MCValue Target,
Rafael Espindola5904e122014-03-29 06:26:49 +0000425 bool &IsPCRel,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000426 uint64_t &FixedValue) {
Jim Grosbach28fcafb2011-06-24 23:44:37 +0000427 TargetObjectWriter->RecordRelocation(this, Asm, Layout, Fragment, Fixup,
428 Target, FixedValue);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000429}
430
431void MachObjectWriter::BindIndirectSymbols(MCAssembler &Asm) {
432 // This is the point where 'as' creates actual symbols for indirect symbols
433 // (in the following two passes). It would be easier for us to do this sooner
434 // when we see the attribute, but that makes getting the order in the symbol
435 // table much more complicated than it is worth.
436 //
437 // FIXME: Revisit this when the dust settles.
438
Kevin Enderby3aeada22013-08-28 17:50:59 +0000439 // Report errors for use of .indirect_symbol not in a symbol pointer section
440 // or stub section.
441 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
442 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
443 const MCSectionMachO &Section =
444 cast<MCSectionMachO>(it->SectionData->getSection());
445
David Majnemer7b583052014-03-07 07:36:05 +0000446 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
447 Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
448 Section.getType() != MachO::S_SYMBOL_STUBS) {
Kevin Enderby3aeada22013-08-28 17:50:59 +0000449 MCSymbol &Symbol = *it->Symbol;
450 report_fatal_error("indirect symbol '" + Symbol.getName() +
451 "' not in a symbol pointer or stub section");
452 }
453 }
454
Alp Tokerf907b892013-12-05 05:44:44 +0000455 // Bind non-lazy symbol pointers first.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000456 unsigned IndirectIndex = 0;
457 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
458 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
459 const MCSectionMachO &Section =
460 cast<MCSectionMachO>(it->SectionData->getSection());
461
David Majnemer7b583052014-03-07 07:36:05 +0000462 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS)
Bill Wendlingeb872e02011-06-22 21:07:27 +0000463 continue;
464
465 // Initialize the section indirect symbol base, if necessary.
Benjamin Kramerf29db272012-08-22 15:37:57 +0000466 IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000467
468 Asm.getOrCreateSymbolData(*it->Symbol);
469 }
470
471 // Then lazy symbol pointers and symbol stubs.
472 IndirectIndex = 0;
473 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
474 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
475 const MCSectionMachO &Section =
476 cast<MCSectionMachO>(it->SectionData->getSection());
477
David Majnemer7b583052014-03-07 07:36:05 +0000478 if (Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
479 Section.getType() != MachO::S_SYMBOL_STUBS)
Bill Wendlingeb872e02011-06-22 21:07:27 +0000480 continue;
481
482 // Initialize the section indirect symbol base, if necessary.
Benjamin Kramerf29db272012-08-22 15:37:57 +0000483 IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000484
485 // Set the symbol type to undefined lazy, but only on construction.
486 //
487 // FIXME: Do not hardcode.
488 bool Created;
489 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
490 if (Created)
491 Entry.setFlags(Entry.getFlags() | 0x0001);
492 }
493}
494
495/// ComputeSymbolTable - Compute the symbol table data
496///
497/// \param StringTable [out] - The string table data.
498/// \param StringIndexMap [out] - Map from symbol names to offsets in the
499/// string table.
Bill Wendling21162212011-06-23 00:09:43 +0000500void MachObjectWriter::
501ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
502 std::vector<MachSymbolData> &LocalSymbolData,
503 std::vector<MachSymbolData> &ExternalSymbolData,
504 std::vector<MachSymbolData> &UndefinedSymbolData) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000505 // Build section lookup table.
506 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
507 unsigned Index = 1;
508 for (MCAssembler::iterator it = Asm.begin(),
509 ie = Asm.end(); it != ie; ++it, ++Index)
510 SectionIndexMap[&it->getSection()] = Index;
511 assert(Index <= 256 && "Too many sections!");
512
513 // Index 0 is always the empty string.
514 StringMap<uint64_t> StringIndexMap;
515 StringTable += '\x00';
516
517 // Build the symbol arrays and the string table, but only for non-local
518 // symbols.
519 //
520 // The particular order that we collect the symbols and create the string
521 // table, then sort the symbols is chosen to match 'as'. Even though it
522 // doesn't matter for correctness, this is important for letting us diff .o
523 // files.
David Blaikie583a31c2014-04-18 18:24:25 +0000524 for (MCSymbolData &SD : Asm.symbols()) {
525 const MCSymbol &Symbol = SD.getSymbol();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000526
527 // Ignore non-linker visible symbols.
David Blaikie583a31c2014-04-18 18:24:25 +0000528 if (!Asm.isSymbolLinkerVisible(SD.getSymbol()))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000529 continue;
530
David Blaikie583a31c2014-04-18 18:24:25 +0000531 if (!SD.isExternal() && !Symbol.isUndefined())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000532 continue;
533
534 uint64_t &Entry = StringIndexMap[Symbol.getName()];
535 if (!Entry) {
536 Entry = StringTable.size();
537 StringTable += Symbol.getName();
538 StringTable += '\x00';
539 }
540
541 MachSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +0000542 MSD.SymbolData = &SD;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000543 MSD.StringIndex = Entry;
544
545 if (Symbol.isUndefined()) {
546 MSD.SectionIndex = 0;
547 UndefinedSymbolData.push_back(MSD);
548 } else if (Symbol.isAbsolute()) {
549 MSD.SectionIndex = 0;
550 ExternalSymbolData.push_back(MSD);
551 } else {
552 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
553 assert(MSD.SectionIndex && "Invalid section index!");
554 ExternalSymbolData.push_back(MSD);
555 }
556 }
557
558 // Now add the data for local symbols.
David Blaikie583a31c2014-04-18 18:24:25 +0000559 for (MCSymbolData &SD : Asm.symbols()) {
560 const MCSymbol &Symbol = SD.getSymbol();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000561
562 // Ignore non-linker visible symbols.
David Blaikie583a31c2014-04-18 18:24:25 +0000563 if (!Asm.isSymbolLinkerVisible(SD.getSymbol()))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000564 continue;
565
David Blaikie583a31c2014-04-18 18:24:25 +0000566 if (SD.isExternal() || Symbol.isUndefined())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000567 continue;
568
569 uint64_t &Entry = StringIndexMap[Symbol.getName()];
570 if (!Entry) {
571 Entry = StringTable.size();
572 StringTable += Symbol.getName();
573 StringTable += '\x00';
574 }
575
576 MachSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +0000577 MSD.SymbolData = &SD;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000578 MSD.StringIndex = Entry;
579
580 if (Symbol.isAbsolute()) {
581 MSD.SectionIndex = 0;
582 LocalSymbolData.push_back(MSD);
583 } else {
584 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
585 assert(MSD.SectionIndex && "Invalid section index!");
586 LocalSymbolData.push_back(MSD);
587 }
588 }
589
590 // External and undefined symbols are required to be in lexicographic order.
591 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
592 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
593
594 // Set the symbol indices.
595 Index = 0;
596 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
597 LocalSymbolData[i].SymbolData->setIndex(Index++);
598 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
599 ExternalSymbolData[i].SymbolData->setIndex(Index++);
600 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
601 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
602
603 // The string table is padded to a multiple of 4.
604 while (StringTable.size() % 4)
605 StringTable += '\x00';
606}
607
608void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
609 const MCAsmLayout &Layout) {
610 uint64_t StartAddress = 0;
611 const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
612 for (int i = 0, n = Order.size(); i != n ; ++i) {
613 const MCSectionData *SD = Order[i];
614 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
615 SectionAddress[SD] = StartAddress;
616 StartAddress += Layout.getSectionAddressSize(SD);
617
618 // Explicitly pad the section to match the alignment requirements of the
619 // following one. This is for 'gas' compatibility, it shouldn't
620 /// strictly be necessary.
621 StartAddress += getPaddingSize(SD, Layout);
622 }
623}
624
Jim Grosbachd96ef192012-09-13 23:11:25 +0000625void MachObjectWriter::markAbsoluteVariableSymbols(MCAssembler &Asm,
626 const MCAsmLayout &Layout) {
David Blaikie583a31c2014-04-18 18:24:25 +0000627 for (MCSymbolData &SD : Asm.symbols()) {
Jim Grosbachd96ef192012-09-13 23:11:25 +0000628 if (!SD.getSymbol().isVariable())
629 continue;
630
631 // Is the variable is a symbol difference (SA - SB + C) expression,
632 // and neither symbol is external, mark the variable as absolute.
633 const MCExpr *Expr = SD.getSymbol().getVariableValue();
634 MCValue Value;
Rafael Espindola3d5d4642014-03-12 16:55:59 +0000635 if (Expr->EvaluateAsRelocatable(Value, &Layout)) {
Jim Grosbachd96ef192012-09-13 23:11:25 +0000636 if (Value.getSymA() && Value.getSymB())
637 const_cast<MCSymbol*>(&SD.getSymbol())->setAbsolute();
638 }
639 }
640}
641
Bill Wendling21162212011-06-23 00:09:43 +0000642void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
643 const MCAsmLayout &Layout) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000644 computeSectionAddresses(Asm, Layout);
645
646 // Create symbol data for any indirect symbols.
647 BindIndirectSymbols(Asm);
648
Jim Grosbachd96ef192012-09-13 23:11:25 +0000649 // Mark symbol difference expressions in variables (from .set or = directives)
650 // as absolute.
651 markAbsoluteVariableSymbols(Asm, Layout);
652
Bill Wendlingeb872e02011-06-22 21:07:27 +0000653 // Compute symbol table information and bind symbol indices.
654 ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
655 UndefinedSymbolData);
656}
657
Bill Wendling21162212011-06-23 00:09:43 +0000658bool MachObjectWriter::
659IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
660 const MCSymbolData &DataA,
661 const MCFragment &FB,
662 bool InSet,
663 bool IsPCRel) const {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000664 if (InSet)
665 return true;
666
667 // The effective address is
668 // addr(atom(A)) + offset(A)
669 // - addr(atom(B)) - offset(B)
670 // and the offsets are not relocatable, so the fixup is fully resolved when
671 // addr(atom(A)) - addr(atom(B)) == 0.
Craig Topperbb694de2014-04-13 04:57:38 +0000672 const MCSymbolData *A_Base = nullptr, *B_Base = nullptr;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000673
674 const MCSymbol &SA = DataA.getSymbol().AliasedSymbol();
675 const MCSection &SecA = SA.getSection();
676 const MCSection &SecB = FB.getParent()->getSection();
677
678 if (IsPCRel) {
679 // The simple (Darwin, except on x86_64) way of dealing with this was to
680 // assume that any reference to a temporary symbol *must* be a temporary
681 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
682 // relocation to a temporary symbol (in the same section) is fully
683 // resolved. This also works in conjunction with absolutized .set, which
684 // requires the compiler to use .set to absolutize the differences between
685 // symbols which the compiler knows to be assembly time constants, so we
686 // don't need to worry about considering symbol differences fully resolved.
Jim Grosbachd6ae4ba2011-12-07 19:46:59 +0000687 //
688 // If the file isn't using sub-sections-via-symbols, we can make the
689 // same assumptions about any symbol that we normally make about
690 // assembler locals.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000691
Rafael Espindolaa063bdd2014-03-11 21:22:57 +0000692 bool hasReliableSymbolDifference = isX86_64();
693 if (!hasReliableSymbolDifference) {
Jim Grosbach40455072012-01-17 22:14:39 +0000694 if (!SA.isInSection() || &SecA != &SecB ||
Jim Grosbachd4dbd092012-01-18 21:54:12 +0000695 (!SA.isTemporary() &&
Jim Grosbach35bc8f92012-01-24 21:45:25 +0000696 FB.getAtom() != Asm.getSymbolData(SA).getFragment()->getAtom() &&
697 Asm.getSubsectionsViaSymbols()))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000698 return false;
699 return true;
700 }
Kevin Enderby7b46bb82011-09-08 20:53:44 +0000701 // For Darwin x86_64, there is one special case when the reference IsPCRel.
702 // If the fragment with the reference does not have a base symbol but meets
703 // the simple way of dealing with this, in that it is a temporary symbol in
704 // the same atom then it is assumed to be fully resolved. This is needed so
Eric Christopher460be992011-09-08 22:17:40 +0000705 // a relocation entry is not created and so the static linker does not
Kevin Enderby7b46bb82011-09-08 20:53:44 +0000706 // mess up the reference later.
707 else if(!FB.getAtom() &&
708 SA.isTemporary() && SA.isInSection() && &SecA == &SecB){
709 return true;
710 }
Bill Wendlingeb872e02011-06-22 21:07:27 +0000711 } else {
712 if (!TargetObjectWriter->useAggressiveSymbolFolding())
713 return false;
714 }
715
Benjamin Kramer91ea5112011-08-12 01:51:29 +0000716 const MCFragment *FA = Asm.getSymbolData(SA).getFragment();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000717
Benjamin Kramer91ea5112011-08-12 01:51:29 +0000718 // Bail if the symbol has no fragment.
719 if (!FA)
720 return false;
721
722 A_Base = FA->getAtom();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000723 if (!A_Base)
724 return false;
725
726 B_Base = FB.getAtom();
727 if (!B_Base)
728 return false;
729
730 // If the atoms are the same, they are guaranteed to have the same address.
731 if (A_Base == B_Base)
732 return true;
733
734 // Otherwise, we can't prove this is fully resolved.
735 return false;
736}
737
Eric Christopher460be992011-09-08 22:17:40 +0000738void MachObjectWriter::WriteObject(MCAssembler &Asm,
Jim Grosbach46be3012011-12-06 00:13:09 +0000739 const MCAsmLayout &Layout) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000740 unsigned NumSections = Asm.size();
Jim Grosbach448334a2014-03-18 22:09:05 +0000741 const MCAssembler::VersionMinInfoType &VersionInfo =
742 Layout.getAssembler().getVersionMinInfo();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000743
744 // The section data starts after the header, the segment load command (and
745 // section headers) and the symbol table.
746 unsigned NumLoadCommands = 1;
747 uint64_t LoadCommandsSize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +0000748 sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64):
749 sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000750
Jim Grosbach448334a2014-03-18 22:09:05 +0000751 // Add the deployment target version info load command size, if used.
752 if (VersionInfo.Major != 0) {
753 ++NumLoadCommands;
754 LoadCommandsSize += sizeof(MachO::version_min_command);
755 }
756
Daniel Dunbareec0f322013-01-18 01:26:07 +0000757 // Add the data-in-code load command size, if used.
758 unsigned NumDataRegions = Asm.getDataRegions().size();
759 if (NumDataRegions) {
760 ++NumLoadCommands;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000761 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000762 }
763
Tim Northover53d32512014-03-29 07:34:53 +0000764 // Add the loh load command size, if used.
765 uint64_t LOHRawSize = Asm.getLOHContainer().getEmitSize(*this, Layout);
766 uint64_t LOHSize = RoundUpToAlignment(LOHRawSize, is64Bit() ? 8 : 4);
767 if (LOHSize) {
768 ++NumLoadCommands;
769 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
770 }
771
Bill Wendlingeb872e02011-06-22 21:07:27 +0000772 // Add the symbol table load command sizes, if used.
773 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
774 UndefinedSymbolData.size();
775 if (NumSymbols) {
776 NumLoadCommands += 2;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000777 LoadCommandsSize += (sizeof(MachO::symtab_command) +
778 sizeof(MachO::dysymtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000779 }
780
Daniel Dunbareec0f322013-01-18 01:26:07 +0000781 // Add the linker option load commands sizes.
782 const std::vector<std::vector<std::string> > &LinkerOptions =
783 Asm.getLinkerOptions();
784 for (unsigned i = 0, e = LinkerOptions.size(); i != e; ++i) {
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000785 ++NumLoadCommands;
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000786 LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(LinkerOptions[i],
787 is64Bit());
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000788 }
Daniel Dunbareec0f322013-01-18 01:26:07 +0000789
Bill Wendlingeb872e02011-06-22 21:07:27 +0000790 // Compute the total size of the section data, as well as its file size and vm
791 // size.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000792 uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) :
793 sizeof(MachO::mach_header)) + LoadCommandsSize;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000794 uint64_t SectionDataSize = 0;
795 uint64_t SectionDataFileSize = 0;
796 uint64_t VMSize = 0;
797 for (MCAssembler::const_iterator it = Asm.begin(),
798 ie = Asm.end(); it != ie; ++it) {
799 const MCSectionData &SD = *it;
800 uint64_t Address = getSectionAddress(&SD);
801 uint64_t Size = Layout.getSectionAddressSize(&SD);
802 uint64_t FileSize = Layout.getSectionFileSize(&SD);
803 FileSize += getPaddingSize(&SD, Layout);
804
805 VMSize = std::max(VMSize, Address + Size);
806
807 if (SD.getSection().isVirtualSection())
808 continue;
809
810 SectionDataSize = std::max(SectionDataSize, Address + Size);
811 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
812 }
813
814 // The section data is padded to 4 bytes.
815 //
816 // FIXME: Is this machine dependent?
817 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
818 SectionDataFileSize += SectionDataPadding;
819
820 // Write the prolog, starting with the header and load command...
821 WriteHeader(NumLoadCommands, LoadCommandsSize,
822 Asm.getSubsectionsViaSymbols());
823 WriteSegmentLoadCommand(NumSections, VMSize,
824 SectionDataStart, SectionDataSize);
825
826 // ... and then the section headers.
827 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
828 for (MCAssembler::const_iterator it = Asm.begin(),
829 ie = Asm.end(); it != ie; ++it) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000830 std::vector<MachO::any_relocation_info> &Relocs = Relocations[it];
Bill Wendlingeb872e02011-06-22 21:07:27 +0000831 unsigned NumRelocs = Relocs.size();
832 uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
833 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000834 RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000835 }
836
Jim Grosbach448334a2014-03-18 22:09:05 +0000837 // Write out the deployment target information, if it's available.
838 if (VersionInfo.Major != 0) {
839 assert(VersionInfo.Update < 256 && "unencodable update target version");
840 assert(VersionInfo.Minor < 256 && "unencodable minor target version");
841 assert(VersionInfo.Major < 65536 && "unencodable major target version");
842 uint32_t EncodedVersion = VersionInfo.Update | (VersionInfo.Minor << 8) |
843 (VersionInfo.Major << 16);
844 Write32(VersionInfo.Kind == MCVM_OSXVersionMin ? MachO::LC_VERSION_MIN_MACOSX :
845 MachO::LC_VERSION_MIN_IPHONEOS);
846 Write32(sizeof(MachO::version_min_command));
847 Write32(EncodedVersion);
848 Write32(0); // reserved.
849 }
850
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000851 // Write the data-in-code load command, if used.
852 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
853 if (NumDataRegions) {
854 uint64_t DataRegionsOffset = RelocTableEnd;
855 uint64_t DataRegionsSize = NumDataRegions * 8;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000856 WriteLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset,
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000857 DataRegionsSize);
858 }
859
Tim Northover53d32512014-03-29 07:34:53 +0000860 // Write the loh load command, if used.
861 uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize;
862 if (LOHSize)
863 WriteLinkeditLoadCommand(MachO::LC_LINKER_OPTIMIZATION_HINT,
864 DataInCodeTableEnd, LOHSize);
865
Bill Wendlingeb872e02011-06-22 21:07:27 +0000866 // Write the symbol table load command, if used.
867 if (NumSymbols) {
868 unsigned FirstLocalSymbol = 0;
869 unsigned NumLocalSymbols = LocalSymbolData.size();
870 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
871 unsigned NumExternalSymbols = ExternalSymbolData.size();
872 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
873 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
874 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
875 unsigned NumSymTabSymbols =
876 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
877 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
878 uint64_t IndirectSymbolOffset = 0;
879
880 // If used, the indirect symbols are written after the section data.
881 if (NumIndirectSymbols)
Tim Northover53d32512014-03-29 07:34:53 +0000882 IndirectSymbolOffset = LOHTableEnd;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000883
884 // The symbol table is written after the indirect symbol data.
Tim Northover53d32512014-03-29 07:34:53 +0000885 uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000886
887 // The string table is written after symbol table.
888 uint64_t StringTableOffset =
Charles Davis8bdfafd2013-09-01 04:28:48 +0000889 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ?
890 sizeof(MachO::nlist_64) :
891 sizeof(MachO::nlist));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000892 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
893 StringTableOffset, StringTable.size());
894
895 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
896 FirstExternalSymbol, NumExternalSymbols,
897 FirstUndefinedSymbol, NumUndefinedSymbols,
898 IndirectSymbolOffset, NumIndirectSymbols);
899 }
900
Daniel Dunbareec0f322013-01-18 01:26:07 +0000901 // Write the linker options load commands.
902 for (unsigned i = 0, e = LinkerOptions.size(); i != e; ++i) {
903 WriteLinkerOptionsLoadCommand(LinkerOptions[i]);
904 }
905
Bill Wendlingeb872e02011-06-22 21:07:27 +0000906 // Write the actual section data.
907 for (MCAssembler::const_iterator it = Asm.begin(),
908 ie = Asm.end(); it != ie; ++it) {
Jim Grosbach18e2fe42011-12-06 00:03:48 +0000909 Asm.writeSectionData(it, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000910
911 uint64_t Pad = getPaddingSize(it, Layout);
912 for (unsigned int i = 0; i < Pad; ++i)
913 Write8(0);
914 }
915
916 // Write the extra padding.
917 WriteZeros(SectionDataPadding);
918
919 // Write the relocation entries.
920 for (MCAssembler::const_iterator it = Asm.begin(),
921 ie = Asm.end(); it != ie; ++it) {
922 // Write the section relocation entries, in reverse order to match 'as'
923 // (approximately, the exact algorithm is more complicated than this).
Charles Davis8bdfafd2013-09-01 04:28:48 +0000924 std::vector<MachO::any_relocation_info> &Relocs = Relocations[it];
Bill Wendlingeb872e02011-06-22 21:07:27 +0000925 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000926 Write32(Relocs[e - i - 1].r_word0);
927 Write32(Relocs[e - i - 1].r_word1);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000928 }
929 }
930
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000931 // Write out the data-in-code region payload, if there is one.
932 for (MCAssembler::const_data_region_iterator
933 it = Asm.data_region_begin(), ie = Asm.data_region_end();
934 it != ie; ++it) {
935 const DataRegionData *Data = &(*it);
Jim Grosbachb12b71a2012-09-18 23:05:12 +0000936 uint64_t Start =
937 getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->Start),
938 Layout);
939 uint64_t End =
940 getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->End),
941 Layout);
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000942 DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
943 << " start: " << Start << "(" << Data->Start->getName() << ")"
944 << " end: " << End << "(" << Data->End->getName() << ")"
945 << " size: " << End - Start
946 << "\n");
947 Write32(Start);
948 Write16(End - Start);
949 Write16(Data->Kind);
950 }
951
Tim Northover53d32512014-03-29 07:34:53 +0000952 // Write out the loh commands, if there is one.
953 if (LOHSize) {
954#ifndef NDEBUG
955 unsigned Start = OS.tell();
956#endif
957 Asm.getLOHContainer().Emit(*this, Layout);
958 // Pad to a multiple of the pointer size.
959 WriteBytes("", OffsetToAlignment(LOHRawSize, is64Bit() ? 8 : 4));
960 assert(OS.tell() - Start == LOHSize);
961 }
962
Bill Wendlingeb872e02011-06-22 21:07:27 +0000963 // Write the symbol table data, if used.
964 if (NumSymbols) {
965 // Write the indirect symbol entries.
966 for (MCAssembler::const_indirect_symbol_iterator
967 it = Asm.indirect_symbol_begin(),
968 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
Alp Tokerf907b892013-12-05 05:44:44 +0000969 // Indirect symbols in the non-lazy symbol pointer section have some
Bill Wendlingeb872e02011-06-22 21:07:27 +0000970 // special handling.
971 const MCSectionMachO &Section =
972 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
David Majnemer7b583052014-03-07 07:36:05 +0000973 if (Section.getType() == MachO::S_NON_LAZY_SYMBOL_POINTERS) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000974 // If this symbol is defined and internal, mark it as such.
975 if (it->Symbol->isDefined() &&
976 !Asm.getSymbolData(*it->Symbol).isExternal()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000977 uint32_t Flags = MachO::INDIRECT_SYMBOL_LOCAL;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000978 if (it->Symbol->isAbsolute())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000979 Flags |= MachO::INDIRECT_SYMBOL_ABS;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000980 Write32(Flags);
981 continue;
982 }
983 }
984
985 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
986 }
987
988 // FIXME: Check that offsets match computed ones.
989
990 // Write the symbol table entries.
991 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
992 WriteNlist(LocalSymbolData[i], Layout);
993 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
994 WriteNlist(ExternalSymbolData[i], Layout);
995 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
996 WriteNlist(UndefinedSymbolData[i], Layout);
997
998 // Write the string table.
999 OS << StringTable.str();
1000 }
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +00001001}
1002
Daniel Dunbar8888a962010-12-16 16:09:19 +00001003MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
Daniel Dunbar03fcccb2010-12-16 17:21:02 +00001004 raw_ostream &OS,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001005 bool IsLittleEndian) {
Daniel Dunbar03fcccb2010-12-16 17:21:02 +00001006 return new MachObjectWriter(MOTW, OS, IsLittleEndian);
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +00001007}