blob: 588d424120c44cb596877696a3e8201456e7f1f8 [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.
Benjamin Kramer3e67db92014-10-11 15:07:21 +000044 if (SD->getSymbol().isUndefined())
Daniel Dunbar7de31062010-05-10 23:15:13 +000045 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;
Joerg Sonnenberger752b91b2014-08-10 11:35:12 +000087 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, &Layout, nullptr))
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
Tim Northovereaef0742014-05-30 13:22:59 +0000306MachObjectWriter::MachSymbolData *
307MachObjectWriter::findSymbolData(const MCSymbol &Sym) {
308 for (auto &Entry : LocalSymbolData)
309 if (&Entry.SymbolData->getSymbol() == &Sym)
310 return &Entry;
311
312 for (auto &Entry : ExternalSymbolData)
313 if (&Entry.SymbolData->getSymbol() == &Sym)
314 return &Entry;
315
316 for (auto &Entry : UndefinedSymbolData)
317 if (&Entry.SymbolData->getSymbol() == &Sym)
318 return &Entry;
319
320 return nullptr;
321}
322
Bill Wendling21162212011-06-23 00:09:43 +0000323void MachObjectWriter::WriteNlist(MachSymbolData &MSD,
324 const MCAsmLayout &Layout) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000325 MCSymbolData &Data = *MSD.SymbolData;
Tim Northovereaef0742014-05-30 13:22:59 +0000326 const MCSymbol *Symbol = &Data.getSymbol();
327 const MCSymbol *AliasedSymbol = &Symbol->AliasedSymbol();
328 uint8_t SectionIndex = MSD.SectionIndex;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000329 uint8_t Type = 0;
330 uint16_t Flags = Data.getFlags();
Jim Grosbacha3171602011-08-09 22:12:37 +0000331 uint64_t Address = 0;
Tim Northovereaef0742014-05-30 13:22:59 +0000332 bool IsAlias = Symbol != AliasedSymbol;
333
334 MachSymbolData *AliaseeInfo;
335 if (IsAlias) {
336 AliaseeInfo = findSymbolData(*AliasedSymbol);
337 if (AliaseeInfo)
338 SectionIndex = AliaseeInfo->SectionIndex;
339 Symbol = AliasedSymbol;
340 }
Bill Wendlingeb872e02011-06-22 21:07:27 +0000341
342 // Set the N_TYPE bits. See <mach-o/nlist.h>.
343 //
344 // FIXME: Are the prebound or indirect fields possible here?
Tim Northovereaef0742014-05-30 13:22:59 +0000345 if (IsAlias && Symbol->isUndefined())
346 Type = MachO::N_INDR;
347 else if (Symbol->isUndefined())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000348 Type = MachO::N_UNDF;
Tim Northovereaef0742014-05-30 13:22:59 +0000349 else if (Symbol->isAbsolute())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000350 Type = MachO::N_ABS;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000351 else
Charles Davis8bdfafd2013-09-01 04:28:48 +0000352 Type = MachO::N_SECT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000353
354 // FIXME: Set STAB bits.
355
356 if (Data.isPrivateExtern())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000357 Type |= MachO::N_PEXT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000358
359 // Set external bit.
Tim Northovereaef0742014-05-30 13:22:59 +0000360 if (Data.isExternal() || (!IsAlias && Symbol->isUndefined()))
Charles Davis8bdfafd2013-09-01 04:28:48 +0000361 Type |= MachO::N_EXT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000362
363 // Compute the symbol address.
Tim Northovereaef0742014-05-30 13:22:59 +0000364 if (IsAlias && Symbol->isUndefined())
365 Address = AliaseeInfo->StringIndex;
366 else if (Symbol->isDefined())
Jim Grosbachd96ef192012-09-13 23:11:25 +0000367 Address = getSymbolAddress(&Data, Layout);
Tim Northovereaef0742014-05-30 13:22:59 +0000368 else if (Data.isCommon()) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000369 // Common symbols are encoded with the size in the address
370 // field, and their alignment in the flags.
371 Address = Data.getCommonSize();
372
373 // Common alignment is packed into the 'desc' bits.
374 if (unsigned Align = Data.getCommonAlignment()) {
375 unsigned Log2Size = Log2_32(Align);
376 assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
377 if (Log2Size > 15)
378 report_fatal_error("invalid 'common' alignment '" +
Tim Northovereaef0742014-05-30 13:22:59 +0000379 Twine(Align) + "' for '" + Symbol->getName() + "'",
Jim Grosbachaff6a0c2013-09-24 23:56:31 +0000380 false);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000381 // FIXME: Keep this mask with the SymbolFlags enumeration.
382 Flags = (Flags & 0xF0FF) | (Log2Size << 8);
383 }
384 }
385
Tim Northovereaef0742014-05-30 13:22:59 +0000386 if (Layout.getAssembler().isThumbFunc(Symbol))
Rafael Espindolab60c8292014-04-29 12:46:50 +0000387 Flags |= SF_ThumbFunc;
388
Bill Wendlingeb872e02011-06-22 21:07:27 +0000389 // struct nlist (12 bytes)
390
391 Write32(MSD.StringIndex);
392 Write8(Type);
Tim Northovereaef0742014-05-30 13:22:59 +0000393 Write8(SectionIndex);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000394
395 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
396 // value.
397 Write16(Flags);
398 if (is64Bit())
399 Write64(Address);
400 else
401 Write32(Address);
402}
403
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000404void MachObjectWriter::WriteLinkeditLoadCommand(uint32_t Type,
405 uint32_t DataOffset,
406 uint32_t DataSize) {
407 uint64_t Start = OS.tell();
408 (void) Start;
409
410 Write32(Type);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000411 Write32(sizeof(MachO::linkedit_data_command));
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000412 Write32(DataOffset);
413 Write32(DataSize);
414
Charles Davis8bdfafd2013-09-01 04:28:48 +0000415 assert(OS.tell() - Start == sizeof(MachO::linkedit_data_command));
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000416}
417
Daniel Dunbareec0f322013-01-18 01:26:07 +0000418static unsigned ComputeLinkerOptionsLoadCommandSize(
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000419 const std::vector<std::string> &Options, bool is64Bit)
Daniel Dunbareec0f322013-01-18 01:26:07 +0000420{
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +0000421 unsigned Size = sizeof(MachO::linker_option_command);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000422 for (unsigned i = 0, e = Options.size(); i != e; ++i)
423 Size += Options[i].size() + 1;
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000424 return RoundUpToAlignment(Size, is64Bit ? 8 : 4);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000425}
426
427void MachObjectWriter::WriteLinkerOptionsLoadCommand(
428 const std::vector<std::string> &Options)
429{
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000430 unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit());
Daniel Dunbareec0f322013-01-18 01:26:07 +0000431 uint64_t Start = OS.tell();
432 (void) Start;
433
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +0000434 Write32(MachO::LC_LINKER_OPTION);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000435 Write32(Size);
436 Write32(Options.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +0000437 uint64_t BytesWritten = sizeof(MachO::linker_option_command);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000438 for (unsigned i = 0, e = Options.size(); i != e; ++i) {
439 // Write each string, including the null byte.
440 const std::string &Option = Options[i];
441 WriteBytes(Option.c_str(), Option.size() + 1);
442 BytesWritten += Option.size() + 1;
443 }
444
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000445 // Pad to a multiple of the pointer size.
446 WriteBytes("", OffsetToAlignment(BytesWritten, is64Bit() ? 8 : 4));
Daniel Dunbareec0f322013-01-18 01:26:07 +0000447
448 assert(OS.tell() - Start == Size);
449}
450
Rafael Espindola26585542015-01-19 21:11:14 +0000451void MachObjectWriter::RecordRelocation(MCAssembler &Asm,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000452 const MCAsmLayout &Layout,
453 const MCFragment *Fragment,
Rafael Espindola26585542015-01-19 21:11:14 +0000454 const MCFixup &Fixup, MCValue Target,
455 bool &IsPCRel, uint64_t &FixedValue) {
Jim Grosbach28fcafb2011-06-24 23:44:37 +0000456 TargetObjectWriter->RecordRelocation(this, Asm, Layout, Fragment, Fixup,
457 Target, FixedValue);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000458}
459
460void MachObjectWriter::BindIndirectSymbols(MCAssembler &Asm) {
461 // This is the point where 'as' creates actual symbols for indirect symbols
462 // (in the following two passes). It would be easier for us to do this sooner
463 // when we see the attribute, but that makes getting the order in the symbol
464 // table much more complicated than it is worth.
465 //
466 // FIXME: Revisit this when the dust settles.
467
Kevin Enderby3aeada22013-08-28 17:50:59 +0000468 // Report errors for use of .indirect_symbol not in a symbol pointer section
469 // or stub section.
470 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
471 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
472 const MCSectionMachO &Section =
473 cast<MCSectionMachO>(it->SectionData->getSection());
474
David Majnemer7b583052014-03-07 07:36:05 +0000475 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
476 Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
477 Section.getType() != MachO::S_SYMBOL_STUBS) {
Kevin Enderby3aeada22013-08-28 17:50:59 +0000478 MCSymbol &Symbol = *it->Symbol;
479 report_fatal_error("indirect symbol '" + Symbol.getName() +
480 "' not in a symbol pointer or stub section");
481 }
482 }
483
Alp Tokerf907b892013-12-05 05:44:44 +0000484 // Bind non-lazy symbol pointers first.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000485 unsigned IndirectIndex = 0;
486 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
487 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
488 const MCSectionMachO &Section =
489 cast<MCSectionMachO>(it->SectionData->getSection());
490
David Majnemer7b583052014-03-07 07:36:05 +0000491 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS)
Bill Wendlingeb872e02011-06-22 21:07:27 +0000492 continue;
493
494 // Initialize the section indirect symbol base, if necessary.
Benjamin Kramerf29db272012-08-22 15:37:57 +0000495 IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000496
497 Asm.getOrCreateSymbolData(*it->Symbol);
498 }
499
500 // Then lazy symbol pointers and symbol stubs.
501 IndirectIndex = 0;
502 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
503 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
504 const MCSectionMachO &Section =
505 cast<MCSectionMachO>(it->SectionData->getSection());
506
David Majnemer7b583052014-03-07 07:36:05 +0000507 if (Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
508 Section.getType() != MachO::S_SYMBOL_STUBS)
Bill Wendlingeb872e02011-06-22 21:07:27 +0000509 continue;
510
511 // Initialize the section indirect symbol base, if necessary.
Benjamin Kramerf29db272012-08-22 15:37:57 +0000512 IndirectSymBase.insert(std::make_pair(it->SectionData, IndirectIndex));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000513
514 // Set the symbol type to undefined lazy, but only on construction.
515 //
516 // FIXME: Do not hardcode.
517 bool Created;
518 MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
519 if (Created)
520 Entry.setFlags(Entry.getFlags() | 0x0001);
521 }
522}
523
524/// ComputeSymbolTable - Compute the symbol table data
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000525void MachObjectWriter::ComputeSymbolTable(
526 MCAssembler &Asm, std::vector<MachSymbolData> &LocalSymbolData,
527 std::vector<MachSymbolData> &ExternalSymbolData,
528 std::vector<MachSymbolData> &UndefinedSymbolData) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000529 // Build section lookup table.
530 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
531 unsigned Index = 1;
532 for (MCAssembler::iterator it = Asm.begin(),
533 ie = Asm.end(); it != ie; ++it, ++Index)
534 SectionIndexMap[&it->getSection()] = Index;
535 assert(Index <= 256 && "Too many sections!");
536
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000537 // Build the string table.
538 for (MCSymbolData &SD : Asm.symbols()) {
539 const MCSymbol &Symbol = SD.getSymbol();
540 if (!Asm.isSymbolLinkerVisible(Symbol))
541 continue;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000542
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000543 StringTable.add(Symbol.getName());
544 }
545 StringTable.finalize(StringTableBuilder::MachO);
546
547 // Build the symbol arrays but only for non-local symbols.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000548 //
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000549 // The particular order that we collect and then sort the symbols is chosen to
550 // match 'as'. Even though it doesn't matter for correctness, this is
551 // important for letting us diff .o files.
David Blaikie583a31c2014-04-18 18:24:25 +0000552 for (MCSymbolData &SD : Asm.symbols()) {
553 const MCSymbol &Symbol = SD.getSymbol();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000554
555 // Ignore non-linker visible symbols.
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000556 if (!Asm.isSymbolLinkerVisible(Symbol))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000557 continue;
558
David Blaikie583a31c2014-04-18 18:24:25 +0000559 if (!SD.isExternal() && !Symbol.isUndefined())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000560 continue;
561
Bill Wendlingeb872e02011-06-22 21:07:27 +0000562 MachSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +0000563 MSD.SymbolData = &SD;
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000564 MSD.StringIndex = StringTable.getOffset(Symbol.getName());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000565
566 if (Symbol.isUndefined()) {
567 MSD.SectionIndex = 0;
568 UndefinedSymbolData.push_back(MSD);
569 } else if (Symbol.isAbsolute()) {
570 MSD.SectionIndex = 0;
571 ExternalSymbolData.push_back(MSD);
572 } else {
573 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
574 assert(MSD.SectionIndex && "Invalid section index!");
575 ExternalSymbolData.push_back(MSD);
576 }
577 }
578
579 // Now add the data for local symbols.
David Blaikie583a31c2014-04-18 18:24:25 +0000580 for (MCSymbolData &SD : Asm.symbols()) {
581 const MCSymbol &Symbol = SD.getSymbol();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000582
583 // Ignore non-linker visible symbols.
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000584 if (!Asm.isSymbolLinkerVisible(Symbol))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000585 continue;
586
David Blaikie583a31c2014-04-18 18:24:25 +0000587 if (SD.isExternal() || Symbol.isUndefined())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000588 continue;
589
Bill Wendlingeb872e02011-06-22 21:07:27 +0000590 MachSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +0000591 MSD.SymbolData = &SD;
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000592 MSD.StringIndex = StringTable.getOffset(Symbol.getName());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000593
594 if (Symbol.isAbsolute()) {
595 MSD.SectionIndex = 0;
596 LocalSymbolData.push_back(MSD);
597 } else {
598 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
599 assert(MSD.SectionIndex && "Invalid section index!");
600 LocalSymbolData.push_back(MSD);
601 }
602 }
603
604 // External and undefined symbols are required to be in lexicographic order.
605 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
606 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
607
608 // Set the symbol indices.
609 Index = 0;
610 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
611 LocalSymbolData[i].SymbolData->setIndex(Index++);
612 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
613 ExternalSymbolData[i].SymbolData->setIndex(Index++);
614 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
615 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola26585542015-01-19 21:11:14 +0000616
617 for (const MCSectionData &SD : Asm) {
618 std::vector<RelAndSymbol> &Relocs = Relocations[&SD];
619 for (RelAndSymbol &Rel : Relocs) {
620 if (!Rel.Sym)
621 continue;
622
623 // Set the Index and the IsExtern bit.
624 unsigned Index = Rel.Sym->getIndex();
625 assert(isInt<24>(Index));
626 if (IsLittleEndian)
627 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & (-1 << 24)) | Index | (1 << 27);
628 else
629 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & 0xff) | Index << 8 | (1 << 4);
630 }
631 }
Bill Wendlingeb872e02011-06-22 21:07:27 +0000632}
633
634void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
635 const MCAsmLayout &Layout) {
636 uint64_t StartAddress = 0;
637 const SmallVectorImpl<MCSectionData*> &Order = Layout.getSectionOrder();
638 for (int i = 0, n = Order.size(); i != n ; ++i) {
639 const MCSectionData *SD = Order[i];
640 StartAddress = RoundUpToAlignment(StartAddress, SD->getAlignment());
641 SectionAddress[SD] = StartAddress;
642 StartAddress += Layout.getSectionAddressSize(SD);
643
644 // Explicitly pad the section to match the alignment requirements of the
645 // following one. This is for 'gas' compatibility, it shouldn't
646 /// strictly be necessary.
647 StartAddress += getPaddingSize(SD, Layout);
648 }
649}
650
Jim Grosbachd96ef192012-09-13 23:11:25 +0000651void MachObjectWriter::markAbsoluteVariableSymbols(MCAssembler &Asm,
652 const MCAsmLayout &Layout) {
David Blaikie583a31c2014-04-18 18:24:25 +0000653 for (MCSymbolData &SD : Asm.symbols()) {
Jim Grosbachd96ef192012-09-13 23:11:25 +0000654 if (!SD.getSymbol().isVariable())
655 continue;
656
657 // Is the variable is a symbol difference (SA - SB + C) expression,
658 // and neither symbol is external, mark the variable as absolute.
659 const MCExpr *Expr = SD.getSymbol().getVariableValue();
660 MCValue Value;
Joerg Sonnenberger752b91b2014-08-10 11:35:12 +0000661 if (Expr->EvaluateAsRelocatable(Value, &Layout, nullptr)) {
Jim Grosbachd96ef192012-09-13 23:11:25 +0000662 if (Value.getSymA() && Value.getSymB())
663 const_cast<MCSymbol*>(&SD.getSymbol())->setAbsolute();
664 }
665 }
666}
667
Bill Wendling21162212011-06-23 00:09:43 +0000668void MachObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
669 const MCAsmLayout &Layout) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000670 computeSectionAddresses(Asm, Layout);
671
672 // Create symbol data for any indirect symbols.
673 BindIndirectSymbols(Asm);
674
Jim Grosbachd96ef192012-09-13 23:11:25 +0000675 // Mark symbol difference expressions in variables (from .set or = directives)
676 // as absolute.
677 markAbsoluteVariableSymbols(Asm, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000678}
679
Bill Wendling21162212011-06-23 00:09:43 +0000680bool MachObjectWriter::
681IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
682 const MCSymbolData &DataA,
683 const MCFragment &FB,
684 bool InSet,
685 bool IsPCRel) const {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000686 if (InSet)
687 return true;
688
689 // The effective address is
690 // addr(atom(A)) + offset(A)
691 // - addr(atom(B)) - offset(B)
692 // and the offsets are not relocatable, so the fixup is fully resolved when
693 // addr(atom(A)) - addr(atom(B)) == 0.
Craig Topperbb694de2014-04-13 04:57:38 +0000694 const MCSymbolData *A_Base = nullptr, *B_Base = nullptr;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000695
696 const MCSymbol &SA = DataA.getSymbol().AliasedSymbol();
697 const MCSection &SecA = SA.getSection();
698 const MCSection &SecB = FB.getParent()->getSection();
699
700 if (IsPCRel) {
701 // The simple (Darwin, except on x86_64) way of dealing with this was to
702 // assume that any reference to a temporary symbol *must* be a temporary
703 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
704 // relocation to a temporary symbol (in the same section) is fully
705 // resolved. This also works in conjunction with absolutized .set, which
706 // requires the compiler to use .set to absolutize the differences between
707 // symbols which the compiler knows to be assembly time constants, so we
708 // don't need to worry about considering symbol differences fully resolved.
Jim Grosbachd6ae4ba2011-12-07 19:46:59 +0000709 //
710 // If the file isn't using sub-sections-via-symbols, we can make the
711 // same assumptions about any symbol that we normally make about
712 // assembler locals.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000713
Rafael Espindolaa063bdd2014-03-11 21:22:57 +0000714 bool hasReliableSymbolDifference = isX86_64();
715 if (!hasReliableSymbolDifference) {
Jim Grosbach40455072012-01-17 22:14:39 +0000716 if (!SA.isInSection() || &SecA != &SecB ||
Jim Grosbachd4dbd092012-01-18 21:54:12 +0000717 (!SA.isTemporary() &&
Jim Grosbach35bc8f92012-01-24 21:45:25 +0000718 FB.getAtom() != Asm.getSymbolData(SA).getFragment()->getAtom() &&
719 Asm.getSubsectionsViaSymbols()))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000720 return false;
721 return true;
722 }
Kevin Enderby7b46bb82011-09-08 20:53:44 +0000723 // For Darwin x86_64, there is one special case when the reference IsPCRel.
724 // If the fragment with the reference does not have a base symbol but meets
725 // the simple way of dealing with this, in that it is a temporary symbol in
726 // the same atom then it is assumed to be fully resolved. This is needed so
Eric Christopher460be992011-09-08 22:17:40 +0000727 // a relocation entry is not created and so the static linker does not
Kevin Enderby7b46bb82011-09-08 20:53:44 +0000728 // mess up the reference later.
729 else if(!FB.getAtom() &&
730 SA.isTemporary() && SA.isInSection() && &SecA == &SecB){
731 return true;
732 }
Bill Wendlingeb872e02011-06-22 21:07:27 +0000733 } else {
734 if (!TargetObjectWriter->useAggressiveSymbolFolding())
735 return false;
736 }
737
Rafael Espindolabfd0f012014-11-04 22:10:33 +0000738 // If they are not in the same section, we can't compute the diff.
739 if (&SecA != &SecB)
740 return false;
741
Benjamin Kramer91ea5112011-08-12 01:51:29 +0000742 const MCFragment *FA = Asm.getSymbolData(SA).getFragment();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000743
Benjamin Kramer91ea5112011-08-12 01:51:29 +0000744 // Bail if the symbol has no fragment.
745 if (!FA)
746 return false;
747
748 A_Base = FA->getAtom();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000749 B_Base = FB.getAtom();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000750
751 // If the atoms are the same, they are guaranteed to have the same address.
752 if (A_Base == B_Base)
753 return true;
754
755 // Otherwise, we can't prove this is fully resolved.
756 return false;
757}
758
Eric Christopher460be992011-09-08 22:17:40 +0000759void MachObjectWriter::WriteObject(MCAssembler &Asm,
Jim Grosbach46be3012011-12-06 00:13:09 +0000760 const MCAsmLayout &Layout) {
Rafael Espindola26585542015-01-19 21:11:14 +0000761 // Compute symbol table information and bind symbol indices.
762 ComputeSymbolTable(Asm, LocalSymbolData, ExternalSymbolData,
763 UndefinedSymbolData);
764
Bill Wendlingeb872e02011-06-22 21:07:27 +0000765 unsigned NumSections = Asm.size();
Jim Grosbach448334a2014-03-18 22:09:05 +0000766 const MCAssembler::VersionMinInfoType &VersionInfo =
767 Layout.getAssembler().getVersionMinInfo();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000768
769 // The section data starts after the header, the segment load command (and
770 // section headers) and the symbol table.
771 unsigned NumLoadCommands = 1;
772 uint64_t LoadCommandsSize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +0000773 sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64):
774 sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000775
Jim Grosbach448334a2014-03-18 22:09:05 +0000776 // Add the deployment target version info load command size, if used.
777 if (VersionInfo.Major != 0) {
778 ++NumLoadCommands;
779 LoadCommandsSize += sizeof(MachO::version_min_command);
780 }
781
Daniel Dunbareec0f322013-01-18 01:26:07 +0000782 // Add the data-in-code load command size, if used.
783 unsigned NumDataRegions = Asm.getDataRegions().size();
784 if (NumDataRegions) {
785 ++NumLoadCommands;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000786 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000787 }
788
Tim Northover53d32512014-03-29 07:34:53 +0000789 // Add the loh load command size, if used.
790 uint64_t LOHRawSize = Asm.getLOHContainer().getEmitSize(*this, Layout);
791 uint64_t LOHSize = RoundUpToAlignment(LOHRawSize, is64Bit() ? 8 : 4);
792 if (LOHSize) {
793 ++NumLoadCommands;
794 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
795 }
796
Bill Wendlingeb872e02011-06-22 21:07:27 +0000797 // Add the symbol table load command sizes, if used.
798 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
799 UndefinedSymbolData.size();
800 if (NumSymbols) {
801 NumLoadCommands += 2;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000802 LoadCommandsSize += (sizeof(MachO::symtab_command) +
803 sizeof(MachO::dysymtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000804 }
805
Daniel Dunbareec0f322013-01-18 01:26:07 +0000806 // Add the linker option load commands sizes.
807 const std::vector<std::vector<std::string> > &LinkerOptions =
808 Asm.getLinkerOptions();
809 for (unsigned i = 0, e = LinkerOptions.size(); i != e; ++i) {
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000810 ++NumLoadCommands;
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000811 LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(LinkerOptions[i],
812 is64Bit());
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000813 }
Daniel Dunbareec0f322013-01-18 01:26:07 +0000814
Bill Wendlingeb872e02011-06-22 21:07:27 +0000815 // Compute the total size of the section data, as well as its file size and vm
816 // size.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000817 uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) :
818 sizeof(MachO::mach_header)) + LoadCommandsSize;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000819 uint64_t SectionDataSize = 0;
820 uint64_t SectionDataFileSize = 0;
821 uint64_t VMSize = 0;
822 for (MCAssembler::const_iterator it = Asm.begin(),
823 ie = Asm.end(); it != ie; ++it) {
824 const MCSectionData &SD = *it;
825 uint64_t Address = getSectionAddress(&SD);
826 uint64_t Size = Layout.getSectionAddressSize(&SD);
827 uint64_t FileSize = Layout.getSectionFileSize(&SD);
828 FileSize += getPaddingSize(&SD, Layout);
829
830 VMSize = std::max(VMSize, Address + Size);
831
832 if (SD.getSection().isVirtualSection())
833 continue;
834
835 SectionDataSize = std::max(SectionDataSize, Address + Size);
836 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
837 }
838
839 // The section data is padded to 4 bytes.
840 //
841 // FIXME: Is this machine dependent?
842 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
843 SectionDataFileSize += SectionDataPadding;
844
845 // Write the prolog, starting with the header and load command...
846 WriteHeader(NumLoadCommands, LoadCommandsSize,
847 Asm.getSubsectionsViaSymbols());
848 WriteSegmentLoadCommand(NumSections, VMSize,
849 SectionDataStart, SectionDataSize);
850
851 // ... and then the section headers.
852 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
853 for (MCAssembler::const_iterator it = Asm.begin(),
854 ie = Asm.end(); it != ie; ++it) {
Rafael Espindola26585542015-01-19 21:11:14 +0000855 std::vector<RelAndSymbol> &Relocs = Relocations[it];
Bill Wendlingeb872e02011-06-22 21:07:27 +0000856 unsigned NumRelocs = Relocs.size();
857 uint64_t SectionStart = SectionDataStart + getSectionAddress(it);
858 WriteSection(Asm, Layout, *it, SectionStart, RelocTableEnd, NumRelocs);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000859 RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000860 }
861
Jim Grosbach448334a2014-03-18 22:09:05 +0000862 // Write out the deployment target information, if it's available.
863 if (VersionInfo.Major != 0) {
864 assert(VersionInfo.Update < 256 && "unencodable update target version");
865 assert(VersionInfo.Minor < 256 && "unencodable minor target version");
866 assert(VersionInfo.Major < 65536 && "unencodable major target version");
867 uint32_t EncodedVersion = VersionInfo.Update | (VersionInfo.Minor << 8) |
868 (VersionInfo.Major << 16);
869 Write32(VersionInfo.Kind == MCVM_OSXVersionMin ? MachO::LC_VERSION_MIN_MACOSX :
870 MachO::LC_VERSION_MIN_IPHONEOS);
871 Write32(sizeof(MachO::version_min_command));
872 Write32(EncodedVersion);
873 Write32(0); // reserved.
874 }
875
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000876 // Write the data-in-code load command, if used.
877 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
878 if (NumDataRegions) {
879 uint64_t DataRegionsOffset = RelocTableEnd;
880 uint64_t DataRegionsSize = NumDataRegions * 8;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000881 WriteLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset,
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000882 DataRegionsSize);
883 }
884
Tim Northover53d32512014-03-29 07:34:53 +0000885 // Write the loh load command, if used.
886 uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize;
887 if (LOHSize)
888 WriteLinkeditLoadCommand(MachO::LC_LINKER_OPTIMIZATION_HINT,
889 DataInCodeTableEnd, LOHSize);
890
Bill Wendlingeb872e02011-06-22 21:07:27 +0000891 // Write the symbol table load command, if used.
892 if (NumSymbols) {
893 unsigned FirstLocalSymbol = 0;
894 unsigned NumLocalSymbols = LocalSymbolData.size();
895 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
896 unsigned NumExternalSymbols = ExternalSymbolData.size();
897 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
898 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
899 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
900 unsigned NumSymTabSymbols =
901 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
902 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
903 uint64_t IndirectSymbolOffset = 0;
904
905 // If used, the indirect symbols are written after the section data.
906 if (NumIndirectSymbols)
Tim Northover53d32512014-03-29 07:34:53 +0000907 IndirectSymbolOffset = LOHTableEnd;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000908
909 // The symbol table is written after the indirect symbol data.
Tim Northover53d32512014-03-29 07:34:53 +0000910 uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000911
912 // The string table is written after symbol table.
913 uint64_t StringTableOffset =
Charles Davis8bdfafd2013-09-01 04:28:48 +0000914 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ?
915 sizeof(MachO::nlist_64) :
916 sizeof(MachO::nlist));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000917 WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000918 StringTableOffset, StringTable.data().size());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000919
920 WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
921 FirstExternalSymbol, NumExternalSymbols,
922 FirstUndefinedSymbol, NumUndefinedSymbols,
923 IndirectSymbolOffset, NumIndirectSymbols);
924 }
925
Daniel Dunbareec0f322013-01-18 01:26:07 +0000926 // Write the linker options load commands.
927 for (unsigned i = 0, e = LinkerOptions.size(); i != e; ++i) {
928 WriteLinkerOptionsLoadCommand(LinkerOptions[i]);
929 }
930
Bill Wendlingeb872e02011-06-22 21:07:27 +0000931 // Write the actual section data.
932 for (MCAssembler::const_iterator it = Asm.begin(),
933 ie = Asm.end(); it != ie; ++it) {
Jim Grosbach18e2fe42011-12-06 00:03:48 +0000934 Asm.writeSectionData(it, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000935
936 uint64_t Pad = getPaddingSize(it, Layout);
937 for (unsigned int i = 0; i < Pad; ++i)
938 Write8(0);
939 }
940
941 // Write the extra padding.
942 WriteZeros(SectionDataPadding);
943
944 // Write the relocation entries.
945 for (MCAssembler::const_iterator it = Asm.begin(),
946 ie = Asm.end(); it != ie; ++it) {
947 // Write the section relocation entries, in reverse order to match 'as'
948 // (approximately, the exact algorithm is more complicated than this).
Rafael Espindola26585542015-01-19 21:11:14 +0000949 std::vector<RelAndSymbol> &Relocs = Relocations[it];
Bill Wendlingeb872e02011-06-22 21:07:27 +0000950 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola26585542015-01-19 21:11:14 +0000951 Write32(Relocs[e - i - 1].MRE.r_word0);
952 Write32(Relocs[e - i - 1].MRE.r_word1);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000953 }
954 }
955
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000956 // Write out the data-in-code region payload, if there is one.
957 for (MCAssembler::const_data_region_iterator
958 it = Asm.data_region_begin(), ie = Asm.data_region_end();
959 it != ie; ++it) {
960 const DataRegionData *Data = &(*it);
Jim Grosbachb12b71a2012-09-18 23:05:12 +0000961 uint64_t Start =
962 getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->Start),
963 Layout);
964 uint64_t End =
965 getSymbolAddress(&Layout.getAssembler().getSymbolData(*Data->End),
966 Layout);
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000967 DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
968 << " start: " << Start << "(" << Data->Start->getName() << ")"
969 << " end: " << End << "(" << Data->End->getName() << ")"
970 << " size: " << End - Start
971 << "\n");
972 Write32(Start);
973 Write16(End - Start);
974 Write16(Data->Kind);
975 }
976
Tim Northover53d32512014-03-29 07:34:53 +0000977 // Write out the loh commands, if there is one.
978 if (LOHSize) {
979#ifndef NDEBUG
980 unsigned Start = OS.tell();
981#endif
982 Asm.getLOHContainer().Emit(*this, Layout);
983 // Pad to a multiple of the pointer size.
984 WriteBytes("", OffsetToAlignment(LOHRawSize, is64Bit() ? 8 : 4));
985 assert(OS.tell() - Start == LOHSize);
986 }
987
Bill Wendlingeb872e02011-06-22 21:07:27 +0000988 // Write the symbol table data, if used.
989 if (NumSymbols) {
990 // Write the indirect symbol entries.
991 for (MCAssembler::const_indirect_symbol_iterator
992 it = Asm.indirect_symbol_begin(),
993 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
Alp Tokerf907b892013-12-05 05:44:44 +0000994 // Indirect symbols in the non-lazy symbol pointer section have some
Bill Wendlingeb872e02011-06-22 21:07:27 +0000995 // special handling.
996 const MCSectionMachO &Section =
997 static_cast<const MCSectionMachO&>(it->SectionData->getSection());
David Majnemer7b583052014-03-07 07:36:05 +0000998 if (Section.getType() == MachO::S_NON_LAZY_SYMBOL_POINTERS) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000999 // If this symbol is defined and internal, mark it as such.
1000 if (it->Symbol->isDefined() &&
1001 !Asm.getSymbolData(*it->Symbol).isExternal()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001002 uint32_t Flags = MachO::INDIRECT_SYMBOL_LOCAL;
Bill Wendlingeb872e02011-06-22 21:07:27 +00001003 if (it->Symbol->isAbsolute())
Charles Davis8bdfafd2013-09-01 04:28:48 +00001004 Flags |= MachO::INDIRECT_SYMBOL_ABS;
Bill Wendlingeb872e02011-06-22 21:07:27 +00001005 Write32(Flags);
1006 continue;
1007 }
1008 }
1009
1010 Write32(Asm.getSymbolData(*it->Symbol).getIndex());
1011 }
1012
1013 // FIXME: Check that offsets match computed ones.
1014
1015 // Write the symbol table entries.
1016 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1017 WriteNlist(LocalSymbolData[i], Layout);
1018 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1019 WriteNlist(ExternalSymbolData[i], Layout);
1020 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1021 WriteNlist(UndefinedSymbolData[i], Layout);
1022
1023 // Write the string table.
Hans Wennborg1b1a3992014-10-06 17:05:19 +00001024 OS << StringTable.data();
Bill Wendlingeb872e02011-06-22 21:07:27 +00001025 }
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +00001026}
1027
Daniel Dunbar8888a962010-12-16 16:09:19 +00001028MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
Daniel Dunbar03fcccb2010-12-16 17:21:02 +00001029 raw_ostream &OS,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001030 bool IsLittleEndian) {
Daniel Dunbar03fcccb2010-12-16 17:21:02 +00001031 return new MachObjectWriter(MOTW, OS, IsLittleEndian);
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +00001032}