blob: 2fa65658ccfacfec0db3928d16586ee18f3be9e8 [file] [log] [blame]
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001//===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Eugene Zelenkof31871c2017-02-07 23:02:00 +000010#include "llvm/ADT/DenseMap.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000011#include "llvm/ADT/Twine.h"
Chandler Carruthe3e43d92017-06-06 11:49:48 +000012#include "llvm/ADT/iterator_range.h"
Zachary Turner19ca2b02017-06-07 03:48:56 +000013#include "llvm/BinaryFormat/MachO.h"
Evan Cheng78c10ee2011-07-25 23:24:55 +000014#include "llvm/MC/MCAsmBackend.h"
Daniel Dunbar207e06e2010-03-24 03:43:40 +000015#include "llvm/MC/MCAsmLayout.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/MC/MCAssembler.h"
Eugene Zelenkof31871c2017-02-07 23:02:00 +000017#include "llvm/MC/MCDirectives.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000018#include "llvm/MC/MCExpr.h"
Craig Topperf1d0f772012-03-26 06:58:25 +000019#include "llvm/MC/MCFixupKindInfo.h"
Eugene Zelenkof31871c2017-02-07 23:02:00 +000020#include "llvm/MC/MCFragment.h"
21#include "llvm/MC/MCMachObjectWriter.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000022#include "llvm/MC/MCObjectWriter.h"
Eugene Zelenkof31871c2017-02-07 23:02:00 +000023#include "llvm/MC/MCSection.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000024#include "llvm/MC/MCSectionMachO.h"
Eugene Zelenkof31871c2017-02-07 23:02:00 +000025#include "llvm/MC/MCSymbol.h"
Pete Cooperd3869ee2015-06-08 17:17:28 +000026#include "llvm/MC/MCSymbolMachO.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000027#include "llvm/MC/MCValue.h"
Eugene Zelenkof31871c2017-02-07 23:02:00 +000028#include "llvm/Support/Casting.h"
Jim Grosbach3e965312012-05-18 19:12:01 +000029#include "llvm/Support/Debug.h"
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000030#include "llvm/Support/ErrorHandling.h"
Eugene Zelenkof31871c2017-02-07 23:02:00 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer1bfcd1f2015-03-23 19:32:43 +000032#include "llvm/Support/raw_ostream.h"
Eugene Zelenkof31871c2017-02-07 23:02:00 +000033#include <algorithm>
34#include <cassert>
35#include <cstdint>
36#include <string>
37#include <utility>
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000038#include <vector>
Eugene Zelenkof31871c2017-02-07 23:02:00 +000039
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000040using namespace llvm;
41
Chandler Carruth283b3992014-04-21 22:55:11 +000042#define DEBUG_TYPE "mc"
43
Pedro Artigas99cbdde2012-12-14 18:52:11 +000044void MachObjectWriter::reset() {
45 Relocations.clear();
46 IndirectSymBase.clear();
47 StringTable.clear();
48 LocalSymbolData.clear();
49 ExternalSymbolData.clear();
50 UndefinedSymbolData.clear();
51 MCObjectWriter::reset();
52}
53
Duncan P. N. Exon Smithc8d166a2015-05-20 15:16:14 +000054bool MachObjectWriter::doesSymbolRequireExternRelocation(const MCSymbol &S) {
Daniel Dunbare9460ec2010-05-10 23:15:13 +000055 // Undefined symbols are always extern.
Duncan P. N. Exon Smithc8d166a2015-05-20 15:16:14 +000056 if (S.isUndefined())
Daniel Dunbare9460ec2010-05-10 23:15:13 +000057 return true;
58
59 // References to weak definitions require external relocation entries; the
60 // definition may not always be the one in the same object file.
Pete Cooperd3869ee2015-06-08 17:17:28 +000061 if (cast<MCSymbolMachO>(S).isWeakDefinition())
Daniel Dunbare9460ec2010-05-10 23:15:13 +000062 return true;
63
64 // Otherwise, we can use an internal relocation.
65 return false;
66}
67
Jim Grosbachba8297e2011-06-24 23:44:37 +000068bool MachObjectWriter::
69MachSymbolData::operator<(const MachSymbolData &RHS) const {
Duncan P. N. Exon Smithc8d166a2015-05-20 15:16:14 +000070 return Symbol->getName() < RHS.Symbol->getName();
Jim Grosbachba8297e2011-06-24 23:44:37 +000071}
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000072
Jim Grosbachba8297e2011-06-24 23:44:37 +000073bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
74 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
75 (MCFixupKind) Kind);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000076
Jim Grosbachba8297e2011-06-24 23:44:37 +000077 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
78}
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +000079
Jim Grosbachba8297e2011-06-24 23:44:37 +000080uint64_t MachObjectWriter::getFragmentAddress(const MCFragment *Fragment,
81 const MCAsmLayout &Layout) const {
Rafael Espindola504473e2015-05-26 00:52:18 +000082 return getSectionAddress(Fragment->getParent()) +
Rafael Espindolaf3639602015-05-26 00:36:57 +000083 Layout.getFragmentOffset(Fragment);
Jim Grosbachba8297e2011-06-24 23:44:37 +000084}
Bill Wendlingbbdffa92011-06-22 21:07:27 +000085
Duncan P. N. Exon Smith891fd532015-05-20 00:02:39 +000086uint64_t MachObjectWriter::getSymbolAddress(const MCSymbol &S,
Bill Wendlingbbdffa92011-06-22 21:07:27 +000087 const MCAsmLayout &Layout) const {
Bill Wendlingbbdffa92011-06-22 21:07:27 +000088 // If this is a variable, then recursively evaluate now.
89 if (S.isVariable()) {
Jim Grosbach45d81bd2012-09-13 23:11:25 +000090 if (const MCConstantExpr *C =
91 dyn_cast<const MCConstantExpr>(S.getVariableValue()))
92 return C->getValue();
93
Bill Wendlingbbdffa92011-06-22 21:07:27 +000094 MCValue Target;
Jim Grosbach586c0042015-05-30 01:25:56 +000095 if (!S.getVariableValue()->evaluateAsRelocatable(Target, &Layout, nullptr))
Bill Wendlingbbdffa92011-06-22 21:07:27 +000096 report_fatal_error("unable to evaluate offset for variable '" +
97 S.getName() + "'");
98
99 // Verify that any used symbols are defined.
100 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
101 report_fatal_error("unable to evaluate offset to undefined symbol '" +
102 Target.getSymA()->getSymbol().getName() + "'");
103 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
104 report_fatal_error("unable to evaluate offset to undefined symbol '" +
105 Target.getSymB()->getSymbol().getName() + "'");
106
107 uint64_t Address = Target.getConstant();
108 if (Target.getSymA())
Duncan P. N. Exon Smith891fd532015-05-20 00:02:39 +0000109 Address += getSymbolAddress(Target.getSymA()->getSymbol(), Layout);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000110 if (Target.getSymB())
Duncan P. N. Exon Smith891fd532015-05-20 00:02:39 +0000111 Address += getSymbolAddress(Target.getSymB()->getSymbol(), Layout);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000112 return Address;
113 }
114
Rafael Espindolacfac75a2015-05-29 21:45:01 +0000115 return getSectionAddress(S.getFragment()->getParent()) +
Duncan P. N. Exon Smithe1fce862015-05-19 23:53:20 +0000116 Layout.getSymbolOffset(S);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000117}
118
Rafael Espindola1826cd62015-05-26 01:15:30 +0000119uint64_t MachObjectWriter::getPaddingSize(const MCSection *Sec,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000120 const MCAsmLayout &Layout) const {
Rafael Espindolaea3533b2015-05-26 02:00:36 +0000121 uint64_t EndAddr = getSectionAddress(Sec) + Layout.getSectionAddressSize(Sec);
Rafael Espindola1826cd62015-05-26 01:15:30 +0000122 unsigned Next = Sec->getLayoutOrder() + 1;
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000123 if (Next >= Layout.getSectionOrder().size())
124 return 0;
125
Rafael Espindolaea3533b2015-05-26 02:00:36 +0000126 const MCSection &NextSec = *Layout.getSectionOrder()[Next];
127 if (NextSec.isVirtualSection())
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000128 return 0;
Rafael Espindolaea3533b2015-05-26 02:00:36 +0000129 return OffsetToAlignment(EndAddr, NextSec.getAlignment());
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000130}
131
Frederic Rissbfec0722015-08-26 05:09:46 +0000132void MachObjectWriter::writeHeader(MachO::HeaderFileType Type,
133 unsigned NumLoadCommands,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000134 unsigned LoadCommandsSize,
135 bool SubsectionsViaSymbols) {
136 uint32_t Flags = 0;
137
138 if (SubsectionsViaSymbols)
Charles Davis55107282013-09-01 04:28:48 +0000139 Flags |= MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000140
141 // struct mach_header (28 bytes) or
142 // struct mach_header_64 (32 bytes)
143
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000144 uint64_t Start = W.OS.tell();
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000145 (void) Start;
146
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000147 W.write<uint32_t>(is64Bit() ? MachO::MH_MAGIC_64 : MachO::MH_MAGIC);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000148
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000149 W.write<uint32_t>(TargetObjectWriter->getCPUType());
150 W.write<uint32_t>(TargetObjectWriter->getCPUSubtype());
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000151
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000152 W.write<uint32_t>(Type);
153 W.write<uint32_t>(NumLoadCommands);
154 W.write<uint32_t>(LoadCommandsSize);
155 W.write<uint32_t>(Flags);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000156 if (is64Bit())
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000157 W.write<uint32_t>(0); // reserved
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000158
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000159 assert(W.OS.tell() - Start == (is64Bit() ? sizeof(MachO::mach_header_64)
160 : sizeof(MachO::mach_header)));
161}
162
163void MachObjectWriter::writeWithPadding(StringRef Str, uint64_t Size) {
164 assert(Size >= Str.size());
165 W.OS << Str;
166 W.OS.write_zeros(Size - Str.size());
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000167}
168
Jim Grosbacheafe4652015-06-04 23:25:54 +0000169/// writeSegmentLoadCommand - Write a segment load command.
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000170///
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +0000171/// \param NumSections The number of sections in this segment.
172/// \param SectionDataSize The total size of the sections.
Frederic Rissbfec0722015-08-26 05:09:46 +0000173void MachObjectWriter::writeSegmentLoadCommand(
174 StringRef Name, unsigned NumSections, uint64_t VMAddr, uint64_t VMSize,
175 uint64_t SectionDataStartOffset, uint64_t SectionDataSize, uint32_t MaxProt,
176 uint32_t InitProt) {
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000177 // struct segment_command (56 bytes) or
178 // struct segment_command_64 (72 bytes)
179
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000180 uint64_t Start = W.OS.tell();
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000181 (void) Start;
182
183 unsigned SegmentLoadCommandSize =
Charles Davis55107282013-09-01 04:28:48 +0000184 is64Bit() ? sizeof(MachO::segment_command_64):
185 sizeof(MachO::segment_command);
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000186 W.write<uint32_t>(is64Bit() ? MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT);
187 W.write<uint32_t>(SegmentLoadCommandSize +
Charles Davis55107282013-09-01 04:28:48 +0000188 NumSections * (is64Bit() ? sizeof(MachO::section_64) :
189 sizeof(MachO::section)));
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000190
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000191 writeWithPadding(Name, 16);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000192 if (is64Bit()) {
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000193 W.write<uint64_t>(VMAddr); // vmaddr
194 W.write<uint64_t>(VMSize); // vmsize
195 W.write<uint64_t>(SectionDataStartOffset); // file offset
196 W.write<uint64_t>(SectionDataSize); // file size
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000197 } else {
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000198 W.write<uint32_t>(VMAddr); // vmaddr
199 W.write<uint32_t>(VMSize); // vmsize
200 W.write<uint32_t>(SectionDataStartOffset); // file offset
201 W.write<uint32_t>(SectionDataSize); // file size
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000202 }
Nick Kledzika38c27b2013-09-04 23:53:44 +0000203 // maxprot
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000204 W.write<uint32_t>(MaxProt);
Nick Kledzika38c27b2013-09-04 23:53:44 +0000205 // initprot
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000206 W.write<uint32_t>(InitProt);
207 W.write<uint32_t>(NumSections);
208 W.write<uint32_t>(0); // flags
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000209
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000210 assert(W.OS.tell() - Start == SegmentLoadCommandSize);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000211}
212
Frederic Rissbfec0722015-08-26 05:09:46 +0000213void MachObjectWriter::writeSection(const MCAsmLayout &Layout,
214 const MCSection &Sec, uint64_t VMAddr,
215 uint64_t FileOffset, unsigned Flags,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000216 uint64_t RelocationsStart,
217 unsigned NumRelocations) {
Rafael Espindolaea3533b2015-05-26 02:00:36 +0000218 uint64_t SectionSize = Layout.getSectionAddressSize(&Sec);
Rafael Espindola1826cd62015-05-26 01:15:30 +0000219 const MCSectionMachO &Section = cast<MCSectionMachO>(Sec);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000220
221 // The offset is unused for virtual sections.
Rafael Espindola477acf62015-05-21 21:02:35 +0000222 if (Section.isVirtualSection()) {
Rafael Espindolaea3533b2015-05-26 02:00:36 +0000223 assert(Layout.getSectionFileSize(&Sec) == 0 && "Invalid file size!");
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000224 FileOffset = 0;
225 }
226
227 // struct section (68 bytes) or
228 // struct section_64 (80 bytes)
229
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000230 uint64_t Start = W.OS.tell();
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000231 (void) Start;
232
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000233 writeWithPadding(Section.getSectionName(), 16);
234 writeWithPadding(Section.getSegmentName(), 16);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000235 if (is64Bit()) {
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000236 W.write<uint64_t>(VMAddr); // address
237 W.write<uint64_t>(SectionSize); // size
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000238 } else {
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000239 W.write<uint32_t>(VMAddr); // address
240 W.write<uint32_t>(SectionSize); // size
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000241 }
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000242 W.write<uint32_t>(FileOffset);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000243
Rafael Espindola477acf62015-05-21 21:02:35 +0000244 assert(isPowerOf2_32(Section.getAlignment()) && "Invalid alignment!");
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000245 W.write<uint32_t>(Log2_32(Section.getAlignment()));
246 W.write<uint32_t>(NumRelocations ? RelocationsStart : 0);
247 W.write<uint32_t>(NumRelocations);
248 W.write<uint32_t>(Flags);
249 W.write<uint32_t>(IndirectSymBase.lookup(&Sec)); // reserved1
250 W.write<uint32_t>(Section.getStubSize()); // reserved2
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000251 if (is64Bit())
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000252 W.write<uint32_t>(0); // reserved3
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000253
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000254 assert(W.OS.tell() - Start ==
David Majnemer919f1f42015-09-01 16:19:03 +0000255 (is64Bit() ? sizeof(MachO::section_64) : sizeof(MachO::section)));
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000256}
257
Jim Grosbacheafe4652015-06-04 23:25:54 +0000258void MachObjectWriter::writeSymtabLoadCommand(uint32_t SymbolOffset,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000259 uint32_t NumSymbols,
260 uint32_t StringTableOffset,
261 uint32_t StringTableSize) {
262 // struct symtab_command (24 bytes)
263
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000264 uint64_t Start = W.OS.tell();
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000265 (void) Start;
266
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000267 W.write<uint32_t>(MachO::LC_SYMTAB);
268 W.write<uint32_t>(sizeof(MachO::symtab_command));
269 W.write<uint32_t>(SymbolOffset);
270 W.write<uint32_t>(NumSymbols);
271 W.write<uint32_t>(StringTableOffset);
272 W.write<uint32_t>(StringTableSize);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000273
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000274 assert(W.OS.tell() - Start == sizeof(MachO::symtab_command));
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000275}
276
Jim Grosbacheafe4652015-06-04 23:25:54 +0000277void MachObjectWriter::writeDysymtabLoadCommand(uint32_t FirstLocalSymbol,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000278 uint32_t NumLocalSymbols,
279 uint32_t FirstExternalSymbol,
280 uint32_t NumExternalSymbols,
281 uint32_t FirstUndefinedSymbol,
282 uint32_t NumUndefinedSymbols,
283 uint32_t IndirectSymbolOffset,
284 uint32_t NumIndirectSymbols) {
285 // struct dysymtab_command (80 bytes)
286
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000287 uint64_t Start = W.OS.tell();
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000288 (void) Start;
289
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000290 W.write<uint32_t>(MachO::LC_DYSYMTAB);
291 W.write<uint32_t>(sizeof(MachO::dysymtab_command));
292 W.write<uint32_t>(FirstLocalSymbol);
293 W.write<uint32_t>(NumLocalSymbols);
294 W.write<uint32_t>(FirstExternalSymbol);
295 W.write<uint32_t>(NumExternalSymbols);
296 W.write<uint32_t>(FirstUndefinedSymbol);
297 W.write<uint32_t>(NumUndefinedSymbols);
298 W.write<uint32_t>(0); // tocoff
299 W.write<uint32_t>(0); // ntoc
300 W.write<uint32_t>(0); // modtaboff
301 W.write<uint32_t>(0); // nmodtab
302 W.write<uint32_t>(0); // extrefsymoff
303 W.write<uint32_t>(0); // nextrefsyms
304 W.write<uint32_t>(IndirectSymbolOffset);
305 W.write<uint32_t>(NumIndirectSymbols);
306 W.write<uint32_t>(0); // extreloff
307 W.write<uint32_t>(0); // nextrel
308 W.write<uint32_t>(0); // locreloff
309 W.write<uint32_t>(0); // nlocrel
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000310
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000311 assert(W.OS.tell() - Start == sizeof(MachO::dysymtab_command));
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000312}
313
Tim Northover98f8bc92014-05-30 13:22:59 +0000314MachObjectWriter::MachSymbolData *
315MachObjectWriter::findSymbolData(const MCSymbol &Sym) {
Benjamin Kramer5deb54f2015-06-04 21:17:27 +0000316 for (auto *SymbolData :
317 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
318 for (MachSymbolData &Entry : *SymbolData)
319 if (Entry.Symbol == &Sym)
320 return &Entry;
Tim Northover98f8bc92014-05-30 13:22:59 +0000321
322 return nullptr;
323}
324
Rafael Espindoladb244042015-04-17 12:28:43 +0000325const MCSymbol &MachObjectWriter::findAliasedSymbol(const MCSymbol &Sym) const {
326 const MCSymbol *S = &Sym;
327 while (S->isVariable()) {
328 const MCExpr *Value = S->getVariableValue();
329 const auto *Ref = dyn_cast<MCSymbolRefExpr>(Value);
330 if (!Ref)
331 return *S;
332 S = &Ref->getSymbol();
333 }
334 return *S;
335}
336
Jim Grosbacheafe4652015-06-04 23:25:54 +0000337void MachObjectWriter::writeNlist(MachSymbolData &MSD,
Bill Wendling3f2ea822011-06-23 00:09:43 +0000338 const MCAsmLayout &Layout) {
Duncan P. N. Exon Smithc8d166a2015-05-20 15:16:14 +0000339 const MCSymbol *Symbol = MSD.Symbol;
Rafael Espindolacfac75a2015-05-29 21:45:01 +0000340 const MCSymbol &Data = *Symbol;
Rafael Espindoladb244042015-04-17 12:28:43 +0000341 const MCSymbol *AliasedSymbol = &findAliasedSymbol(*Symbol);
Tim Northover98f8bc92014-05-30 13:22:59 +0000342 uint8_t SectionIndex = MSD.SectionIndex;
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000343 uint8_t Type = 0;
Jim Grosbach739b5572011-08-09 22:12:37 +0000344 uint64_t Address = 0;
Tim Northover98f8bc92014-05-30 13:22:59 +0000345 bool IsAlias = Symbol != AliasedSymbol;
346
Duncan P. N. Exon Smithaa87ff82015-05-21 00:39:24 +0000347 const MCSymbol &OrigSymbol = *Symbol;
Tim Northover98f8bc92014-05-30 13:22:59 +0000348 MachSymbolData *AliaseeInfo;
349 if (IsAlias) {
350 AliaseeInfo = findSymbolData(*AliasedSymbol);
351 if (AliaseeInfo)
352 SectionIndex = AliaseeInfo->SectionIndex;
353 Symbol = AliasedSymbol;
Lang Hames875b7562016-03-15 01:43:05 +0000354 // FIXME: Should this update Data as well?
Tim Northover98f8bc92014-05-30 13:22:59 +0000355 }
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000356
357 // Set the N_TYPE bits. See <mach-o/nlist.h>.
358 //
359 // FIXME: Are the prebound or indirect fields possible here?
Tim Northover98f8bc92014-05-30 13:22:59 +0000360 if (IsAlias && Symbol->isUndefined())
361 Type = MachO::N_INDR;
362 else if (Symbol->isUndefined())
Charles Davis55107282013-09-01 04:28:48 +0000363 Type = MachO::N_UNDF;
Tim Northover98f8bc92014-05-30 13:22:59 +0000364 else if (Symbol->isAbsolute())
Charles Davis55107282013-09-01 04:28:48 +0000365 Type = MachO::N_ABS;
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000366 else
Charles Davis55107282013-09-01 04:28:48 +0000367 Type = MachO::N_SECT;
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000368
369 // FIXME: Set STAB bits.
370
371 if (Data.isPrivateExtern())
Charles Davis55107282013-09-01 04:28:48 +0000372 Type |= MachO::N_PEXT;
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000373
374 // Set external bit.
Tim Northover98f8bc92014-05-30 13:22:59 +0000375 if (Data.isExternal() || (!IsAlias && Symbol->isUndefined()))
Charles Davis55107282013-09-01 04:28:48 +0000376 Type |= MachO::N_EXT;
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000377
378 // Compute the symbol address.
Tim Northover98f8bc92014-05-30 13:22:59 +0000379 if (IsAlias && Symbol->isUndefined())
380 Address = AliaseeInfo->StringIndex;
381 else if (Symbol->isDefined())
Duncan P. N. Exon Smithaa87ff82015-05-21 00:39:24 +0000382 Address = getSymbolAddress(OrigSymbol, Layout);
Rafael Espindola82fdcc02015-05-29 17:48:04 +0000383 else if (Symbol->isCommon()) {
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000384 // Common symbols are encoded with the size in the address
385 // field, and their alignment in the flags.
Rafael Espindola82fdcc02015-05-29 17:48:04 +0000386 Address = Symbol->getCommonSize();
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000387 }
388
389 // struct nlist (12 bytes)
390
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000391 W.write<uint32_t>(MSD.StringIndex);
392 W.OS << char(Type);
393 W.OS << char(SectionIndex);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000394
395 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
396 // value.
Lang Hames875b7562016-03-15 01:43:05 +0000397 bool EncodeAsAltEntry =
398 IsAlias && cast<MCSymbolMachO>(OrigSymbol).isAltEntry();
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000399 W.write<uint16_t>(cast<MCSymbolMachO>(Symbol)->getEncodedFlags(EncodeAsAltEntry));
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000400 if (is64Bit())
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000401 W.write<uint64_t>(Address);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000402 else
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000403 W.write<uint32_t>(Address);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000404}
405
Jim Grosbacheafe4652015-06-04 23:25:54 +0000406void MachObjectWriter::writeLinkeditLoadCommand(uint32_t Type,
Jim Grosbach3e965312012-05-18 19:12:01 +0000407 uint32_t DataOffset,
408 uint32_t DataSize) {
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000409 uint64_t Start = W.OS.tell();
Jim Grosbach3e965312012-05-18 19:12:01 +0000410 (void) Start;
411
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000412 W.write<uint32_t>(Type);
413 W.write<uint32_t>(sizeof(MachO::linkedit_data_command));
414 W.write<uint32_t>(DataOffset);
415 W.write<uint32_t>(DataSize);
Jim Grosbach3e965312012-05-18 19:12:01 +0000416
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000417 assert(W.OS.tell() - Start == sizeof(MachO::linkedit_data_command));
Jim Grosbach3e965312012-05-18 19:12:01 +0000418}
419
Daniel Dunbara94c3392013-01-18 01:26:07 +0000420static unsigned ComputeLinkerOptionsLoadCommandSize(
Daniel Dunbar84920962013-01-22 03:42:49 +0000421 const std::vector<std::string> &Options, bool is64Bit)
Daniel Dunbara94c3392013-01-18 01:26:07 +0000422{
Kevin Enderby1025e9e2014-12-18 00:53:40 +0000423 unsigned Size = sizeof(MachO::linker_option_command);
Benjamin Kramer5deb54f2015-06-04 21:17:27 +0000424 for (const std::string &Option : Options)
425 Size += Option.size() + 1;
Rui Ueyama3edb0ec2016-01-14 21:06:47 +0000426 return alignTo(Size, is64Bit ? 8 : 4);
Daniel Dunbara94c3392013-01-18 01:26:07 +0000427}
428
Jim Grosbacheafe4652015-06-04 23:25:54 +0000429void MachObjectWriter::writeLinkerOptionsLoadCommand(
Daniel Dunbara94c3392013-01-18 01:26:07 +0000430 const std::vector<std::string> &Options)
431{
Daniel Dunbar84920962013-01-22 03:42:49 +0000432 unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit());
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000433 uint64_t Start = W.OS.tell();
Daniel Dunbara94c3392013-01-18 01:26:07 +0000434 (void) Start;
435
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000436 W.write<uint32_t>(MachO::LC_LINKER_OPTION);
437 W.write<uint32_t>(Size);
438 W.write<uint32_t>(Options.size());
Kevin Enderby1025e9e2014-12-18 00:53:40 +0000439 uint64_t BytesWritten = sizeof(MachO::linker_option_command);
Benjamin Kramer5deb54f2015-06-04 21:17:27 +0000440 for (const std::string &Option : Options) {
Daniel Dunbara94c3392013-01-18 01:26:07 +0000441 // Write each string, including the null byte.
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000442 W.OS << Option << '\0';
Daniel Dunbara94c3392013-01-18 01:26:07 +0000443 BytesWritten += Option.size() + 1;
444 }
445
Daniel Dunbar84920962013-01-22 03:42:49 +0000446 // Pad to a multiple of the pointer size.
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000447 W.OS.write_zeros(OffsetToAlignment(BytesWritten, is64Bit() ? 8 : 4));
Daniel Dunbara94c3392013-01-18 01:26:07 +0000448
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000449 assert(W.OS.tell() - Start == Size);
Daniel Dunbara94c3392013-01-18 01:26:07 +0000450}
451
Jim Grosbachbc812862015-06-04 22:24:41 +0000452void MachObjectWriter::recordRelocation(MCAssembler &Asm,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000453 const MCAsmLayout &Layout,
454 const MCFragment *Fragment,
Rafael Espindolaa23cc6a2015-01-19 21:11:14 +0000455 const MCFixup &Fixup, MCValue Target,
Rafael Espindola210f5222017-07-11 23:56:10 +0000456 uint64_t &FixedValue) {
Jim Grosbachbc812862015-06-04 22:24:41 +0000457 TargetObjectWriter->recordRelocation(this, Asm, Layout, Fragment, Fixup,
Jim Grosbachba8297e2011-06-24 23:44:37 +0000458 Target, FixedValue);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000459}
460
Jim Grosbacheafe4652015-06-04 23:25:54 +0000461void MachObjectWriter::bindIndirectSymbols(MCAssembler &Asm) {
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000462 // This is the point where 'as' creates actual symbols for indirect symbols
463 // (in the following two passes). It would be easier for us to do this sooner
464 // when we see the attribute, but that makes getting the order in the symbol
465 // table much more complicated than it is worth.
466 //
467 // FIXME: Revisit this when the dust settles.
468
Kevin Enderby4f066b62013-08-28 17:50:59 +0000469 // Report errors for use of .indirect_symbol not in a symbol pointer section
470 // or stub section.
471 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
472 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
Rafael Espindola2224f642015-05-26 02:17:21 +0000473 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
Kevin Enderby4f066b62013-08-28 17:50:59 +0000474
David Majnemer508e0c42014-03-07 07:36:05 +0000475 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
476 Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
Tim Northover02e44982016-04-25 21:12:04 +0000477 Section.getType() != MachO::S_THREAD_LOCAL_VARIABLE_POINTERS &&
David Majnemer508e0c42014-03-07 07:36:05 +0000478 Section.getType() != MachO::S_SYMBOL_STUBS) {
NAKAMURA Takumi09c0ea52015-09-22 11:15:07 +0000479 MCSymbol &Symbol = *it->Symbol;
480 report_fatal_error("indirect symbol '" + Symbol.getName() +
481 "' not in a symbol pointer or stub section");
Kevin Enderby4f066b62013-08-28 17:50:59 +0000482 }
483 }
484
Alp Toker087ab612013-12-05 05:44:44 +0000485 // Bind non-lazy symbol pointers first.
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000486 unsigned IndirectIndex = 0;
487 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
488 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Rafael Espindola2224f642015-05-26 02:17:21 +0000489 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000490
Tim Northover3005d0c2016-04-26 18:29:16 +0000491 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
492 Section.getType() != MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000493 continue;
494
495 // Initialize the section indirect symbol base, if necessary.
Rafael Espindola2224f642015-05-26 02:17:21 +0000496 IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000497
Rafael Espindolaf00654b2015-05-29 20:21:02 +0000498 Asm.registerSymbol(*it->Symbol);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000499 }
500
501 // Then lazy symbol pointers and symbol stubs.
502 IndirectIndex = 0;
503 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
504 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Rafael Espindola2224f642015-05-26 02:17:21 +0000505 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000506
David Majnemer508e0c42014-03-07 07:36:05 +0000507 if (Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
508 Section.getType() != MachO::S_SYMBOL_STUBS)
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000509 continue;
510
511 // Initialize the section indirect symbol base, if necessary.
Rafael Espindola2224f642015-05-26 02:17:21 +0000512 IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
Bill Wendlingbbdffa92011-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;
Rafael Espindolaf00654b2015-05-29 20:21:02 +0000518 Asm.registerSymbol(*it->Symbol, &Created);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000519 if (Created)
Pete Cooperd3869ee2015-06-08 17:17:28 +0000520 cast<MCSymbolMachO>(it->Symbol)->setReferenceTypeUndefinedLazy(true);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000521 }
522}
523
Jim Grosbacheafe4652015-06-04 23:25:54 +0000524/// computeSymbolTable - Compute the symbol table data
525void MachObjectWriter::computeSymbolTable(
Hans Wennborg7fcd5f82014-10-06 17:05:19 +0000526 MCAssembler &Asm, std::vector<MachSymbolData> &LocalSymbolData,
527 std::vector<MachSymbolData> &ExternalSymbolData,
528 std::vector<MachSymbolData> &UndefinedSymbolData) {
Bill Wendlingbbdffa92011-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)
Rafael Espindolae86bc462015-05-25 23:14:17 +0000534 SectionIndexMap[&*it] = Index;
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000535 assert(Index <= 256 && "Too many sections!");
536
Hans Wennborg7fcd5f82014-10-06 17:05:19 +0000537 // Build the string table.
Duncan P. N. Exon Smitha5bb8422015-05-16 00:35:24 +0000538 for (const MCSymbol &Symbol : Asm.symbols()) {
Hans Wennborg7fcd5f82014-10-06 17:05:19 +0000539 if (!Asm.isSymbolLinkerVisible(Symbol))
540 continue;
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000541
Hans Wennborg7fcd5f82014-10-06 17:05:19 +0000542 StringTable.add(Symbol.getName());
543 }
Rafael Espindola715bcca2015-10-23 21:48:05 +0000544 StringTable.finalize();
Hans Wennborg7fcd5f82014-10-06 17:05:19 +0000545
546 // Build the symbol arrays but only for non-local symbols.
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000547 //
Hans Wennborg7fcd5f82014-10-06 17:05:19 +0000548 // The particular order that we collect and then sort the symbols is chosen to
549 // match 'as'. Even though it doesn't matter for correctness, this is
550 // important for letting us diff .o files.
Duncan P. N. Exon Smitha5bb8422015-05-16 00:35:24 +0000551 for (const MCSymbol &Symbol : Asm.symbols()) {
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000552 // Ignore non-linker visible symbols.
Hans Wennborg7fcd5f82014-10-06 17:05:19 +0000553 if (!Asm.isSymbolLinkerVisible(Symbol))
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000554 continue;
555
Rafael Espindolacfac75a2015-05-29 21:45:01 +0000556 if (!Symbol.isExternal() && !Symbol.isUndefined())
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000557 continue;
558
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000559 MachSymbolData MSD;
Duncan P. N. Exon Smithc8d166a2015-05-20 15:16:14 +0000560 MSD.Symbol = &Symbol;
Hans Wennborg7fcd5f82014-10-06 17:05:19 +0000561 MSD.StringIndex = StringTable.getOffset(Symbol.getName());
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000562
563 if (Symbol.isUndefined()) {
564 MSD.SectionIndex = 0;
565 UndefinedSymbolData.push_back(MSD);
566 } else if (Symbol.isAbsolute()) {
567 MSD.SectionIndex = 0;
568 ExternalSymbolData.push_back(MSD);
569 } else {
570 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
571 assert(MSD.SectionIndex && "Invalid section index!");
572 ExternalSymbolData.push_back(MSD);
573 }
574 }
575
576 // Now add the data for local symbols.
Duncan P. N. Exon Smitha5bb8422015-05-16 00:35:24 +0000577 for (const MCSymbol &Symbol : Asm.symbols()) {
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000578 // Ignore non-linker visible symbols.
Hans Wennborg7fcd5f82014-10-06 17:05:19 +0000579 if (!Asm.isSymbolLinkerVisible(Symbol))
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000580 continue;
581
Rafael Espindolacfac75a2015-05-29 21:45:01 +0000582 if (Symbol.isExternal() || Symbol.isUndefined())
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000583 continue;
584
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000585 MachSymbolData MSD;
Duncan P. N. Exon Smithc8d166a2015-05-20 15:16:14 +0000586 MSD.Symbol = &Symbol;
Daniel Jasperb7f5b8b2015-06-23 11:31:32 +0000587 MSD.StringIndex = StringTable.getOffset(Symbol.getName());
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000588
589 if (Symbol.isAbsolute()) {
590 MSD.SectionIndex = 0;
591 LocalSymbolData.push_back(MSD);
592 } else {
593 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
594 assert(MSD.SectionIndex && "Invalid section index!");
595 LocalSymbolData.push_back(MSD);
596 }
597 }
598
599 // External and undefined symbols are required to be in lexicographic order.
Fangrui Song3b35e172018-09-27 02:13:45 +0000600 llvm::sort(ExternalSymbolData);
601 llvm::sort(UndefinedSymbolData);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000602
603 // Set the symbol indices.
604 Index = 0;
Benjamin Kramer5deb54f2015-06-04 21:17:27 +0000605 for (auto *SymbolData :
606 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
607 for (MachSymbolData &Entry : *SymbolData)
608 Entry.Symbol->setIndex(Index++);
Rafael Espindolaa23cc6a2015-01-19 21:11:14 +0000609
Rafael Espindolae86bc462015-05-25 23:14:17 +0000610 for (const MCSection &Section : Asm) {
Benjamin Kramer5deb54f2015-06-04 21:17:27 +0000611 for (RelAndSymbol &Rel : Relocations[&Section]) {
Rafael Espindolaa23cc6a2015-01-19 21:11:14 +0000612 if (!Rel.Sym)
613 continue;
614
615 // Set the Index and the IsExtern bit.
Duncan P. N. Exon Smith6c3a7cb2015-05-22 05:54:01 +0000616 unsigned Index = Rel.Sym->getIndex();
Rafael Espindolaa23cc6a2015-01-19 21:11:14 +0000617 assert(isInt<24>(Index));
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000618 if (W.Endian == support::little)
Justin Bogner47ccfa7d2015-05-14 23:54:49 +0000619 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & (~0U << 24)) | Index | (1 << 27);
Rafael Espindolaa23cc6a2015-01-19 21:11:14 +0000620 else
621 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & 0xff) | Index << 8 | (1 << 4);
622 }
623 }
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000624}
625
626void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
627 const MCAsmLayout &Layout) {
628 uint64_t StartAddress = 0;
Benjamin Kramer5deb54f2015-06-04 21:17:27 +0000629 for (const MCSection *Sec : Layout.getSectionOrder()) {
Rui Ueyama3edb0ec2016-01-14 21:06:47 +0000630 StartAddress = alignTo(StartAddress, Sec->getAlignment());
Rafael Espindolaea3533b2015-05-26 02:00:36 +0000631 SectionAddress[Sec] = StartAddress;
632 StartAddress += Layout.getSectionAddressSize(Sec);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000633
634 // Explicitly pad the section to match the alignment requirements of the
635 // following one. This is for 'gas' compatibility, it shouldn't
636 /// strictly be necessary.
Rafael Espindolaea3533b2015-05-26 02:00:36 +0000637 StartAddress += getPaddingSize(Sec, Layout);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000638 }
639}
640
Jim Grosbacheafe4652015-06-04 23:25:54 +0000641void MachObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
Bill Wendling3f2ea822011-06-23 00:09:43 +0000642 const MCAsmLayout &Layout) {
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000643 computeSectionAddresses(Asm, Layout);
644
645 // Create symbol data for any indirect symbols.
Jim Grosbacheafe4652015-06-04 23:25:54 +0000646 bindIndirectSymbols(Asm);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000647}
648
Jim Grosbachbc812862015-06-04 22:24:41 +0000649bool MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
Rafael Espindola0eba49c2015-10-05 12:07:05 +0000650 const MCAssembler &Asm, const MCSymbol &A, const MCSymbol &B,
651 bool InSet) const {
652 // FIXME: We don't handle things like
653 // foo = .
654 // creating atoms.
655 if (A.isVariable() || B.isVariable())
656 return false;
657 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, A, B,
658 InSet);
659}
660
661bool MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
Duncan P. N. Exon Smith9e6378d2015-05-16 01:01:55 +0000662 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
Rafael Espindolafb118bd2015-04-17 21:15:17 +0000663 bool InSet, bool IsPCRel) const {
Bill Wendlingbbdffa92011-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.
Duncan P. N. Exon Smith9e6378d2015-05-16 01:01:55 +0000672 const MCSymbol &SA = findAliasedSymbol(SymA);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000673 const MCSection &SecA = SA.getSection();
Rafael Espindolaf3639602015-05-26 00:36:57 +0000674 const MCSection &SecB = *FB.getParent();
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000675
676 if (IsPCRel) {
677 // The simple (Darwin, except on x86_64) way of dealing with this was to
678 // assume that any reference to a temporary symbol *must* be a temporary
679 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
680 // relocation to a temporary symbol (in the same section) is fully
681 // resolved. This also works in conjunction with absolutized .set, which
682 // requires the compiler to use .set to absolutize the differences between
683 // symbols which the compiler knows to be assembly time constants, so we
684 // don't need to worry about considering symbol differences fully resolved.
Jim Grosbach577b0912011-12-07 19:46:59 +0000685 //
686 // If the file isn't using sub-sections-via-symbols, we can make the
687 // same assumptions about any symbol that we normally make about
688 // assembler locals.
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000689
Rafael Espindolad1742f62014-03-11 21:22:57 +0000690 bool hasReliableSymbolDifference = isX86_64();
691 if (!hasReliableSymbolDifference) {
Jim Grosbach8b9300b2012-01-17 22:14:39 +0000692 if (!SA.isInSection() || &SecA != &SecB ||
Rafael Espindolacfac75a2015-05-29 21:45:01 +0000693 (!SA.isTemporary() && FB.getAtom() != SA.getFragment()->getAtom() &&
Jim Grosbachc389af92012-01-24 21:45:25 +0000694 Asm.getSubsectionsViaSymbols()))
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000695 return false;
696 return true;
697 }
Kevin Enderby5afc1902011-09-08 20:53:44 +0000698 // For Darwin x86_64, there is one special case when the reference IsPCRel.
699 // If the fragment with the reference does not have a base symbol but meets
700 // the simple way of dealing with this, in that it is a temporary symbol in
701 // the same atom then it is assumed to be fully resolved. This is needed so
Eric Christopherd1e002a2011-09-08 22:17:40 +0000702 // a relocation entry is not created and so the static linker does not
Kevin Enderby5afc1902011-09-08 20:53:44 +0000703 // mess up the reference later.
704 else if(!FB.getAtom() &&
705 SA.isTemporary() && SA.isInSection() && &SecA == &SecB){
706 return true;
707 }
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000708 }
709
Rafael Espindolac3260672014-11-04 22:10:33 +0000710 // If they are not in the same section, we can't compute the diff.
711 if (&SecA != &SecB)
712 return false;
713
Rafael Espindolacfac75a2015-05-29 21:45:01 +0000714 const MCFragment *FA = SA.getFragment();
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000715
Benjamin Kramer0d46ccf2011-08-12 01:51:29 +0000716 // Bail if the symbol has no fragment.
717 if (!FA)
718 return false;
719
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000720 // If the atoms are the same, they are guaranteed to have the same address.
Duncan P. N. Exon Smith5f7c1f82015-05-16 00:48:58 +0000721 if (FA->getAtom() == FB.getAtom())
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000722 return true;
723
724 // Otherwise, we can't prove this is fully resolved.
725 return false;
726}
727
Matthias Braun177a4fc2017-12-14 00:12:46 +0000728static MachO::LoadCommandType getLCFromMCVM(MCVersionMinType Type) {
729 switch (Type) {
730 case MCVM_OSXVersionMin: return MachO::LC_VERSION_MIN_MACOSX;
731 case MCVM_IOSVersionMin: return MachO::LC_VERSION_MIN_IPHONEOS;
732 case MCVM_TvOSVersionMin: return MachO::LC_VERSION_MIN_TVOS;
733 case MCVM_WatchOSVersionMin: return MachO::LC_VERSION_MIN_WATCHOS;
734 }
735 llvm_unreachable("Invalid mc version min type");
736}
737
Peter Collingbourne0d4292f2018-05-21 18:23:50 +0000738uint64_t MachObjectWriter::writeObject(MCAssembler &Asm,
739 const MCAsmLayout &Layout) {
740 uint64_t StartOffset = W.OS.tell();
741
Rafael Espindolaa23cc6a2015-01-19 21:11:14 +0000742 // Compute symbol table information and bind symbol indices.
Jim Grosbacheafe4652015-06-04 23:25:54 +0000743 computeSymbolTable(Asm, LocalSymbolData, ExternalSymbolData,
Rafael Espindolaa23cc6a2015-01-19 21:11:14 +0000744 UndefinedSymbolData);
745
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000746 unsigned NumSections = Asm.size();
Matthias Braun177a4fc2017-12-14 00:12:46 +0000747 const MCAssembler::VersionInfoType &VersionInfo =
748 Layout.getAssembler().getVersionInfo();
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000749
750 // The section data starts after the header, the segment load command (and
751 // section headers) and the symbol table.
752 unsigned NumLoadCommands = 1;
753 uint64_t LoadCommandsSize = is64Bit() ?
Charles Davis55107282013-09-01 04:28:48 +0000754 sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64):
755 sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000756
Jim Grosbachd55fc3f2014-03-18 22:09:05 +0000757 // Add the deployment target version info load command size, if used.
758 if (VersionInfo.Major != 0) {
759 ++NumLoadCommands;
Matthias Braun177a4fc2017-12-14 00:12:46 +0000760 if (VersionInfo.EmitBuildVersion)
761 LoadCommandsSize += sizeof(MachO::build_version_command);
762 else
763 LoadCommandsSize += sizeof(MachO::version_min_command);
Jim Grosbachd55fc3f2014-03-18 22:09:05 +0000764 }
765
Daniel Dunbara94c3392013-01-18 01:26:07 +0000766 // Add the data-in-code load command size, if used.
767 unsigned NumDataRegions = Asm.getDataRegions().size();
768 if (NumDataRegions) {
769 ++NumLoadCommands;
Charles Davis55107282013-09-01 04:28:48 +0000770 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
Daniel Dunbara94c3392013-01-18 01:26:07 +0000771 }
772
Tim Northover1330ee32014-03-29 07:34:53 +0000773 // Add the loh load command size, if used.
774 uint64_t LOHRawSize = Asm.getLOHContainer().getEmitSize(*this, Layout);
Rui Ueyama3edb0ec2016-01-14 21:06:47 +0000775 uint64_t LOHSize = alignTo(LOHRawSize, is64Bit() ? 8 : 4);
Tim Northover1330ee32014-03-29 07:34:53 +0000776 if (LOHSize) {
777 ++NumLoadCommands;
778 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
779 }
780
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000781 // Add the symbol table load command sizes, if used.
782 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
783 UndefinedSymbolData.size();
784 if (NumSymbols) {
785 NumLoadCommands += 2;
Charles Davis55107282013-09-01 04:28:48 +0000786 LoadCommandsSize += (sizeof(MachO::symtab_command) +
787 sizeof(MachO::dysymtab_command));
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000788 }
789
Daniel Dunbara94c3392013-01-18 01:26:07 +0000790 // Add the linker option load commands sizes.
Benjamin Kramer5deb54f2015-06-04 21:17:27 +0000791 for (const auto &Option : Asm.getLinkerOptions()) {
Jim Grosbach3e965312012-05-18 19:12:01 +0000792 ++NumLoadCommands;
Benjamin Kramer5deb54f2015-06-04 21:17:27 +0000793 LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(Option, is64Bit());
Jim Grosbach3e965312012-05-18 19:12:01 +0000794 }
NAKAMURA Takumic36e7462015-09-22 11:14:39 +0000795
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000796 // Compute the total size of the section data, as well as its file size and vm
797 // size.
Charles Davis55107282013-09-01 04:28:48 +0000798 uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) :
799 sizeof(MachO::mach_header)) + LoadCommandsSize;
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000800 uint64_t SectionDataSize = 0;
801 uint64_t SectionDataFileSize = 0;
802 uint64_t VMSize = 0;
Rafael Espindola2dd8a672015-06-01 01:30:01 +0000803 for (const MCSection &Sec : Asm) {
Rafael Espindolaea3533b2015-05-26 02:00:36 +0000804 uint64_t Address = getSectionAddress(&Sec);
805 uint64_t Size = Layout.getSectionAddressSize(&Sec);
806 uint64_t FileSize = Layout.getSectionFileSize(&Sec);
807 FileSize += getPaddingSize(&Sec, Layout);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000808
809 VMSize = std::max(VMSize, Address + Size);
810
Rafael Espindola2dd8a672015-06-01 01:30:01 +0000811 if (Sec.isVirtualSection())
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000812 continue;
813
814 SectionDataSize = std::max(SectionDataSize, Address + Size);
815 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
816 }
817
818 // The section data is padded to 4 bytes.
819 //
820 // FIXME: Is this machine dependent?
821 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
822 SectionDataFileSize += SectionDataPadding;
823
824 // Write the prolog, starting with the header and load command...
Frederic Rissbfec0722015-08-26 05:09:46 +0000825 writeHeader(MachO::MH_OBJECT, NumLoadCommands, LoadCommandsSize,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000826 Asm.getSubsectionsViaSymbols());
Frederic Rissbfec0722015-08-26 05:09:46 +0000827 uint32_t Prot =
828 MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE;
829 writeSegmentLoadCommand("", NumSections, 0, VMSize, SectionDataStart,
830 SectionDataSize, Prot, Prot);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000831
832 // ... and then the section headers.
833 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
Frederic Rissbfec0722015-08-26 05:09:46 +0000834 for (const MCSection &Section : Asm) {
835 const auto &Sec = cast<MCSectionMachO>(Section);
Rafael Espindola2dd8a672015-06-01 01:30:01 +0000836 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000837 unsigned NumRelocs = Relocs.size();
Rafael Espindola2dd8a672015-06-01 01:30:01 +0000838 uint64_t SectionStart = SectionDataStart + getSectionAddress(&Sec);
Frederic Rissbfec0722015-08-26 05:09:46 +0000839 unsigned Flags = Sec.getTypeAndAttributes();
840 if (Sec.hasInstructions())
841 Flags |= MachO::S_ATTR_SOME_INSTRUCTIONS;
842 writeSection(Layout, Sec, getSectionAddress(&Sec), SectionStart, Flags,
843 RelocTableEnd, NumRelocs);
Charles Davis55107282013-09-01 04:28:48 +0000844 RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000845 }
846
Jim Grosbachd55fc3f2014-03-18 22:09:05 +0000847 // Write out the deployment target information, if it's available.
848 if (VersionInfo.Major != 0) {
Alex Lorenz6592c092018-12-14 01:14:10 +0000849 auto EncodeVersion = [](VersionTuple V) -> uint32_t {
850 assert(!V.empty() && "empty version");
851 unsigned Update = V.getSubminor() ? *V.getSubminor() : 0;
852 unsigned Minor = V.getMinor() ? *V.getMinor() : 0;
853 assert(Update < 256 && "unencodable update target version");
854 assert(Minor < 256 && "unencodable minor target version");
855 assert(V.getMajor() < 65536 && "unencodable major target version");
856 return Update | (Minor << 8) | (V.getMajor() << 16);
857 };
858 uint32_t EncodedVersion = EncodeVersion(
859 VersionTuple(VersionInfo.Major, VersionInfo.Minor, VersionInfo.Update));
860 uint32_t SDKVersion = !VersionInfo.SDKVersion.empty()
861 ? EncodeVersion(VersionInfo.SDKVersion)
862 : 0;
Matthias Braun177a4fc2017-12-14 00:12:46 +0000863 if (VersionInfo.EmitBuildVersion) {
864 // FIXME: Currently empty tools. Add clang version in the future.
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000865 W.write<uint32_t>(MachO::LC_BUILD_VERSION);
866 W.write<uint32_t>(sizeof(MachO::build_version_command));
867 W.write<uint32_t>(VersionInfo.TypeOrPlatform.Platform);
868 W.write<uint32_t>(EncodedVersion);
Alex Lorenz6592c092018-12-14 01:14:10 +0000869 W.write<uint32_t>(SDKVersion);
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000870 W.write<uint32_t>(0); // Empty tools list.
Matthias Braun177a4fc2017-12-14 00:12:46 +0000871 } else {
872 MachO::LoadCommandType LCType
873 = getLCFromMCVM(VersionInfo.TypeOrPlatform.Type);
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000874 W.write<uint32_t>(LCType);
875 W.write<uint32_t>(sizeof(MachO::version_min_command));
876 W.write<uint32_t>(EncodedVersion);
Alex Lorenz6592c092018-12-14 01:14:10 +0000877 W.write<uint32_t>(SDKVersion);
Tim Northover856a0382015-10-28 22:36:05 +0000878 }
Jim Grosbachd55fc3f2014-03-18 22:09:05 +0000879 }
880
Jim Grosbach3e965312012-05-18 19:12:01 +0000881 // Write the data-in-code load command, if used.
882 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
883 if (NumDataRegions) {
884 uint64_t DataRegionsOffset = RelocTableEnd;
885 uint64_t DataRegionsSize = NumDataRegions * 8;
Jim Grosbacheafe4652015-06-04 23:25:54 +0000886 writeLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset,
Jim Grosbach3e965312012-05-18 19:12:01 +0000887 DataRegionsSize);
888 }
889
Tim Northover1330ee32014-03-29 07:34:53 +0000890 // Write the loh load command, if used.
891 uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize;
892 if (LOHSize)
Jim Grosbacheafe4652015-06-04 23:25:54 +0000893 writeLinkeditLoadCommand(MachO::LC_LINKER_OPTIMIZATION_HINT,
Tim Northover1330ee32014-03-29 07:34:53 +0000894 DataInCodeTableEnd, LOHSize);
895
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000896 // Write the symbol table load command, if used.
897 if (NumSymbols) {
898 unsigned FirstLocalSymbol = 0;
899 unsigned NumLocalSymbols = LocalSymbolData.size();
900 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
901 unsigned NumExternalSymbols = ExternalSymbolData.size();
902 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
903 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
904 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
905 unsigned NumSymTabSymbols =
906 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
907 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
908 uint64_t IndirectSymbolOffset = 0;
909
910 // If used, the indirect symbols are written after the section data.
911 if (NumIndirectSymbols)
Tim Northover1330ee32014-03-29 07:34:53 +0000912 IndirectSymbolOffset = LOHTableEnd;
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000913
914 // The symbol table is written after the indirect symbol data.
Tim Northover1330ee32014-03-29 07:34:53 +0000915 uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize;
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000916
917 // The string table is written after symbol table.
918 uint64_t StringTableOffset =
Charles Davis55107282013-09-01 04:28:48 +0000919 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ?
920 sizeof(MachO::nlist_64) :
921 sizeof(MachO::nlist));
Jim Grosbacheafe4652015-06-04 23:25:54 +0000922 writeSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
Rafael Espindola2638e452016-10-04 22:43:25 +0000923 StringTableOffset, StringTable.getSize());
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000924
Jim Grosbacheafe4652015-06-04 23:25:54 +0000925 writeDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000926 FirstExternalSymbol, NumExternalSymbols,
927 FirstUndefinedSymbol, NumUndefinedSymbols,
928 IndirectSymbolOffset, NumIndirectSymbols);
929 }
930
Daniel Dunbara94c3392013-01-18 01:26:07 +0000931 // Write the linker options load commands.
Benjamin Kramer5deb54f2015-06-04 21:17:27 +0000932 for (const auto &Option : Asm.getLinkerOptions())
Jim Grosbacheafe4652015-06-04 23:25:54 +0000933 writeLinkerOptionsLoadCommand(Option);
Daniel Dunbara94c3392013-01-18 01:26:07 +0000934
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000935 // Write the actual section data.
Rafael Espindola2dd8a672015-06-01 01:30:01 +0000936 for (const MCSection &Sec : Asm) {
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000937 Asm.writeSectionData(W.OS, &Sec, Layout);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000938
Rafael Espindola2224f642015-05-26 02:17:21 +0000939 uint64_t Pad = getPaddingSize(&Sec, Layout);
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000940 W.OS.write_zeros(Pad);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000941 }
942
943 // Write the extra padding.
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000944 W.OS.write_zeros(SectionDataPadding);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000945
946 // Write the relocation entries.
Rafael Espindola2dd8a672015-06-01 01:30:01 +0000947 for (const MCSection &Sec : Asm) {
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000948 // Write the section relocation entries, in reverse order to match 'as'
949 // (approximately, the exact algorithm is more complicated than this).
Rafael Espindola2dd8a672015-06-01 01:30:01 +0000950 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
Benjamin Kramer5deb54f2015-06-04 21:17:27 +0000951 for (const RelAndSymbol &Rel : make_range(Relocs.rbegin(), Relocs.rend())) {
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000952 W.write<uint32_t>(Rel.MRE.r_word0);
953 W.write<uint32_t>(Rel.MRE.r_word1);
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000954 }
955 }
956
Jim Grosbach3e965312012-05-18 19:12:01 +0000957 // Write out the data-in-code region payload, if there is one.
958 for (MCAssembler::const_data_region_iterator
959 it = Asm.data_region_begin(), ie = Asm.data_region_end();
960 it != ie; ++it) {
961 const DataRegionData *Data = &(*it);
Duncan P. N. Exon Smith891fd532015-05-20 00:02:39 +0000962 uint64_t Start = getSymbolAddress(*Data->Start, Layout);
Gerolf Hoflehnera438b612018-02-12 07:19:05 +0000963 uint64_t End;
Fangrui Songaf7b1832018-07-30 19:41:25 +0000964 if (Data->End)
Gerolf Hoflehnera438b612018-02-12 07:19:05 +0000965 End = getSymbolAddress(*Data->End, Layout);
966 else
967 report_fatal_error("Data region not terminated");
968
Nicola Zaghen0818e782018-05-14 12:53:11 +0000969 LLVM_DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
970 << " start: " << Start << "(" << Data->Start->getName()
971 << ")"
972 << " end: " << End << "(" << Data->End->getName() << ")"
973 << " size: " << End - Start << "\n");
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000974 W.write<uint32_t>(Start);
975 W.write<uint16_t>(End - Start);
976 W.write<uint16_t>(Data->Kind);
Jim Grosbach3e965312012-05-18 19:12:01 +0000977 }
978
Tim Northover1330ee32014-03-29 07:34:53 +0000979 // Write out the loh commands, if there is one.
980 if (LOHSize) {
981#ifndef NDEBUG
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000982 unsigned Start = W.OS.tell();
Tim Northover1330ee32014-03-29 07:34:53 +0000983#endif
Jim Grosbach398f1752015-06-01 23:55:06 +0000984 Asm.getLOHContainer().emit(*this, Layout);
Tim Northover1330ee32014-03-29 07:34:53 +0000985 // Pad to a multiple of the pointer size.
Peter Collingbourne8e93a952018-05-21 18:17:42 +0000986 W.OS.write_zeros(OffsetToAlignment(LOHRawSize, is64Bit() ? 8 : 4));
987 assert(W.OS.tell() - Start == LOHSize);
Tim Northover1330ee32014-03-29 07:34:53 +0000988 }
989
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000990 // Write the symbol table data, if used.
991 if (NumSymbols) {
992 // Write the indirect symbol entries.
993 for (MCAssembler::const_indirect_symbol_iterator
994 it = Asm.indirect_symbol_begin(),
995 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
Alp Toker087ab612013-12-05 05:44:44 +0000996 // Indirect symbols in the non-lazy symbol pointer section have some
Bill Wendlingbbdffa92011-06-22 21:07:27 +0000997 // special handling.
998 const MCSectionMachO &Section =
Rafael Espindola2224f642015-05-26 02:17:21 +0000999 static_cast<const MCSectionMachO &>(*it->Section);
David Majnemer508e0c42014-03-07 07:36:05 +00001000 if (Section.getType() == MachO::S_NON_LAZY_SYMBOL_POINTERS) {
Bill Wendlingbbdffa92011-06-22 21:07:27 +00001001 // If this symbol is defined and internal, mark it as such.
Rafael Espindolacfac75a2015-05-29 21:45:01 +00001002 if (it->Symbol->isDefined() && !it->Symbol->isExternal()) {
Charles Davis55107282013-09-01 04:28:48 +00001003 uint32_t Flags = MachO::INDIRECT_SYMBOL_LOCAL;
Bill Wendlingbbdffa92011-06-22 21:07:27 +00001004 if (it->Symbol->isAbsolute())
Charles Davis55107282013-09-01 04:28:48 +00001005 Flags |= MachO::INDIRECT_SYMBOL_ABS;
Peter Collingbourne8e93a952018-05-21 18:17:42 +00001006 W.write<uint32_t>(Flags);
Bill Wendlingbbdffa92011-06-22 21:07:27 +00001007 continue;
1008 }
1009 }
1010
Peter Collingbourne8e93a952018-05-21 18:17:42 +00001011 W.write<uint32_t>(it->Symbol->getIndex());
Bill Wendlingbbdffa92011-06-22 21:07:27 +00001012 }
1013
1014 // FIXME: Check that offsets match computed ones.
1015
1016 // Write the symbol table entries.
Benjamin Kramer5deb54f2015-06-04 21:17:27 +00001017 for (auto *SymbolData :
1018 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
1019 for (MachSymbolData &Entry : *SymbolData)
Jim Grosbacheafe4652015-06-04 23:25:54 +00001020 writeNlist(Entry, Layout);
Bill Wendlingbbdffa92011-06-22 21:07:27 +00001021
1022 // Write the string table.
Peter Collingbourne8e93a952018-05-21 18:17:42 +00001023 StringTable.write(W.OS);
Bill Wendlingbbdffa92011-06-22 21:07:27 +00001024 }
Peter Collingbourne0d4292f2018-05-21 18:23:50 +00001025
1026 return W.OS.tell() - StartOffset;
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001027}
1028
Lang Hamese4713462017-10-10 16:28:07 +00001029std::unique_ptr<MCObjectWriter>
Lang Hames331cf982017-10-09 22:38:13 +00001030llvm::createMachObjectWriter(std::unique_ptr<MCMachObjectTargetWriter> MOTW,
1031 raw_pwrite_stream &OS, bool IsLittleEndian) {
Lang Hamese4713462017-10-10 16:28:07 +00001032 return llvm::make_unique<MachObjectWriter>(std::move(MOTW), OS,
1033 IsLittleEndian);
Daniel Dunbar2df4ceb2010-03-19 10:43:15 +00001034}