blob: 251fe5abbcfcbd556d48fad8ba428ad0d4d0bad2 [file] [log] [blame]
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +00001//===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +00006//
7//===----------------------------------------------------------------------===//
8
Eugene Zelenko1d435522017-02-07 23:02:00 +00009#include "llvm/ADT/DenseMap.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000010#include "llvm/ADT/Twine.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000011#include "llvm/ADT/iterator_range.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000012#include "llvm/BinaryFormat/MachO.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"
Francis Visoiu Mistrihc01140e2019-03-06 18:10:41 +000016#include "llvm/MC/MCContext.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000017#include "llvm/MC/MCDirectives.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000018#include "llvm/MC/MCExpr.h"
Craig Topper6e80c282012-03-26 06:58:25 +000019#include "llvm/MC/MCFixupKindInfo.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000020#include "llvm/MC/MCFragment.h"
21#include "llvm/MC/MCMachObjectWriter.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000022#include "llvm/MC/MCObjectWriter.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000023#include "llvm/MC/MCSection.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000024#include "llvm/MC/MCSectionMachO.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000025#include "llvm/MC/MCSymbol.h"
Pete Cooper916f79e2015-06-08 17:17:28 +000026#include "llvm/MC/MCSymbolMachO.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000027#include "llvm/MC/MCValue.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000028#include "llvm/Support/Casting.h"
Jim Grosbach4b63d2a2012-05-18 19:12:01 +000029#include "llvm/Support/Debug.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000030#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000032#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000033#include <algorithm>
34#include <cassert>
35#include <cstdint>
36#include <string>
37#include <utility>
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000038#include <vector>
Eugene Zelenko1d435522017-02-07 23:02:00 +000039
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000040using namespace llvm;
41
Chandler Carruthe96dd892014-04-21 22:55:11 +000042#define DEBUG_TYPE "mc"
43
Pedro Artigasb95c53e2012-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 Smith08b87262015-05-20 15:16:14 +000054bool MachObjectWriter::doesSymbolRequireExternRelocation(const MCSymbol &S) {
Daniel Dunbar7de31062010-05-10 23:15:13 +000055 // Undefined symbols are always extern.
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +000056 if (S.isUndefined())
Daniel Dunbar7de31062010-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 Cooper916f79e2015-06-08 17:17:28 +000061 if (cast<MCSymbolMachO>(S).isWeakDefinition())
Daniel Dunbar7de31062010-05-10 23:15:13 +000062 return true;
63
64 // Otherwise, we can use an internal relocation.
65 return false;
66}
67
Jim Grosbach28fcafb2011-06-24 23:44:37 +000068bool MachObjectWriter::
69MachSymbolData::operator<(const MachSymbolData &RHS) const {
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +000070 return Symbol->getName() < RHS.Symbol->getName();
Jim Grosbach28fcafb2011-06-24 23:44:37 +000071}
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000072
Jim Grosbach28fcafb2011-06-24 23:44:37 +000073bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
74 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
75 (MCFixupKind) Kind);
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000076
Jim Grosbach28fcafb2011-06-24 23:44:37 +000077 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
78}
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000079
Jim Grosbach28fcafb2011-06-24 23:44:37 +000080uint64_t MachObjectWriter::getFragmentAddress(const MCFragment *Fragment,
81 const MCAsmLayout &Layout) const {
Rafael Espindola079027e2015-05-26 00:52:18 +000082 return getSectionAddress(Fragment->getParent()) +
Rafael Espindola7549f872015-05-26 00:36:57 +000083 Layout.getFragmentOffset(Fragment);
Jim Grosbach28fcafb2011-06-24 23:44:37 +000084}
Bill Wendlingeb872e02011-06-22 21:07:27 +000085
Duncan P. N. Exon Smith99d8a8e2015-05-20 00:02:39 +000086uint64_t MachObjectWriter::getSymbolAddress(const MCSymbol &S,
Bill Wendlingeb872e02011-06-22 21:07:27 +000087 const MCAsmLayout &Layout) const {
Bill Wendlingeb872e02011-06-22 21:07:27 +000088 // If this is a variable, then recursively evaluate now.
89 if (S.isVariable()) {
Jim Grosbachd96ef192012-09-13 23:11:25 +000090 if (const MCConstantExpr *C =
91 dyn_cast<const MCConstantExpr>(S.getVariableValue()))
92 return C->getValue();
93
Bill Wendlingeb872e02011-06-22 21:07:27 +000094 MCValue Target;
Jim Grosbach13760bd2015-05-30 01:25:56 +000095 if (!S.getVariableValue()->evaluateAsRelocatable(Target, &Layout, nullptr))
Bill Wendlingeb872e02011-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 Smith99d8a8e2015-05-20 00:02:39 +0000109 Address += getSymbolAddress(Target.getSymA()->getSymbol(), Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000110 if (Target.getSymB())
Duncan P. N. Exon Smith99d8a8e2015-05-20 00:02:39 +0000111 Address += getSymbolAddress(Target.getSymB()->getSymbol(), Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000112 return Address;
113 }
114
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000115 return getSectionAddress(S.getFragment()->getParent()) +
Duncan P. N. Exon Smith2a404832015-05-19 23:53:20 +0000116 Layout.getSymbolOffset(S);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000117}
118
Rafael Espindola61e724a2015-05-26 01:15:30 +0000119uint64_t MachObjectWriter::getPaddingSize(const MCSection *Sec,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000120 const MCAsmLayout &Layout) const {
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000121 uint64_t EndAddr = getSectionAddress(Sec) + Layout.getSectionAddressSize(Sec);
Rafael Espindola61e724a2015-05-26 01:15:30 +0000122 unsigned Next = Sec->getLayoutOrder() + 1;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000123 if (Next >= Layout.getSectionOrder().size())
124 return 0;
125
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000126 const MCSection &NextSec = *Layout.getSectionOrder()[Next];
127 if (NextSec.isVirtualSection())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000128 return 0;
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000129 return OffsetToAlignment(EndAddr, NextSec.getAlignment());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000130}
131
Frederic Riss75c0c702015-08-26 05:09:46 +0000132void MachObjectWriter::writeHeader(MachO::HeaderFileType Type,
133 unsigned NumLoadCommands,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000134 unsigned LoadCommandsSize,
135 bool SubsectionsViaSymbols) {
136 uint32_t Flags = 0;
137
138 if (SubsectionsViaSymbols)
Charles Davis8bdfafd2013-09-01 04:28:48 +0000139 Flags |= MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000140
141 // struct mach_header (28 bytes) or
142 // struct mach_header_64 (32 bytes)
143
Peter Collingbournef17b1492018-05-21 18:17:42 +0000144 uint64_t Start = W.OS.tell();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000145 (void) Start;
146
Peter Collingbournef17b1492018-05-21 18:17:42 +0000147 W.write<uint32_t>(is64Bit() ? MachO::MH_MAGIC_64 : MachO::MH_MAGIC);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000148
Peter Collingbournef17b1492018-05-21 18:17:42 +0000149 W.write<uint32_t>(TargetObjectWriter->getCPUType());
150 W.write<uint32_t>(TargetObjectWriter->getCPUSubtype());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000151
Peter Collingbournef17b1492018-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 Wendlingeb872e02011-06-22 21:07:27 +0000156 if (is64Bit())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000157 W.write<uint32_t>(0); // reserved
Bill Wendlingeb872e02011-06-22 21:07:27 +0000158
Peter Collingbournef17b1492018-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 Wendlingeb872e02011-06-22 21:07:27 +0000167}
168
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000169/// writeSegmentLoadCommand - Write a segment load command.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000170///
Dmitri Gribenko5485acd2012-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 Riss75c0c702015-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 Wendlingeb872e02011-06-22 21:07:27 +0000177 // struct segment_command (56 bytes) or
178 // struct segment_command_64 (72 bytes)
179
Peter Collingbournef17b1492018-05-21 18:17:42 +0000180 uint64_t Start = W.OS.tell();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000181 (void) Start;
182
183 unsigned SegmentLoadCommandSize =
Charles Davis8bdfafd2013-09-01 04:28:48 +0000184 is64Bit() ? sizeof(MachO::segment_command_64):
185 sizeof(MachO::segment_command);
Peter Collingbournef17b1492018-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 Davis8bdfafd2013-09-01 04:28:48 +0000188 NumSections * (is64Bit() ? sizeof(MachO::section_64) :
189 sizeof(MachO::section)));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000190
Peter Collingbournef17b1492018-05-21 18:17:42 +0000191 writeWithPadding(Name, 16);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000192 if (is64Bit()) {
Peter Collingbournef17b1492018-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 Wendlingeb872e02011-06-22 21:07:27 +0000197 } else {
Peter Collingbournef17b1492018-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 Wendlingeb872e02011-06-22 21:07:27 +0000202 }
Nick Kledzikfe6813f2013-09-04 23:53:44 +0000203 // maxprot
Peter Collingbournef17b1492018-05-21 18:17:42 +0000204 W.write<uint32_t>(MaxProt);
Nick Kledzikfe6813f2013-09-04 23:53:44 +0000205 // initprot
Peter Collingbournef17b1492018-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 Wendlingeb872e02011-06-22 21:07:27 +0000209
Peter Collingbournef17b1492018-05-21 18:17:42 +0000210 assert(W.OS.tell() - Start == SegmentLoadCommandSize);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000211}
212
Frederic Riss75c0c702015-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 Wendlingeb872e02011-06-22 21:07:27 +0000216 uint64_t RelocationsStart,
217 unsigned NumRelocations) {
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000218 uint64_t SectionSize = Layout.getSectionAddressSize(&Sec);
Rafael Espindola61e724a2015-05-26 01:15:30 +0000219 const MCSectionMachO &Section = cast<MCSectionMachO>(Sec);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000220
221 // The offset is unused for virtual sections.
Rafael Espindola967d6a62015-05-21 21:02:35 +0000222 if (Section.isVirtualSection()) {
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000223 assert(Layout.getSectionFileSize(&Sec) == 0 && "Invalid file size!");
Bill Wendlingeb872e02011-06-22 21:07:27 +0000224 FileOffset = 0;
225 }
226
227 // struct section (68 bytes) or
228 // struct section_64 (80 bytes)
229
Peter Collingbournef17b1492018-05-21 18:17:42 +0000230 uint64_t Start = W.OS.tell();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000231 (void) Start;
232
Peter Collingbournef17b1492018-05-21 18:17:42 +0000233 writeWithPadding(Section.getSectionName(), 16);
234 writeWithPadding(Section.getSegmentName(), 16);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000235 if (is64Bit()) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000236 W.write<uint64_t>(VMAddr); // address
237 W.write<uint64_t>(SectionSize); // size
Bill Wendlingeb872e02011-06-22 21:07:27 +0000238 } else {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000239 W.write<uint32_t>(VMAddr); // address
240 W.write<uint32_t>(SectionSize); // size
Bill Wendlingeb872e02011-06-22 21:07:27 +0000241 }
Peter Collingbournef17b1492018-05-21 18:17:42 +0000242 W.write<uint32_t>(FileOffset);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000243
Rafael Espindola967d6a62015-05-21 21:02:35 +0000244 assert(isPowerOf2_32(Section.getAlignment()) && "Invalid alignment!");
Peter Collingbournef17b1492018-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 Wendlingeb872e02011-06-22 21:07:27 +0000251 if (is64Bit())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000252 W.write<uint32_t>(0); // reserved3
Bill Wendlingeb872e02011-06-22 21:07:27 +0000253
Peter Collingbournef17b1492018-05-21 18:17:42 +0000254 assert(W.OS.tell() - Start ==
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000255 (is64Bit() ? sizeof(MachO::section_64) : sizeof(MachO::section)));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000256}
257
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000258void MachObjectWriter::writeSymtabLoadCommand(uint32_t SymbolOffset,
Bill Wendlingeb872e02011-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 Collingbournef17b1492018-05-21 18:17:42 +0000264 uint64_t Start = W.OS.tell();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000265 (void) Start;
266
Peter Collingbournef17b1492018-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 Wendlingeb872e02011-06-22 21:07:27 +0000273
Peter Collingbournef17b1492018-05-21 18:17:42 +0000274 assert(W.OS.tell() - Start == sizeof(MachO::symtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000275}
276
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000277void MachObjectWriter::writeDysymtabLoadCommand(uint32_t FirstLocalSymbol,
Bill Wendlingeb872e02011-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 Collingbournef17b1492018-05-21 18:17:42 +0000287 uint64_t Start = W.OS.tell();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000288 (void) Start;
289
Peter Collingbournef17b1492018-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 Wendlingeb872e02011-06-22 21:07:27 +0000310
Peter Collingbournef17b1492018-05-21 18:17:42 +0000311 assert(W.OS.tell() - Start == sizeof(MachO::dysymtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000312}
313
Tim Northovereaef0742014-05-30 13:22:59 +0000314MachObjectWriter::MachSymbolData *
315MachObjectWriter::findSymbolData(const MCSymbol &Sym) {
Benjamin Kramer1ec70d82015-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 Northovereaef0742014-05-30 13:22:59 +0000321
322 return nullptr;
323}
324
Rafael Espindola7f4e07b2015-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 Grosbach56ed0bb2015-06-04 23:25:54 +0000337void MachObjectWriter::writeNlist(MachSymbolData &MSD,
Bill Wendling21162212011-06-23 00:09:43 +0000338 const MCAsmLayout &Layout) {
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +0000339 const MCSymbol *Symbol = MSD.Symbol;
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000340 const MCSymbol &Data = *Symbol;
Rafael Espindola7f4e07b2015-04-17 12:28:43 +0000341 const MCSymbol *AliasedSymbol = &findAliasedSymbol(*Symbol);
Tim Northovereaef0742014-05-30 13:22:59 +0000342 uint8_t SectionIndex = MSD.SectionIndex;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000343 uint8_t Type = 0;
Jim Grosbacha3171602011-08-09 22:12:37 +0000344 uint64_t Address = 0;
Tim Northovereaef0742014-05-30 13:22:59 +0000345 bool IsAlias = Symbol != AliasedSymbol;
346
Duncan P. N. Exon Smith24f47752015-05-21 00:39:24 +0000347 const MCSymbol &OrigSymbol = *Symbol;
Tim Northovereaef0742014-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 Hames1b640e02016-03-15 01:43:05 +0000354 // FIXME: Should this update Data as well?
Tim Northovereaef0742014-05-30 13:22:59 +0000355 }
Bill Wendlingeb872e02011-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 Northovereaef0742014-05-30 13:22:59 +0000360 if (IsAlias && Symbol->isUndefined())
361 Type = MachO::N_INDR;
362 else if (Symbol->isUndefined())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000363 Type = MachO::N_UNDF;
Tim Northovereaef0742014-05-30 13:22:59 +0000364 else if (Symbol->isAbsolute())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000365 Type = MachO::N_ABS;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000366 else
Charles Davis8bdfafd2013-09-01 04:28:48 +0000367 Type = MachO::N_SECT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000368
369 // FIXME: Set STAB bits.
370
371 if (Data.isPrivateExtern())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000372 Type |= MachO::N_PEXT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000373
374 // Set external bit.
Tim Northovereaef0742014-05-30 13:22:59 +0000375 if (Data.isExternal() || (!IsAlias && Symbol->isUndefined()))
Charles Davis8bdfafd2013-09-01 04:28:48 +0000376 Type |= MachO::N_EXT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000377
378 // Compute the symbol address.
Tim Northovereaef0742014-05-30 13:22:59 +0000379 if (IsAlias && Symbol->isUndefined())
380 Address = AliaseeInfo->StringIndex;
381 else if (Symbol->isDefined())
Duncan P. N. Exon Smith24f47752015-05-21 00:39:24 +0000382 Address = getSymbolAddress(OrigSymbol, Layout);
Rafael Espindola14672502015-05-29 17:48:04 +0000383 else if (Symbol->isCommon()) {
Bill Wendlingeb872e02011-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 Espindola14672502015-05-29 17:48:04 +0000386 Address = Symbol->getCommonSize();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000387 }
388
389 // struct nlist (12 bytes)
390
Peter Collingbournef17b1492018-05-21 18:17:42 +0000391 W.write<uint32_t>(MSD.StringIndex);
392 W.OS << char(Type);
393 W.OS << char(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.
Lang Hames1b640e02016-03-15 01:43:05 +0000397 bool EncodeAsAltEntry =
398 IsAlias && cast<MCSymbolMachO>(OrigSymbol).isAltEntry();
Peter Collingbournef17b1492018-05-21 18:17:42 +0000399 W.write<uint16_t>(cast<MCSymbolMachO>(Symbol)->getEncodedFlags(EncodeAsAltEntry));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000400 if (is64Bit())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000401 W.write<uint64_t>(Address);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000402 else
Peter Collingbournef17b1492018-05-21 18:17:42 +0000403 W.write<uint32_t>(Address);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000404}
405
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000406void MachObjectWriter::writeLinkeditLoadCommand(uint32_t Type,
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000407 uint32_t DataOffset,
408 uint32_t DataSize) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000409 uint64_t Start = W.OS.tell();
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000410 (void) Start;
411
Peter Collingbournef17b1492018-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 Grosbach4b63d2a2012-05-18 19:12:01 +0000416
Peter Collingbournef17b1492018-05-21 18:17:42 +0000417 assert(W.OS.tell() - Start == sizeof(MachO::linkedit_data_command));
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000418}
419
Daniel Dunbareec0f322013-01-18 01:26:07 +0000420static unsigned ComputeLinkerOptionsLoadCommandSize(
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000421 const std::vector<std::string> &Options, bool is64Bit)
Daniel Dunbareec0f322013-01-18 01:26:07 +0000422{
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +0000423 unsigned Size = sizeof(MachO::linker_option_command);
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000424 for (const std::string &Option : Options)
425 Size += Option.size() + 1;
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000426 return alignTo(Size, is64Bit ? 8 : 4);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000427}
428
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000429void MachObjectWriter::writeLinkerOptionsLoadCommand(
Daniel Dunbareec0f322013-01-18 01:26:07 +0000430 const std::vector<std::string> &Options)
431{
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000432 unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit());
Peter Collingbournef17b1492018-05-21 18:17:42 +0000433 uint64_t Start = W.OS.tell();
Daniel Dunbareec0f322013-01-18 01:26:07 +0000434 (void) Start;
435
Peter Collingbournef17b1492018-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 Enderbyd0b6b7f2014-12-18 00:53:40 +0000439 uint64_t BytesWritten = sizeof(MachO::linker_option_command);
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000440 for (const std::string &Option : Options) {
Daniel Dunbareec0f322013-01-18 01:26:07 +0000441 // Write each string, including the null byte.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000442 W.OS << Option << '\0';
Daniel Dunbareec0f322013-01-18 01:26:07 +0000443 BytesWritten += Option.size() + 1;
444 }
445
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000446 // Pad to a multiple of the pointer size.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000447 W.OS.write_zeros(OffsetToAlignment(BytesWritten, is64Bit() ? 8 : 4));
Daniel Dunbareec0f322013-01-18 01:26:07 +0000448
Peter Collingbournef17b1492018-05-21 18:17:42 +0000449 assert(W.OS.tell() - Start == Size);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000450}
451
Francis Visoiu Mistrihc01140e2019-03-06 18:10:41 +0000452static bool isFixupTargetValid(const MCValue &Target) {
453 // Target is (LHS - RHS + cst).
454 // We don't support the form where LHS is null: -RHS + cst
455 if (!Target.getSymA() && Target.getSymB())
456 return false;
457 return true;
458}
459
Jim Grosbach36e60e92015-06-04 22:24:41 +0000460void MachObjectWriter::recordRelocation(MCAssembler &Asm,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000461 const MCAsmLayout &Layout,
462 const MCFragment *Fragment,
Rafael Espindola26585542015-01-19 21:11:14 +0000463 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000464 uint64_t &FixedValue) {
Francis Visoiu Mistrihc01140e2019-03-06 18:10:41 +0000465 if (!isFixupTargetValid(Target)) {
466 Asm.getContext().reportError(Fixup.getLoc(),
467 "unsupported relocation expression");
468 return;
469 }
470
Jim Grosbach36e60e92015-06-04 22:24:41 +0000471 TargetObjectWriter->recordRelocation(this, Asm, Layout, Fragment, Fixup,
Jim Grosbach28fcafb2011-06-24 23:44:37 +0000472 Target, FixedValue);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000473}
474
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000475void MachObjectWriter::bindIndirectSymbols(MCAssembler &Asm) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000476 // This is the point where 'as' creates actual symbols for indirect symbols
477 // (in the following two passes). It would be easier for us to do this sooner
478 // when we see the attribute, but that makes getting the order in the symbol
479 // table much more complicated than it is worth.
480 //
481 // FIXME: Revisit this when the dust settles.
482
Kevin Enderby3aeada22013-08-28 17:50:59 +0000483 // Report errors for use of .indirect_symbol not in a symbol pointer section
484 // or stub section.
485 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
486 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000487 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
Kevin Enderby3aeada22013-08-28 17:50:59 +0000488
David Majnemer7b583052014-03-07 07:36:05 +0000489 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
490 Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
Tim Northover5c3140f2016-04-25 21:12:04 +0000491 Section.getType() != MachO::S_THREAD_LOCAL_VARIABLE_POINTERS &&
David Majnemer7b583052014-03-07 07:36:05 +0000492 Section.getType() != MachO::S_SYMBOL_STUBS) {
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +0000493 MCSymbol &Symbol = *it->Symbol;
494 report_fatal_error("indirect symbol '" + Symbol.getName() +
495 "' not in a symbol pointer or stub section");
Kevin Enderby3aeada22013-08-28 17:50:59 +0000496 }
497 }
498
Alp Tokerf907b892013-12-05 05:44:44 +0000499 // Bind non-lazy symbol pointers first.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000500 unsigned IndirectIndex = 0;
501 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
502 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000503 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000504
Tim Northover43978372016-04-26 18:29:16 +0000505 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
506 Section.getType() != MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
Bill Wendlingeb872e02011-06-22 21:07:27 +0000507 continue;
508
509 // Initialize the section indirect symbol base, if necessary.
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000510 IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000511
Rafael Espindolab5d316b2015-05-29 20:21:02 +0000512 Asm.registerSymbol(*it->Symbol);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000513 }
514
515 // Then lazy symbol pointers and symbol stubs.
516 IndirectIndex = 0;
517 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
518 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000519 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000520
David Majnemer7b583052014-03-07 07:36:05 +0000521 if (Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
522 Section.getType() != MachO::S_SYMBOL_STUBS)
Bill Wendlingeb872e02011-06-22 21:07:27 +0000523 continue;
524
525 // Initialize the section indirect symbol base, if necessary.
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000526 IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000527
528 // Set the symbol type to undefined lazy, but only on construction.
529 //
530 // FIXME: Do not hardcode.
531 bool Created;
Rafael Espindolab5d316b2015-05-29 20:21:02 +0000532 Asm.registerSymbol(*it->Symbol, &Created);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000533 if (Created)
Pete Cooper916f79e2015-06-08 17:17:28 +0000534 cast<MCSymbolMachO>(it->Symbol)->setReferenceTypeUndefinedLazy(true);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000535 }
536}
537
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000538/// computeSymbolTable - Compute the symbol table data
539void MachObjectWriter::computeSymbolTable(
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000540 MCAssembler &Asm, std::vector<MachSymbolData> &LocalSymbolData,
541 std::vector<MachSymbolData> &ExternalSymbolData,
542 std::vector<MachSymbolData> &UndefinedSymbolData) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000543 // Build section lookup table.
544 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
545 unsigned Index = 1;
546 for (MCAssembler::iterator it = Asm.begin(),
547 ie = Asm.end(); it != ie; ++it, ++Index)
Rafael Espindolaa554c052015-05-25 23:14:17 +0000548 SectionIndexMap[&*it] = Index;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000549 assert(Index <= 256 && "Too many sections!");
550
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000551 // Build the string table.
Duncan P. N. Exon Smithf48de1c2015-05-16 00:35:24 +0000552 for (const MCSymbol &Symbol : Asm.symbols()) {
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000553 if (!Asm.isSymbolLinkerVisible(Symbol))
554 continue;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000555
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000556 StringTable.add(Symbol.getName());
557 }
Rafael Espindola21956e42015-10-23 21:48:05 +0000558 StringTable.finalize();
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000559
560 // Build the symbol arrays but only for non-local symbols.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000561 //
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000562 // The particular order that we collect and then sort the symbols is chosen to
563 // match 'as'. Even though it doesn't matter for correctness, this is
564 // important for letting us diff .o files.
Duncan P. N. Exon Smithf48de1c2015-05-16 00:35:24 +0000565 for (const MCSymbol &Symbol : Asm.symbols()) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000566 // Ignore non-linker visible symbols.
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000567 if (!Asm.isSymbolLinkerVisible(Symbol))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000568 continue;
569
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000570 if (!Symbol.isExternal() && !Symbol.isUndefined())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000571 continue;
572
Bill Wendlingeb872e02011-06-22 21:07:27 +0000573 MachSymbolData MSD;
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +0000574 MSD.Symbol = &Symbol;
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000575 MSD.StringIndex = StringTable.getOffset(Symbol.getName());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000576
577 if (Symbol.isUndefined()) {
578 MSD.SectionIndex = 0;
579 UndefinedSymbolData.push_back(MSD);
580 } else if (Symbol.isAbsolute()) {
581 MSD.SectionIndex = 0;
582 ExternalSymbolData.push_back(MSD);
583 } else {
584 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
585 assert(MSD.SectionIndex && "Invalid section index!");
586 ExternalSymbolData.push_back(MSD);
587 }
588 }
589
590 // Now add the data for local symbols.
Duncan P. N. Exon Smithf48de1c2015-05-16 00:35:24 +0000591 for (const MCSymbol &Symbol : Asm.symbols()) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000592 // Ignore non-linker visible symbols.
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000593 if (!Asm.isSymbolLinkerVisible(Symbol))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000594 continue;
595
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000596 if (Symbol.isExternal() || Symbol.isUndefined())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000597 continue;
598
Bill Wendlingeb872e02011-06-22 21:07:27 +0000599 MachSymbolData MSD;
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +0000600 MSD.Symbol = &Symbol;
Daniel Jasper41de8022015-06-23 11:31:32 +0000601 MSD.StringIndex = StringTable.getOffset(Symbol.getName());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000602
603 if (Symbol.isAbsolute()) {
604 MSD.SectionIndex = 0;
605 LocalSymbolData.push_back(MSD);
606 } else {
607 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
608 assert(MSD.SectionIndex && "Invalid section index!");
609 LocalSymbolData.push_back(MSD);
610 }
611 }
612
613 // External and undefined symbols are required to be in lexicographic order.
Fangrui Song0cac7262018-09-27 02:13:45 +0000614 llvm::sort(ExternalSymbolData);
615 llvm::sort(UndefinedSymbolData);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000616
617 // Set the symbol indices.
618 Index = 0;
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000619 for (auto *SymbolData :
620 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
621 for (MachSymbolData &Entry : *SymbolData)
622 Entry.Symbol->setIndex(Index++);
Rafael Espindola26585542015-01-19 21:11:14 +0000623
Rafael Espindolaa554c052015-05-25 23:14:17 +0000624 for (const MCSection &Section : Asm) {
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000625 for (RelAndSymbol &Rel : Relocations[&Section]) {
Rafael Espindola26585542015-01-19 21:11:14 +0000626 if (!Rel.Sym)
627 continue;
628
629 // Set the Index and the IsExtern bit.
Duncan P. N. Exon Smith1247bbd2015-05-22 05:54:01 +0000630 unsigned Index = Rel.Sym->getIndex();
Rafael Espindola26585542015-01-19 21:11:14 +0000631 assert(isInt<24>(Index));
Peter Collingbournef17b1492018-05-21 18:17:42 +0000632 if (W.Endian == support::little)
Justin Bognerd4e08a02015-05-14 23:54:49 +0000633 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & (~0U << 24)) | Index | (1 << 27);
Rafael Espindola26585542015-01-19 21:11:14 +0000634 else
635 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & 0xff) | Index << 8 | (1 << 4);
636 }
637 }
Bill Wendlingeb872e02011-06-22 21:07:27 +0000638}
639
640void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
641 const MCAsmLayout &Layout) {
642 uint64_t StartAddress = 0;
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000643 for (const MCSection *Sec : Layout.getSectionOrder()) {
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000644 StartAddress = alignTo(StartAddress, Sec->getAlignment());
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000645 SectionAddress[Sec] = StartAddress;
646 StartAddress += Layout.getSectionAddressSize(Sec);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000647
648 // Explicitly pad the section to match the alignment requirements of the
649 // following one. This is for 'gas' compatibility, it shouldn't
650 /// strictly be necessary.
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000651 StartAddress += getPaddingSize(Sec, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000652 }
653}
654
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000655void MachObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
Bill Wendling21162212011-06-23 00:09:43 +0000656 const MCAsmLayout &Layout) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000657 computeSectionAddresses(Asm, Layout);
658
659 // Create symbol data for any indirect symbols.
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000660 bindIndirectSymbols(Asm);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000661}
662
Jim Grosbach36e60e92015-06-04 22:24:41 +0000663bool MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
Rafael Espindolae3a20f52015-10-05 12:07:05 +0000664 const MCAssembler &Asm, const MCSymbol &A, const MCSymbol &B,
665 bool InSet) const {
666 // FIXME: We don't handle things like
667 // foo = .
668 // creating atoms.
669 if (A.isVariable() || B.isVariable())
670 return false;
671 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, A, B,
672 InSet);
673}
674
675bool MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
Duncan P. N. Exon Smithd81ba532015-05-16 01:01:55 +0000676 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
Rafael Espindola35d61892015-04-17 21:15:17 +0000677 bool InSet, bool IsPCRel) const {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000678 if (InSet)
679 return true;
680
681 // The effective address is
682 // addr(atom(A)) + offset(A)
683 // - addr(atom(B)) - offset(B)
684 // and the offsets are not relocatable, so the fixup is fully resolved when
685 // addr(atom(A)) - addr(atom(B)) == 0.
Duncan P. N. Exon Smithd81ba532015-05-16 01:01:55 +0000686 const MCSymbol &SA = findAliasedSymbol(SymA);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000687 const MCSection &SecA = SA.getSection();
Rafael Espindola7549f872015-05-26 00:36:57 +0000688 const MCSection &SecB = *FB.getParent();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000689
690 if (IsPCRel) {
691 // The simple (Darwin, except on x86_64) way of dealing with this was to
692 // assume that any reference to a temporary symbol *must* be a temporary
693 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
694 // relocation to a temporary symbol (in the same section) is fully
695 // resolved. This also works in conjunction with absolutized .set, which
696 // requires the compiler to use .set to absolutize the differences between
697 // symbols which the compiler knows to be assembly time constants, so we
698 // don't need to worry about considering symbol differences fully resolved.
Jim Grosbachd6ae4ba2011-12-07 19:46:59 +0000699 //
700 // If the file isn't using sub-sections-via-symbols, we can make the
701 // same assumptions about any symbol that we normally make about
702 // assembler locals.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000703
Rafael Espindolaa063bdd2014-03-11 21:22:57 +0000704 bool hasReliableSymbolDifference = isX86_64();
705 if (!hasReliableSymbolDifference) {
Jim Grosbach40455072012-01-17 22:14:39 +0000706 if (!SA.isInSection() || &SecA != &SecB ||
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000707 (!SA.isTemporary() && FB.getAtom() != SA.getFragment()->getAtom() &&
Jim Grosbach35bc8f92012-01-24 21:45:25 +0000708 Asm.getSubsectionsViaSymbols()))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000709 return false;
710 return true;
711 }
Kevin Enderby7b46bb82011-09-08 20:53:44 +0000712 // For Darwin x86_64, there is one special case when the reference IsPCRel.
713 // If the fragment with the reference does not have a base symbol but meets
714 // the simple way of dealing with this, in that it is a temporary symbol in
715 // the same atom then it is assumed to be fully resolved. This is needed so
Eric Christopher460be992011-09-08 22:17:40 +0000716 // a relocation entry is not created and so the static linker does not
Kevin Enderby7b46bb82011-09-08 20:53:44 +0000717 // mess up the reference later.
718 else if(!FB.getAtom() &&
719 SA.isTemporary() && SA.isInSection() && &SecA == &SecB){
720 return true;
721 }
Bill Wendlingeb872e02011-06-22 21:07:27 +0000722 }
723
Rafael Espindolabfd0f012014-11-04 22:10:33 +0000724 // If they are not in the same section, we can't compute the diff.
725 if (&SecA != &SecB)
726 return false;
727
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000728 const MCFragment *FA = SA.getFragment();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000729
Benjamin Kramer91ea5112011-08-12 01:51:29 +0000730 // Bail if the symbol has no fragment.
731 if (!FA)
732 return false;
733
Bill Wendlingeb872e02011-06-22 21:07:27 +0000734 // If the atoms are the same, they are guaranteed to have the same address.
Duncan P. N. Exon Smith09bfa582015-05-16 00:48:58 +0000735 if (FA->getAtom() == FB.getAtom())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000736 return true;
737
738 // Otherwise, we can't prove this is fully resolved.
739 return false;
740}
741
Matthias Braun0148c882017-12-14 00:12:46 +0000742static MachO::LoadCommandType getLCFromMCVM(MCVersionMinType Type) {
743 switch (Type) {
744 case MCVM_OSXVersionMin: return MachO::LC_VERSION_MIN_MACOSX;
745 case MCVM_IOSVersionMin: return MachO::LC_VERSION_MIN_IPHONEOS;
746 case MCVM_TvOSVersionMin: return MachO::LC_VERSION_MIN_TVOS;
747 case MCVM_WatchOSVersionMin: return MachO::LC_VERSION_MIN_WATCHOS;
748 }
749 llvm_unreachable("Invalid mc version min type");
750}
751
Peter Collingbourne438390f2018-05-21 18:23:50 +0000752uint64_t MachObjectWriter::writeObject(MCAssembler &Asm,
753 const MCAsmLayout &Layout) {
754 uint64_t StartOffset = W.OS.tell();
755
Rafael Espindola26585542015-01-19 21:11:14 +0000756 // Compute symbol table information and bind symbol indices.
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000757 computeSymbolTable(Asm, LocalSymbolData, ExternalSymbolData,
Rafael Espindola26585542015-01-19 21:11:14 +0000758 UndefinedSymbolData);
759
Bill Wendlingeb872e02011-06-22 21:07:27 +0000760 unsigned NumSections = Asm.size();
Matthias Braun0148c882017-12-14 00:12:46 +0000761 const MCAssembler::VersionInfoType &VersionInfo =
762 Layout.getAssembler().getVersionInfo();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000763
764 // The section data starts after the header, the segment load command (and
765 // section headers) and the symbol table.
766 unsigned NumLoadCommands = 1;
767 uint64_t LoadCommandsSize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +0000768 sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64):
769 sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000770
Jim Grosbach448334a2014-03-18 22:09:05 +0000771 // Add the deployment target version info load command size, if used.
772 if (VersionInfo.Major != 0) {
773 ++NumLoadCommands;
Matthias Braun0148c882017-12-14 00:12:46 +0000774 if (VersionInfo.EmitBuildVersion)
775 LoadCommandsSize += sizeof(MachO::build_version_command);
776 else
777 LoadCommandsSize += sizeof(MachO::version_min_command);
Jim Grosbach448334a2014-03-18 22:09:05 +0000778 }
779
Daniel Dunbareec0f322013-01-18 01:26:07 +0000780 // Add the data-in-code load command size, if used.
781 unsigned NumDataRegions = Asm.getDataRegions().size();
782 if (NumDataRegions) {
783 ++NumLoadCommands;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000784 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000785 }
786
Tim Northover53d32512014-03-29 07:34:53 +0000787 // Add the loh load command size, if used.
788 uint64_t LOHRawSize = Asm.getLOHContainer().getEmitSize(*this, Layout);
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000789 uint64_t LOHSize = alignTo(LOHRawSize, is64Bit() ? 8 : 4);
Tim Northover53d32512014-03-29 07:34:53 +0000790 if (LOHSize) {
791 ++NumLoadCommands;
792 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
793 }
794
Bill Wendlingeb872e02011-06-22 21:07:27 +0000795 // Add the symbol table load command sizes, if used.
796 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
797 UndefinedSymbolData.size();
798 if (NumSymbols) {
799 NumLoadCommands += 2;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000800 LoadCommandsSize += (sizeof(MachO::symtab_command) +
801 sizeof(MachO::dysymtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000802 }
803
Daniel Dunbareec0f322013-01-18 01:26:07 +0000804 // Add the linker option load commands sizes.
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000805 for (const auto &Option : Asm.getLinkerOptions()) {
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000806 ++NumLoadCommands;
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000807 LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(Option, is64Bit());
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000808 }
NAKAMURA Takumia9cb5382015-09-22 11:14:39 +0000809
Bill Wendlingeb872e02011-06-22 21:07:27 +0000810 // Compute the total size of the section data, as well as its file size and vm
811 // size.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000812 uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) :
813 sizeof(MachO::mach_header)) + LoadCommandsSize;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000814 uint64_t SectionDataSize = 0;
815 uint64_t SectionDataFileSize = 0;
816 uint64_t VMSize = 0;
Rafael Espindola63702e22015-06-01 01:30:01 +0000817 for (const MCSection &Sec : Asm) {
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000818 uint64_t Address = getSectionAddress(&Sec);
819 uint64_t Size = Layout.getSectionAddressSize(&Sec);
820 uint64_t FileSize = Layout.getSectionFileSize(&Sec);
821 FileSize += getPaddingSize(&Sec, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000822
823 VMSize = std::max(VMSize, Address + Size);
824
Rafael Espindola63702e22015-06-01 01:30:01 +0000825 if (Sec.isVirtualSection())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000826 continue;
827
828 SectionDataSize = std::max(SectionDataSize, Address + Size);
829 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
830 }
831
832 // The section data is padded to 4 bytes.
833 //
834 // FIXME: Is this machine dependent?
835 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
836 SectionDataFileSize += SectionDataPadding;
837
838 // Write the prolog, starting with the header and load command...
Frederic Riss75c0c702015-08-26 05:09:46 +0000839 writeHeader(MachO::MH_OBJECT, NumLoadCommands, LoadCommandsSize,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000840 Asm.getSubsectionsViaSymbols());
Frederic Riss75c0c702015-08-26 05:09:46 +0000841 uint32_t Prot =
842 MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE;
843 writeSegmentLoadCommand("", NumSections, 0, VMSize, SectionDataStart,
844 SectionDataSize, Prot, Prot);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000845
846 // ... and then the section headers.
847 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
Frederic Riss75c0c702015-08-26 05:09:46 +0000848 for (const MCSection &Section : Asm) {
849 const auto &Sec = cast<MCSectionMachO>(Section);
Rafael Espindola63702e22015-06-01 01:30:01 +0000850 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
Bill Wendlingeb872e02011-06-22 21:07:27 +0000851 unsigned NumRelocs = Relocs.size();
Rafael Espindola63702e22015-06-01 01:30:01 +0000852 uint64_t SectionStart = SectionDataStart + getSectionAddress(&Sec);
Frederic Riss75c0c702015-08-26 05:09:46 +0000853 unsigned Flags = Sec.getTypeAndAttributes();
854 if (Sec.hasInstructions())
855 Flags |= MachO::S_ATTR_SOME_INSTRUCTIONS;
856 writeSection(Layout, Sec, getSectionAddress(&Sec), SectionStart, Flags,
857 RelocTableEnd, NumRelocs);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000858 RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000859 }
860
Jim Grosbach448334a2014-03-18 22:09:05 +0000861 // Write out the deployment target information, if it's available.
862 if (VersionInfo.Major != 0) {
Alex Lorenzafa75d72018-12-14 01:14:10 +0000863 auto EncodeVersion = [](VersionTuple V) -> uint32_t {
864 assert(!V.empty() && "empty version");
865 unsigned Update = V.getSubminor() ? *V.getSubminor() : 0;
866 unsigned Minor = V.getMinor() ? *V.getMinor() : 0;
867 assert(Update < 256 && "unencodable update target version");
868 assert(Minor < 256 && "unencodable minor target version");
869 assert(V.getMajor() < 65536 && "unencodable major target version");
870 return Update | (Minor << 8) | (V.getMajor() << 16);
871 };
872 uint32_t EncodedVersion = EncodeVersion(
873 VersionTuple(VersionInfo.Major, VersionInfo.Minor, VersionInfo.Update));
874 uint32_t SDKVersion = !VersionInfo.SDKVersion.empty()
875 ? EncodeVersion(VersionInfo.SDKVersion)
876 : 0;
Matthias Braun0148c882017-12-14 00:12:46 +0000877 if (VersionInfo.EmitBuildVersion) {
878 // FIXME: Currently empty tools. Add clang version in the future.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000879 W.write<uint32_t>(MachO::LC_BUILD_VERSION);
880 W.write<uint32_t>(sizeof(MachO::build_version_command));
881 W.write<uint32_t>(VersionInfo.TypeOrPlatform.Platform);
882 W.write<uint32_t>(EncodedVersion);
Alex Lorenzafa75d72018-12-14 01:14:10 +0000883 W.write<uint32_t>(SDKVersion);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000884 W.write<uint32_t>(0); // Empty tools list.
Matthias Braun0148c882017-12-14 00:12:46 +0000885 } else {
886 MachO::LoadCommandType LCType
887 = getLCFromMCVM(VersionInfo.TypeOrPlatform.Type);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000888 W.write<uint32_t>(LCType);
889 W.write<uint32_t>(sizeof(MachO::version_min_command));
890 W.write<uint32_t>(EncodedVersion);
Alex Lorenzafa75d72018-12-14 01:14:10 +0000891 W.write<uint32_t>(SDKVersion);
Tim Northover2d4d1612015-10-28 22:36:05 +0000892 }
Jim Grosbach448334a2014-03-18 22:09:05 +0000893 }
894
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000895 // Write the data-in-code load command, if used.
896 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
897 if (NumDataRegions) {
898 uint64_t DataRegionsOffset = RelocTableEnd;
899 uint64_t DataRegionsSize = NumDataRegions * 8;
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000900 writeLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset,
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000901 DataRegionsSize);
902 }
903
Tim Northover53d32512014-03-29 07:34:53 +0000904 // Write the loh load command, if used.
905 uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize;
906 if (LOHSize)
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000907 writeLinkeditLoadCommand(MachO::LC_LINKER_OPTIMIZATION_HINT,
Tim Northover53d32512014-03-29 07:34:53 +0000908 DataInCodeTableEnd, LOHSize);
909
Bill Wendlingeb872e02011-06-22 21:07:27 +0000910 // Write the symbol table load command, if used.
911 if (NumSymbols) {
912 unsigned FirstLocalSymbol = 0;
913 unsigned NumLocalSymbols = LocalSymbolData.size();
914 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
915 unsigned NumExternalSymbols = ExternalSymbolData.size();
916 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
917 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
918 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
919 unsigned NumSymTabSymbols =
920 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
921 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
922 uint64_t IndirectSymbolOffset = 0;
923
924 // If used, the indirect symbols are written after the section data.
925 if (NumIndirectSymbols)
Tim Northover53d32512014-03-29 07:34:53 +0000926 IndirectSymbolOffset = LOHTableEnd;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000927
928 // The symbol table is written after the indirect symbol data.
Tim Northover53d32512014-03-29 07:34:53 +0000929 uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000930
931 // The string table is written after symbol table.
932 uint64_t StringTableOffset =
Charles Davis8bdfafd2013-09-01 04:28:48 +0000933 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ?
934 sizeof(MachO::nlist_64) :
935 sizeof(MachO::nlist));
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000936 writeSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
Rafael Espindola39751af2016-10-04 22:43:25 +0000937 StringTableOffset, StringTable.getSize());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000938
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000939 writeDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000940 FirstExternalSymbol, NumExternalSymbols,
941 FirstUndefinedSymbol, NumUndefinedSymbols,
942 IndirectSymbolOffset, NumIndirectSymbols);
943 }
944
Daniel Dunbareec0f322013-01-18 01:26:07 +0000945 // Write the linker options load commands.
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000946 for (const auto &Option : Asm.getLinkerOptions())
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000947 writeLinkerOptionsLoadCommand(Option);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000948
Bill Wendlingeb872e02011-06-22 21:07:27 +0000949 // Write the actual section data.
Rafael Espindola63702e22015-06-01 01:30:01 +0000950 for (const MCSection &Sec : Asm) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000951 Asm.writeSectionData(W.OS, &Sec, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000952
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000953 uint64_t Pad = getPaddingSize(&Sec, Layout);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000954 W.OS.write_zeros(Pad);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000955 }
956
957 // Write the extra padding.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000958 W.OS.write_zeros(SectionDataPadding);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000959
960 // Write the relocation entries.
Rafael Espindola63702e22015-06-01 01:30:01 +0000961 for (const MCSection &Sec : Asm) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000962 // Write the section relocation entries, in reverse order to match 'as'
963 // (approximately, the exact algorithm is more complicated than this).
Rafael Espindola63702e22015-06-01 01:30:01 +0000964 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000965 for (const RelAndSymbol &Rel : make_range(Relocs.rbegin(), Relocs.rend())) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000966 W.write<uint32_t>(Rel.MRE.r_word0);
967 W.write<uint32_t>(Rel.MRE.r_word1);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000968 }
969 }
970
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000971 // Write out the data-in-code region payload, if there is one.
972 for (MCAssembler::const_data_region_iterator
973 it = Asm.data_region_begin(), ie = Asm.data_region_end();
974 it != ie; ++it) {
975 const DataRegionData *Data = &(*it);
Duncan P. N. Exon Smith99d8a8e2015-05-20 00:02:39 +0000976 uint64_t Start = getSymbolAddress(*Data->Start, Layout);
Gerolf Hoflehnerbf82e992018-02-12 07:19:05 +0000977 uint64_t End;
Fangrui Songf78650a2018-07-30 19:41:25 +0000978 if (Data->End)
Gerolf Hoflehnerbf82e992018-02-12 07:19:05 +0000979 End = getSymbolAddress(*Data->End, Layout);
980 else
981 report_fatal_error("Data region not terminated");
982
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000983 LLVM_DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
984 << " start: " << Start << "(" << Data->Start->getName()
985 << ")"
986 << " end: " << End << "(" << Data->End->getName() << ")"
987 << " size: " << End - Start << "\n");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000988 W.write<uint32_t>(Start);
989 W.write<uint16_t>(End - Start);
990 W.write<uint16_t>(Data->Kind);
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000991 }
992
Tim Northover53d32512014-03-29 07:34:53 +0000993 // Write out the loh commands, if there is one.
994 if (LOHSize) {
995#ifndef NDEBUG
Peter Collingbournef17b1492018-05-21 18:17:42 +0000996 unsigned Start = W.OS.tell();
Tim Northover53d32512014-03-29 07:34:53 +0000997#endif
Jim Grosbach249af2a2015-06-01 23:55:06 +0000998 Asm.getLOHContainer().emit(*this, Layout);
Tim Northover53d32512014-03-29 07:34:53 +0000999 // Pad to a multiple of the pointer size.
Peter Collingbournef17b1492018-05-21 18:17:42 +00001000 W.OS.write_zeros(OffsetToAlignment(LOHRawSize, is64Bit() ? 8 : 4));
1001 assert(W.OS.tell() - Start == LOHSize);
Tim Northover53d32512014-03-29 07:34:53 +00001002 }
1003
Bill Wendlingeb872e02011-06-22 21:07:27 +00001004 // Write the symbol table data, if used.
1005 if (NumSymbols) {
1006 // Write the indirect symbol entries.
1007 for (MCAssembler::const_indirect_symbol_iterator
1008 it = Asm.indirect_symbol_begin(),
1009 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
Alp Tokerf907b892013-12-05 05:44:44 +00001010 // Indirect symbols in the non-lazy symbol pointer section have some
Bill Wendlingeb872e02011-06-22 21:07:27 +00001011 // special handling.
1012 const MCSectionMachO &Section =
Rafael Espindola64acc7f2015-05-26 02:17:21 +00001013 static_cast<const MCSectionMachO &>(*it->Section);
David Majnemer7b583052014-03-07 07:36:05 +00001014 if (Section.getType() == MachO::S_NON_LAZY_SYMBOL_POINTERS) {
Bill Wendlingeb872e02011-06-22 21:07:27 +00001015 // If this symbol is defined and internal, mark it as such.
Rafael Espindola4d37b2a2015-05-29 21:45:01 +00001016 if (it->Symbol->isDefined() && !it->Symbol->isExternal()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001017 uint32_t Flags = MachO::INDIRECT_SYMBOL_LOCAL;
Bill Wendlingeb872e02011-06-22 21:07:27 +00001018 if (it->Symbol->isAbsolute())
Charles Davis8bdfafd2013-09-01 04:28:48 +00001019 Flags |= MachO::INDIRECT_SYMBOL_ABS;
Peter Collingbournef17b1492018-05-21 18:17:42 +00001020 W.write<uint32_t>(Flags);
Bill Wendlingeb872e02011-06-22 21:07:27 +00001021 continue;
1022 }
1023 }
1024
Peter Collingbournef17b1492018-05-21 18:17:42 +00001025 W.write<uint32_t>(it->Symbol->getIndex());
Bill Wendlingeb872e02011-06-22 21:07:27 +00001026 }
1027
1028 // FIXME: Check that offsets match computed ones.
1029
1030 // Write the symbol table entries.
Benjamin Kramer1ec70d82015-06-04 21:17:27 +00001031 for (auto *SymbolData :
1032 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
1033 for (MachSymbolData &Entry : *SymbolData)
Jim Grosbach56ed0bb2015-06-04 23:25:54 +00001034 writeNlist(Entry, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +00001035
1036 // Write the string table.
Peter Collingbournef17b1492018-05-21 18:17:42 +00001037 StringTable.write(W.OS);
Bill Wendlingeb872e02011-06-22 21:07:27 +00001038 }
Peter Collingbourne438390f2018-05-21 18:23:50 +00001039
1040 return W.OS.tell() - StartOffset;
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +00001041}
1042
Lang Hames60fbc7c2017-10-10 16:28:07 +00001043std::unique_ptr<MCObjectWriter>
Lang Hames9b206a72017-10-09 22:38:13 +00001044llvm::createMachObjectWriter(std::unique_ptr<MCMachObjectTargetWriter> MOTW,
1045 raw_pwrite_stream &OS, bool IsLittleEndian) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001046 return std::make_unique<MachObjectWriter>(std::move(MOTW), OS,
Lang Hames60fbc7c2017-10-10 16:28:07 +00001047 IsLittleEndian);
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +00001048}