blob: 9f6af981aca108583b3bb83babc17b24ac52d586 [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"
Guillaume Chateletaf11cc72019-09-12 15:20:36 +000028#include "llvm/Support/Alignment.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000029#include "llvm/Support/Casting.h"
Jim Grosbach4b63d2a2012-05-18 19:12:01 +000030#include "llvm/Support/Debug.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000031#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000032#include "llvm/Support/MathExtras.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000033#include "llvm/Support/raw_ostream.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000034#include <algorithm>
35#include <cassert>
36#include <cstdint>
37#include <string>
38#include <utility>
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000039#include <vector>
Eugene Zelenko1d435522017-02-07 23:02:00 +000040
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000041using namespace llvm;
42
Chandler Carruthe96dd892014-04-21 22:55:11 +000043#define DEBUG_TYPE "mc"
44
Pedro Artigasb95c53e2012-12-14 18:52:11 +000045void MachObjectWriter::reset() {
46 Relocations.clear();
47 IndirectSymBase.clear();
48 StringTable.clear();
49 LocalSymbolData.clear();
50 ExternalSymbolData.clear();
51 UndefinedSymbolData.clear();
52 MCObjectWriter::reset();
53}
54
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +000055bool MachObjectWriter::doesSymbolRequireExternRelocation(const MCSymbol &S) {
Daniel Dunbar7de31062010-05-10 23:15:13 +000056 // Undefined symbols are always extern.
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +000057 if (S.isUndefined())
Daniel Dunbar7de31062010-05-10 23:15:13 +000058 return true;
59
60 // References to weak definitions require external relocation entries; the
61 // definition may not always be the one in the same object file.
Pete Cooper916f79e2015-06-08 17:17:28 +000062 if (cast<MCSymbolMachO>(S).isWeakDefinition())
Daniel Dunbar7de31062010-05-10 23:15:13 +000063 return true;
64
65 // Otherwise, we can use an internal relocation.
66 return false;
67}
68
Jim Grosbach28fcafb2011-06-24 23:44:37 +000069bool MachObjectWriter::
70MachSymbolData::operator<(const MachSymbolData &RHS) const {
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +000071 return Symbol->getName() < RHS.Symbol->getName();
Jim Grosbach28fcafb2011-06-24 23:44:37 +000072}
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000073
Jim Grosbach28fcafb2011-06-24 23:44:37 +000074bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
75 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
76 (MCFixupKind) Kind);
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000077
Jim Grosbach28fcafb2011-06-24 23:44:37 +000078 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
79}
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000080
Jim Grosbach28fcafb2011-06-24 23:44:37 +000081uint64_t MachObjectWriter::getFragmentAddress(const MCFragment *Fragment,
82 const MCAsmLayout &Layout) const {
Rafael Espindola079027e2015-05-26 00:52:18 +000083 return getSectionAddress(Fragment->getParent()) +
Rafael Espindola7549f872015-05-26 00:36:57 +000084 Layout.getFragmentOffset(Fragment);
Jim Grosbach28fcafb2011-06-24 23:44:37 +000085}
Bill Wendlingeb872e02011-06-22 21:07:27 +000086
Duncan P. N. Exon Smith99d8a8e2015-05-20 00:02:39 +000087uint64_t MachObjectWriter::getSymbolAddress(const MCSymbol &S,
Bill Wendlingeb872e02011-06-22 21:07:27 +000088 const MCAsmLayout &Layout) const {
Bill Wendlingeb872e02011-06-22 21:07:27 +000089 // If this is a variable, then recursively evaluate now.
90 if (S.isVariable()) {
Jim Grosbachd96ef192012-09-13 23:11:25 +000091 if (const MCConstantExpr *C =
92 dyn_cast<const MCConstantExpr>(S.getVariableValue()))
93 return C->getValue();
94
Bill Wendlingeb872e02011-06-22 21:07:27 +000095 MCValue Target;
Jim Grosbach13760bd2015-05-30 01:25:56 +000096 if (!S.getVariableValue()->evaluateAsRelocatable(Target, &Layout, nullptr))
Bill Wendlingeb872e02011-06-22 21:07:27 +000097 report_fatal_error("unable to evaluate offset for variable '" +
98 S.getName() + "'");
99
100 // Verify that any used symbols are defined.
101 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
102 report_fatal_error("unable to evaluate offset to undefined symbol '" +
103 Target.getSymA()->getSymbol().getName() + "'");
104 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
105 report_fatal_error("unable to evaluate offset to undefined symbol '" +
106 Target.getSymB()->getSymbol().getName() + "'");
107
108 uint64_t Address = Target.getConstant();
109 if (Target.getSymA())
Duncan P. N. Exon Smith99d8a8e2015-05-20 00:02:39 +0000110 Address += getSymbolAddress(Target.getSymA()->getSymbol(), Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000111 if (Target.getSymB())
Duncan P. N. Exon Smith99d8a8e2015-05-20 00:02:39 +0000112 Address += getSymbolAddress(Target.getSymB()->getSymbol(), Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000113 return Address;
114 }
115
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000116 return getSectionAddress(S.getFragment()->getParent()) +
Duncan P. N. Exon Smith2a404832015-05-19 23:53:20 +0000117 Layout.getSymbolOffset(S);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000118}
119
Rafael Espindola61e724a2015-05-26 01:15:30 +0000120uint64_t MachObjectWriter::getPaddingSize(const MCSection *Sec,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000121 const MCAsmLayout &Layout) const {
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000122 uint64_t EndAddr = getSectionAddress(Sec) + Layout.getSectionAddressSize(Sec);
Rafael Espindola61e724a2015-05-26 01:15:30 +0000123 unsigned Next = Sec->getLayoutOrder() + 1;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000124 if (Next >= Layout.getSectionOrder().size())
125 return 0;
126
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000127 const MCSection &NextSec = *Layout.getSectionOrder()[Next];
128 if (NextSec.isVirtualSection())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000129 return 0;
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000130 return offsetToAlignment(EndAddr, Align(NextSec.getAlignment()));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000131}
132
Frederic Riss75c0c702015-08-26 05:09:46 +0000133void MachObjectWriter::writeHeader(MachO::HeaderFileType Type,
134 unsigned NumLoadCommands,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000135 unsigned LoadCommandsSize,
136 bool SubsectionsViaSymbols) {
137 uint32_t Flags = 0;
138
139 if (SubsectionsViaSymbols)
Charles Davis8bdfafd2013-09-01 04:28:48 +0000140 Flags |= MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000141
142 // struct mach_header (28 bytes) or
143 // struct mach_header_64 (32 bytes)
144
Peter Collingbournef17b1492018-05-21 18:17:42 +0000145 uint64_t Start = W.OS.tell();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000146 (void) Start;
147
Peter Collingbournef17b1492018-05-21 18:17:42 +0000148 W.write<uint32_t>(is64Bit() ? MachO::MH_MAGIC_64 : MachO::MH_MAGIC);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000149
Peter Collingbournef17b1492018-05-21 18:17:42 +0000150 W.write<uint32_t>(TargetObjectWriter->getCPUType());
151 W.write<uint32_t>(TargetObjectWriter->getCPUSubtype());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000152
Peter Collingbournef17b1492018-05-21 18:17:42 +0000153 W.write<uint32_t>(Type);
154 W.write<uint32_t>(NumLoadCommands);
155 W.write<uint32_t>(LoadCommandsSize);
156 W.write<uint32_t>(Flags);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000157 if (is64Bit())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000158 W.write<uint32_t>(0); // reserved
Bill Wendlingeb872e02011-06-22 21:07:27 +0000159
Peter Collingbournef17b1492018-05-21 18:17:42 +0000160 assert(W.OS.tell() - Start == (is64Bit() ? sizeof(MachO::mach_header_64)
161 : sizeof(MachO::mach_header)));
162}
163
164void MachObjectWriter::writeWithPadding(StringRef Str, uint64_t Size) {
165 assert(Size >= Str.size());
166 W.OS << Str;
167 W.OS.write_zeros(Size - Str.size());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000168}
169
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000170/// writeSegmentLoadCommand - Write a segment load command.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000171///
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000172/// \param NumSections The number of sections in this segment.
173/// \param SectionDataSize The total size of the sections.
Frederic Riss75c0c702015-08-26 05:09:46 +0000174void MachObjectWriter::writeSegmentLoadCommand(
175 StringRef Name, unsigned NumSections, uint64_t VMAddr, uint64_t VMSize,
176 uint64_t SectionDataStartOffset, uint64_t SectionDataSize, uint32_t MaxProt,
177 uint32_t InitProt) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000178 // struct segment_command (56 bytes) or
179 // struct segment_command_64 (72 bytes)
180
Peter Collingbournef17b1492018-05-21 18:17:42 +0000181 uint64_t Start = W.OS.tell();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000182 (void) Start;
183
184 unsigned SegmentLoadCommandSize =
Charles Davis8bdfafd2013-09-01 04:28:48 +0000185 is64Bit() ? sizeof(MachO::segment_command_64):
186 sizeof(MachO::segment_command);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000187 W.write<uint32_t>(is64Bit() ? MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT);
188 W.write<uint32_t>(SegmentLoadCommandSize +
Charles Davis8bdfafd2013-09-01 04:28:48 +0000189 NumSections * (is64Bit() ? sizeof(MachO::section_64) :
190 sizeof(MachO::section)));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000191
Peter Collingbournef17b1492018-05-21 18:17:42 +0000192 writeWithPadding(Name, 16);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000193 if (is64Bit()) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000194 W.write<uint64_t>(VMAddr); // vmaddr
195 W.write<uint64_t>(VMSize); // vmsize
196 W.write<uint64_t>(SectionDataStartOffset); // file offset
197 W.write<uint64_t>(SectionDataSize); // file size
Bill Wendlingeb872e02011-06-22 21:07:27 +0000198 } else {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000199 W.write<uint32_t>(VMAddr); // vmaddr
200 W.write<uint32_t>(VMSize); // vmsize
201 W.write<uint32_t>(SectionDataStartOffset); // file offset
202 W.write<uint32_t>(SectionDataSize); // file size
Bill Wendlingeb872e02011-06-22 21:07:27 +0000203 }
Nick Kledzikfe6813f2013-09-04 23:53:44 +0000204 // maxprot
Peter Collingbournef17b1492018-05-21 18:17:42 +0000205 W.write<uint32_t>(MaxProt);
Nick Kledzikfe6813f2013-09-04 23:53:44 +0000206 // initprot
Peter Collingbournef17b1492018-05-21 18:17:42 +0000207 W.write<uint32_t>(InitProt);
208 W.write<uint32_t>(NumSections);
209 W.write<uint32_t>(0); // flags
Bill Wendlingeb872e02011-06-22 21:07:27 +0000210
Peter Collingbournef17b1492018-05-21 18:17:42 +0000211 assert(W.OS.tell() - Start == SegmentLoadCommandSize);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000212}
213
Frederic Riss75c0c702015-08-26 05:09:46 +0000214void MachObjectWriter::writeSection(const MCAsmLayout &Layout,
215 const MCSection &Sec, uint64_t VMAddr,
216 uint64_t FileOffset, unsigned Flags,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000217 uint64_t RelocationsStart,
218 unsigned NumRelocations) {
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000219 uint64_t SectionSize = Layout.getSectionAddressSize(&Sec);
Rafael Espindola61e724a2015-05-26 01:15:30 +0000220 const MCSectionMachO &Section = cast<MCSectionMachO>(Sec);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000221
222 // The offset is unused for virtual sections.
Rafael Espindola967d6a62015-05-21 21:02:35 +0000223 if (Section.isVirtualSection()) {
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000224 assert(Layout.getSectionFileSize(&Sec) == 0 && "Invalid file size!");
Bill Wendlingeb872e02011-06-22 21:07:27 +0000225 FileOffset = 0;
226 }
227
228 // struct section (68 bytes) or
229 // struct section_64 (80 bytes)
230
Peter Collingbournef17b1492018-05-21 18:17:42 +0000231 uint64_t Start = W.OS.tell();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000232 (void) Start;
233
Peter Collingbournef17b1492018-05-21 18:17:42 +0000234 writeWithPadding(Section.getSectionName(), 16);
235 writeWithPadding(Section.getSegmentName(), 16);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000236 if (is64Bit()) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000237 W.write<uint64_t>(VMAddr); // address
238 W.write<uint64_t>(SectionSize); // size
Bill Wendlingeb872e02011-06-22 21:07:27 +0000239 } else {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000240 W.write<uint32_t>(VMAddr); // address
241 W.write<uint32_t>(SectionSize); // size
Bill Wendlingeb872e02011-06-22 21:07:27 +0000242 }
Peter Collingbournef17b1492018-05-21 18:17:42 +0000243 W.write<uint32_t>(FileOffset);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000244
Rafael Espindola967d6a62015-05-21 21:02:35 +0000245 assert(isPowerOf2_32(Section.getAlignment()) && "Invalid alignment!");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000246 W.write<uint32_t>(Log2_32(Section.getAlignment()));
247 W.write<uint32_t>(NumRelocations ? RelocationsStart : 0);
248 W.write<uint32_t>(NumRelocations);
249 W.write<uint32_t>(Flags);
250 W.write<uint32_t>(IndirectSymBase.lookup(&Sec)); // reserved1
251 W.write<uint32_t>(Section.getStubSize()); // reserved2
Bill Wendlingeb872e02011-06-22 21:07:27 +0000252 if (is64Bit())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000253 W.write<uint32_t>(0); // reserved3
Bill Wendlingeb872e02011-06-22 21:07:27 +0000254
Peter Collingbournef17b1492018-05-21 18:17:42 +0000255 assert(W.OS.tell() - Start ==
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000256 (is64Bit() ? sizeof(MachO::section_64) : sizeof(MachO::section)));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000257}
258
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000259void MachObjectWriter::writeSymtabLoadCommand(uint32_t SymbolOffset,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000260 uint32_t NumSymbols,
261 uint32_t StringTableOffset,
262 uint32_t StringTableSize) {
263 // struct symtab_command (24 bytes)
264
Peter Collingbournef17b1492018-05-21 18:17:42 +0000265 uint64_t Start = W.OS.tell();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000266 (void) Start;
267
Peter Collingbournef17b1492018-05-21 18:17:42 +0000268 W.write<uint32_t>(MachO::LC_SYMTAB);
269 W.write<uint32_t>(sizeof(MachO::symtab_command));
270 W.write<uint32_t>(SymbolOffset);
271 W.write<uint32_t>(NumSymbols);
272 W.write<uint32_t>(StringTableOffset);
273 W.write<uint32_t>(StringTableSize);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000274
Peter Collingbournef17b1492018-05-21 18:17:42 +0000275 assert(W.OS.tell() - Start == sizeof(MachO::symtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000276}
277
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000278void MachObjectWriter::writeDysymtabLoadCommand(uint32_t FirstLocalSymbol,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000279 uint32_t NumLocalSymbols,
280 uint32_t FirstExternalSymbol,
281 uint32_t NumExternalSymbols,
282 uint32_t FirstUndefinedSymbol,
283 uint32_t NumUndefinedSymbols,
284 uint32_t IndirectSymbolOffset,
285 uint32_t NumIndirectSymbols) {
286 // struct dysymtab_command (80 bytes)
287
Peter Collingbournef17b1492018-05-21 18:17:42 +0000288 uint64_t Start = W.OS.tell();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000289 (void) Start;
290
Peter Collingbournef17b1492018-05-21 18:17:42 +0000291 W.write<uint32_t>(MachO::LC_DYSYMTAB);
292 W.write<uint32_t>(sizeof(MachO::dysymtab_command));
293 W.write<uint32_t>(FirstLocalSymbol);
294 W.write<uint32_t>(NumLocalSymbols);
295 W.write<uint32_t>(FirstExternalSymbol);
296 W.write<uint32_t>(NumExternalSymbols);
297 W.write<uint32_t>(FirstUndefinedSymbol);
298 W.write<uint32_t>(NumUndefinedSymbols);
299 W.write<uint32_t>(0); // tocoff
300 W.write<uint32_t>(0); // ntoc
301 W.write<uint32_t>(0); // modtaboff
302 W.write<uint32_t>(0); // nmodtab
303 W.write<uint32_t>(0); // extrefsymoff
304 W.write<uint32_t>(0); // nextrefsyms
305 W.write<uint32_t>(IndirectSymbolOffset);
306 W.write<uint32_t>(NumIndirectSymbols);
307 W.write<uint32_t>(0); // extreloff
308 W.write<uint32_t>(0); // nextrel
309 W.write<uint32_t>(0); // locreloff
310 W.write<uint32_t>(0); // nlocrel
Bill Wendlingeb872e02011-06-22 21:07:27 +0000311
Peter Collingbournef17b1492018-05-21 18:17:42 +0000312 assert(W.OS.tell() - Start == sizeof(MachO::dysymtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000313}
314
Tim Northovereaef0742014-05-30 13:22:59 +0000315MachObjectWriter::MachSymbolData *
316MachObjectWriter::findSymbolData(const MCSymbol &Sym) {
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000317 for (auto *SymbolData :
318 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
319 for (MachSymbolData &Entry : *SymbolData)
320 if (Entry.Symbol == &Sym)
321 return &Entry;
Tim Northovereaef0742014-05-30 13:22:59 +0000322
323 return nullptr;
324}
325
Rafael Espindola7f4e07b2015-04-17 12:28:43 +0000326const MCSymbol &MachObjectWriter::findAliasedSymbol(const MCSymbol &Sym) const {
327 const MCSymbol *S = &Sym;
328 while (S->isVariable()) {
329 const MCExpr *Value = S->getVariableValue();
330 const auto *Ref = dyn_cast<MCSymbolRefExpr>(Value);
331 if (!Ref)
332 return *S;
333 S = &Ref->getSymbol();
334 }
335 return *S;
336}
337
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000338void MachObjectWriter::writeNlist(MachSymbolData &MSD,
Bill Wendling21162212011-06-23 00:09:43 +0000339 const MCAsmLayout &Layout) {
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +0000340 const MCSymbol *Symbol = MSD.Symbol;
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000341 const MCSymbol &Data = *Symbol;
Rafael Espindola7f4e07b2015-04-17 12:28:43 +0000342 const MCSymbol *AliasedSymbol = &findAliasedSymbol(*Symbol);
Tim Northovereaef0742014-05-30 13:22:59 +0000343 uint8_t SectionIndex = MSD.SectionIndex;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000344 uint8_t Type = 0;
Jim Grosbacha3171602011-08-09 22:12:37 +0000345 uint64_t Address = 0;
Tim Northovereaef0742014-05-30 13:22:59 +0000346 bool IsAlias = Symbol != AliasedSymbol;
347
Duncan P. N. Exon Smith24f47752015-05-21 00:39:24 +0000348 const MCSymbol &OrigSymbol = *Symbol;
Tim Northovereaef0742014-05-30 13:22:59 +0000349 MachSymbolData *AliaseeInfo;
350 if (IsAlias) {
351 AliaseeInfo = findSymbolData(*AliasedSymbol);
352 if (AliaseeInfo)
353 SectionIndex = AliaseeInfo->SectionIndex;
354 Symbol = AliasedSymbol;
Lang Hames1b640e02016-03-15 01:43:05 +0000355 // FIXME: Should this update Data as well?
Tim Northovereaef0742014-05-30 13:22:59 +0000356 }
Bill Wendlingeb872e02011-06-22 21:07:27 +0000357
358 // Set the N_TYPE bits. See <mach-o/nlist.h>.
359 //
360 // FIXME: Are the prebound or indirect fields possible here?
Tim Northovereaef0742014-05-30 13:22:59 +0000361 if (IsAlias && Symbol->isUndefined())
362 Type = MachO::N_INDR;
363 else if (Symbol->isUndefined())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000364 Type = MachO::N_UNDF;
Tim Northovereaef0742014-05-30 13:22:59 +0000365 else if (Symbol->isAbsolute())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000366 Type = MachO::N_ABS;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000367 else
Charles Davis8bdfafd2013-09-01 04:28:48 +0000368 Type = MachO::N_SECT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000369
370 // FIXME: Set STAB bits.
371
372 if (Data.isPrivateExtern())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000373 Type |= MachO::N_PEXT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000374
375 // Set external bit.
Tim Northovereaef0742014-05-30 13:22:59 +0000376 if (Data.isExternal() || (!IsAlias && Symbol->isUndefined()))
Charles Davis8bdfafd2013-09-01 04:28:48 +0000377 Type |= MachO::N_EXT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000378
379 // Compute the symbol address.
Tim Northovereaef0742014-05-30 13:22:59 +0000380 if (IsAlias && Symbol->isUndefined())
381 Address = AliaseeInfo->StringIndex;
382 else if (Symbol->isDefined())
Duncan P. N. Exon Smith24f47752015-05-21 00:39:24 +0000383 Address = getSymbolAddress(OrigSymbol, Layout);
Rafael Espindola14672502015-05-29 17:48:04 +0000384 else if (Symbol->isCommon()) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000385 // Common symbols are encoded with the size in the address
386 // field, and their alignment in the flags.
Rafael Espindola14672502015-05-29 17:48:04 +0000387 Address = Symbol->getCommonSize();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000388 }
389
390 // struct nlist (12 bytes)
391
Peter Collingbournef17b1492018-05-21 18:17:42 +0000392 W.write<uint32_t>(MSD.StringIndex);
393 W.OS << char(Type);
394 W.OS << char(SectionIndex);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000395
396 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
397 // value.
Lang Hames1b640e02016-03-15 01:43:05 +0000398 bool EncodeAsAltEntry =
399 IsAlias && cast<MCSymbolMachO>(OrigSymbol).isAltEntry();
Peter Collingbournef17b1492018-05-21 18:17:42 +0000400 W.write<uint16_t>(cast<MCSymbolMachO>(Symbol)->getEncodedFlags(EncodeAsAltEntry));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000401 if (is64Bit())
Peter Collingbournef17b1492018-05-21 18:17:42 +0000402 W.write<uint64_t>(Address);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000403 else
Peter Collingbournef17b1492018-05-21 18:17:42 +0000404 W.write<uint32_t>(Address);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000405}
406
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000407void MachObjectWriter::writeLinkeditLoadCommand(uint32_t Type,
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000408 uint32_t DataOffset,
409 uint32_t DataSize) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000410 uint64_t Start = W.OS.tell();
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000411 (void) Start;
412
Peter Collingbournef17b1492018-05-21 18:17:42 +0000413 W.write<uint32_t>(Type);
414 W.write<uint32_t>(sizeof(MachO::linkedit_data_command));
415 W.write<uint32_t>(DataOffset);
416 W.write<uint32_t>(DataSize);
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000417
Peter Collingbournef17b1492018-05-21 18:17:42 +0000418 assert(W.OS.tell() - Start == sizeof(MachO::linkedit_data_command));
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000419}
420
Daniel Dunbareec0f322013-01-18 01:26:07 +0000421static unsigned ComputeLinkerOptionsLoadCommandSize(
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000422 const std::vector<std::string> &Options, bool is64Bit)
Daniel Dunbareec0f322013-01-18 01:26:07 +0000423{
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +0000424 unsigned Size = sizeof(MachO::linker_option_command);
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000425 for (const std::string &Option : Options)
426 Size += Option.size() + 1;
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000427 return alignTo(Size, is64Bit ? 8 : 4);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000428}
429
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000430void MachObjectWriter::writeLinkerOptionsLoadCommand(
Daniel Dunbareec0f322013-01-18 01:26:07 +0000431 const std::vector<std::string> &Options)
432{
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000433 unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit());
Peter Collingbournef17b1492018-05-21 18:17:42 +0000434 uint64_t Start = W.OS.tell();
Daniel Dunbareec0f322013-01-18 01:26:07 +0000435 (void) Start;
436
Peter Collingbournef17b1492018-05-21 18:17:42 +0000437 W.write<uint32_t>(MachO::LC_LINKER_OPTION);
438 W.write<uint32_t>(Size);
439 W.write<uint32_t>(Options.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +0000440 uint64_t BytesWritten = sizeof(MachO::linker_option_command);
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000441 for (const std::string &Option : Options) {
Daniel Dunbareec0f322013-01-18 01:26:07 +0000442 // Write each string, including the null byte.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000443 W.OS << Option << '\0';
Daniel Dunbareec0f322013-01-18 01:26:07 +0000444 BytesWritten += Option.size() + 1;
445 }
446
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000447 // Pad to a multiple of the pointer size.
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000448 W.OS.write_zeros(
449 offsetToAlignment(BytesWritten, is64Bit() ? Align(8) : Align(4)));
Daniel Dunbareec0f322013-01-18 01:26:07 +0000450
Peter Collingbournef17b1492018-05-21 18:17:42 +0000451 assert(W.OS.tell() - Start == Size);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000452}
453
Francis Visoiu Mistrihc01140e2019-03-06 18:10:41 +0000454static bool isFixupTargetValid(const MCValue &Target) {
455 // Target is (LHS - RHS + cst).
456 // We don't support the form where LHS is null: -RHS + cst
457 if (!Target.getSymA() && Target.getSymB())
458 return false;
459 return true;
460}
461
Jim Grosbach36e60e92015-06-04 22:24:41 +0000462void MachObjectWriter::recordRelocation(MCAssembler &Asm,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000463 const MCAsmLayout &Layout,
464 const MCFragment *Fragment,
Rafael Espindola26585542015-01-19 21:11:14 +0000465 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000466 uint64_t &FixedValue) {
Francis Visoiu Mistrihc01140e2019-03-06 18:10:41 +0000467 if (!isFixupTargetValid(Target)) {
468 Asm.getContext().reportError(Fixup.getLoc(),
469 "unsupported relocation expression");
470 return;
471 }
472
Jim Grosbach36e60e92015-06-04 22:24:41 +0000473 TargetObjectWriter->recordRelocation(this, Asm, Layout, Fragment, Fixup,
Jim Grosbach28fcafb2011-06-24 23:44:37 +0000474 Target, FixedValue);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000475}
476
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000477void MachObjectWriter::bindIndirectSymbols(MCAssembler &Asm) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000478 // This is the point where 'as' creates actual symbols for indirect symbols
479 // (in the following two passes). It would be easier for us to do this sooner
480 // when we see the attribute, but that makes getting the order in the symbol
481 // table much more complicated than it is worth.
482 //
483 // FIXME: Revisit this when the dust settles.
484
Kevin Enderby3aeada22013-08-28 17:50:59 +0000485 // Report errors for use of .indirect_symbol not in a symbol pointer section
486 // or stub section.
487 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
488 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000489 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
Kevin Enderby3aeada22013-08-28 17:50:59 +0000490
David Majnemer7b583052014-03-07 07:36:05 +0000491 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
492 Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
Tim Northover5c3140f2016-04-25 21:12:04 +0000493 Section.getType() != MachO::S_THREAD_LOCAL_VARIABLE_POINTERS &&
David Majnemer7b583052014-03-07 07:36:05 +0000494 Section.getType() != MachO::S_SYMBOL_STUBS) {
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +0000495 MCSymbol &Symbol = *it->Symbol;
496 report_fatal_error("indirect symbol '" + Symbol.getName() +
497 "' not in a symbol pointer or stub section");
Kevin Enderby3aeada22013-08-28 17:50:59 +0000498 }
499 }
500
Alp Tokerf907b892013-12-05 05:44:44 +0000501 // Bind non-lazy symbol pointers first.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000502 unsigned IndirectIndex = 0;
503 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
504 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000505 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000506
Tim Northover43978372016-04-26 18:29:16 +0000507 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
508 Section.getType() != MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
Bill Wendlingeb872e02011-06-22 21:07:27 +0000509 continue;
510
511 // Initialize the section indirect symbol base, if necessary.
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000512 IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000513
Rafael Espindolab5d316b2015-05-29 20:21:02 +0000514 Asm.registerSymbol(*it->Symbol);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000515 }
516
517 // Then lazy symbol pointers and symbol stubs.
518 IndirectIndex = 0;
519 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
520 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000521 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000522
David Majnemer7b583052014-03-07 07:36:05 +0000523 if (Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
524 Section.getType() != MachO::S_SYMBOL_STUBS)
Bill Wendlingeb872e02011-06-22 21:07:27 +0000525 continue;
526
527 // Initialize the section indirect symbol base, if necessary.
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000528 IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000529
530 // Set the symbol type to undefined lazy, but only on construction.
531 //
532 // FIXME: Do not hardcode.
533 bool Created;
Rafael Espindolab5d316b2015-05-29 20:21:02 +0000534 Asm.registerSymbol(*it->Symbol, &Created);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000535 if (Created)
Pete Cooper916f79e2015-06-08 17:17:28 +0000536 cast<MCSymbolMachO>(it->Symbol)->setReferenceTypeUndefinedLazy(true);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000537 }
538}
539
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000540/// computeSymbolTable - Compute the symbol table data
541void MachObjectWriter::computeSymbolTable(
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000542 MCAssembler &Asm, std::vector<MachSymbolData> &LocalSymbolData,
543 std::vector<MachSymbolData> &ExternalSymbolData,
544 std::vector<MachSymbolData> &UndefinedSymbolData) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000545 // Build section lookup table.
546 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
547 unsigned Index = 1;
548 for (MCAssembler::iterator it = Asm.begin(),
549 ie = Asm.end(); it != ie; ++it, ++Index)
Rafael Espindolaa554c052015-05-25 23:14:17 +0000550 SectionIndexMap[&*it] = Index;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000551 assert(Index <= 256 && "Too many sections!");
552
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000553 // Build the string table.
Duncan P. N. Exon Smithf48de1c2015-05-16 00:35:24 +0000554 for (const MCSymbol &Symbol : Asm.symbols()) {
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000555 if (!Asm.isSymbolLinkerVisible(Symbol))
556 continue;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000557
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000558 StringTable.add(Symbol.getName());
559 }
Rafael Espindola21956e42015-10-23 21:48:05 +0000560 StringTable.finalize();
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000561
562 // Build the symbol arrays but only for non-local symbols.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000563 //
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000564 // The particular order that we collect and then sort the symbols is chosen to
565 // match 'as'. Even though it doesn't matter for correctness, this is
566 // important for letting us diff .o files.
Duncan P. N. Exon Smithf48de1c2015-05-16 00:35:24 +0000567 for (const MCSymbol &Symbol : Asm.symbols()) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000568 // Ignore non-linker visible symbols.
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000569 if (!Asm.isSymbolLinkerVisible(Symbol))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000570 continue;
571
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000572 if (!Symbol.isExternal() && !Symbol.isUndefined())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000573 continue;
574
Bill Wendlingeb872e02011-06-22 21:07:27 +0000575 MachSymbolData MSD;
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +0000576 MSD.Symbol = &Symbol;
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000577 MSD.StringIndex = StringTable.getOffset(Symbol.getName());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000578
579 if (Symbol.isUndefined()) {
580 MSD.SectionIndex = 0;
581 UndefinedSymbolData.push_back(MSD);
582 } else if (Symbol.isAbsolute()) {
583 MSD.SectionIndex = 0;
584 ExternalSymbolData.push_back(MSD);
585 } else {
586 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
587 assert(MSD.SectionIndex && "Invalid section index!");
588 ExternalSymbolData.push_back(MSD);
589 }
590 }
591
592 // Now add the data for local symbols.
Duncan P. N. Exon Smithf48de1c2015-05-16 00:35:24 +0000593 for (const MCSymbol &Symbol : Asm.symbols()) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000594 // Ignore non-linker visible symbols.
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000595 if (!Asm.isSymbolLinkerVisible(Symbol))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000596 continue;
597
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000598 if (Symbol.isExternal() || Symbol.isUndefined())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000599 continue;
600
Bill Wendlingeb872e02011-06-22 21:07:27 +0000601 MachSymbolData MSD;
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +0000602 MSD.Symbol = &Symbol;
Daniel Jasper41de8022015-06-23 11:31:32 +0000603 MSD.StringIndex = StringTable.getOffset(Symbol.getName());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000604
605 if (Symbol.isAbsolute()) {
606 MSD.SectionIndex = 0;
607 LocalSymbolData.push_back(MSD);
608 } else {
609 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
610 assert(MSD.SectionIndex && "Invalid section index!");
611 LocalSymbolData.push_back(MSD);
612 }
613 }
614
615 // External and undefined symbols are required to be in lexicographic order.
Fangrui Song0cac7262018-09-27 02:13:45 +0000616 llvm::sort(ExternalSymbolData);
617 llvm::sort(UndefinedSymbolData);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000618
619 // Set the symbol indices.
620 Index = 0;
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000621 for (auto *SymbolData :
622 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
623 for (MachSymbolData &Entry : *SymbolData)
624 Entry.Symbol->setIndex(Index++);
Rafael Espindola26585542015-01-19 21:11:14 +0000625
Rafael Espindolaa554c052015-05-25 23:14:17 +0000626 for (const MCSection &Section : Asm) {
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000627 for (RelAndSymbol &Rel : Relocations[&Section]) {
Rafael Espindola26585542015-01-19 21:11:14 +0000628 if (!Rel.Sym)
629 continue;
630
631 // Set the Index and the IsExtern bit.
Duncan P. N. Exon Smith1247bbd2015-05-22 05:54:01 +0000632 unsigned Index = Rel.Sym->getIndex();
Rafael Espindola26585542015-01-19 21:11:14 +0000633 assert(isInt<24>(Index));
Peter Collingbournef17b1492018-05-21 18:17:42 +0000634 if (W.Endian == support::little)
Justin Bognerd4e08a02015-05-14 23:54:49 +0000635 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & (~0U << 24)) | Index | (1 << 27);
Rafael Espindola26585542015-01-19 21:11:14 +0000636 else
637 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & 0xff) | Index << 8 | (1 << 4);
638 }
639 }
Bill Wendlingeb872e02011-06-22 21:07:27 +0000640}
641
642void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
643 const MCAsmLayout &Layout) {
644 uint64_t StartAddress = 0;
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000645 for (const MCSection *Sec : Layout.getSectionOrder()) {
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000646 StartAddress = alignTo(StartAddress, Sec->getAlignment());
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000647 SectionAddress[Sec] = StartAddress;
648 StartAddress += Layout.getSectionAddressSize(Sec);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000649
650 // Explicitly pad the section to match the alignment requirements of the
651 // following one. This is for 'gas' compatibility, it shouldn't
652 /// strictly be necessary.
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000653 StartAddress += getPaddingSize(Sec, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000654 }
655}
656
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000657void MachObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
Bill Wendling21162212011-06-23 00:09:43 +0000658 const MCAsmLayout &Layout) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000659 computeSectionAddresses(Asm, Layout);
660
661 // Create symbol data for any indirect symbols.
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000662 bindIndirectSymbols(Asm);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000663}
664
Jim Grosbach36e60e92015-06-04 22:24:41 +0000665bool MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
Rafael Espindolae3a20f52015-10-05 12:07:05 +0000666 const MCAssembler &Asm, const MCSymbol &A, const MCSymbol &B,
667 bool InSet) const {
668 // FIXME: We don't handle things like
669 // foo = .
670 // creating atoms.
671 if (A.isVariable() || B.isVariable())
672 return false;
673 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, A, B,
674 InSet);
675}
676
677bool MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
Duncan P. N. Exon Smithd81ba532015-05-16 01:01:55 +0000678 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
Rafael Espindola35d61892015-04-17 21:15:17 +0000679 bool InSet, bool IsPCRel) const {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000680 if (InSet)
681 return true;
682
683 // The effective address is
684 // addr(atom(A)) + offset(A)
685 // - addr(atom(B)) - offset(B)
686 // and the offsets are not relocatable, so the fixup is fully resolved when
687 // addr(atom(A)) - addr(atom(B)) == 0.
Duncan P. N. Exon Smithd81ba532015-05-16 01:01:55 +0000688 const MCSymbol &SA = findAliasedSymbol(SymA);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000689 const MCSection &SecA = SA.getSection();
Rafael Espindola7549f872015-05-26 00:36:57 +0000690 const MCSection &SecB = *FB.getParent();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000691
692 if (IsPCRel) {
693 // The simple (Darwin, except on x86_64) way of dealing with this was to
694 // assume that any reference to a temporary symbol *must* be a temporary
695 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
696 // relocation to a temporary symbol (in the same section) is fully
697 // resolved. This also works in conjunction with absolutized .set, which
698 // requires the compiler to use .set to absolutize the differences between
699 // symbols which the compiler knows to be assembly time constants, so we
700 // don't need to worry about considering symbol differences fully resolved.
Jim Grosbachd6ae4ba2011-12-07 19:46:59 +0000701 //
702 // If the file isn't using sub-sections-via-symbols, we can make the
703 // same assumptions about any symbol that we normally make about
704 // assembler locals.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000705
Rafael Espindolaa063bdd2014-03-11 21:22:57 +0000706 bool hasReliableSymbolDifference = isX86_64();
707 if (!hasReliableSymbolDifference) {
Jim Grosbach40455072012-01-17 22:14:39 +0000708 if (!SA.isInSection() || &SecA != &SecB ||
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000709 (!SA.isTemporary() && FB.getAtom() != SA.getFragment()->getAtom() &&
Jim Grosbach35bc8f92012-01-24 21:45:25 +0000710 Asm.getSubsectionsViaSymbols()))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000711 return false;
712 return true;
713 }
Kevin Enderby7b46bb82011-09-08 20:53:44 +0000714 // For Darwin x86_64, there is one special case when the reference IsPCRel.
715 // If the fragment with the reference does not have a base symbol but meets
716 // the simple way of dealing with this, in that it is a temporary symbol in
717 // the same atom then it is assumed to be fully resolved. This is needed so
Eric Christopher460be992011-09-08 22:17:40 +0000718 // a relocation entry is not created and so the static linker does not
Kevin Enderby7b46bb82011-09-08 20:53:44 +0000719 // mess up the reference later.
720 else if(!FB.getAtom() &&
721 SA.isTemporary() && SA.isInSection() && &SecA == &SecB){
722 return true;
723 }
Bill Wendlingeb872e02011-06-22 21:07:27 +0000724 }
725
Rafael Espindolabfd0f012014-11-04 22:10:33 +0000726 // If they are not in the same section, we can't compute the diff.
727 if (&SecA != &SecB)
728 return false;
729
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000730 const MCFragment *FA = SA.getFragment();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000731
Benjamin Kramer91ea5112011-08-12 01:51:29 +0000732 // Bail if the symbol has no fragment.
733 if (!FA)
734 return false;
735
Bill Wendlingeb872e02011-06-22 21:07:27 +0000736 // If the atoms are the same, they are guaranteed to have the same address.
Duncan P. N. Exon Smith09bfa582015-05-16 00:48:58 +0000737 if (FA->getAtom() == FB.getAtom())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000738 return true;
739
740 // Otherwise, we can't prove this is fully resolved.
741 return false;
742}
743
Matthias Braun0148c882017-12-14 00:12:46 +0000744static MachO::LoadCommandType getLCFromMCVM(MCVersionMinType Type) {
745 switch (Type) {
746 case MCVM_OSXVersionMin: return MachO::LC_VERSION_MIN_MACOSX;
747 case MCVM_IOSVersionMin: return MachO::LC_VERSION_MIN_IPHONEOS;
748 case MCVM_TvOSVersionMin: return MachO::LC_VERSION_MIN_TVOS;
749 case MCVM_WatchOSVersionMin: return MachO::LC_VERSION_MIN_WATCHOS;
750 }
751 llvm_unreachable("Invalid mc version min type");
752}
753
Peter Collingbourne438390f2018-05-21 18:23:50 +0000754uint64_t MachObjectWriter::writeObject(MCAssembler &Asm,
755 const MCAsmLayout &Layout) {
756 uint64_t StartOffset = W.OS.tell();
757
Rafael Espindola26585542015-01-19 21:11:14 +0000758 // Compute symbol table information and bind symbol indices.
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000759 computeSymbolTable(Asm, LocalSymbolData, ExternalSymbolData,
Rafael Espindola26585542015-01-19 21:11:14 +0000760 UndefinedSymbolData);
761
Bill Wendlingeb872e02011-06-22 21:07:27 +0000762 unsigned NumSections = Asm.size();
Matthias Braun0148c882017-12-14 00:12:46 +0000763 const MCAssembler::VersionInfoType &VersionInfo =
764 Layout.getAssembler().getVersionInfo();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000765
766 // The section data starts after the header, the segment load command (and
767 // section headers) and the symbol table.
768 unsigned NumLoadCommands = 1;
769 uint64_t LoadCommandsSize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +0000770 sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64):
771 sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000772
Jim Grosbach448334a2014-03-18 22:09:05 +0000773 // Add the deployment target version info load command size, if used.
774 if (VersionInfo.Major != 0) {
775 ++NumLoadCommands;
Matthias Braun0148c882017-12-14 00:12:46 +0000776 if (VersionInfo.EmitBuildVersion)
777 LoadCommandsSize += sizeof(MachO::build_version_command);
778 else
779 LoadCommandsSize += sizeof(MachO::version_min_command);
Jim Grosbach448334a2014-03-18 22:09:05 +0000780 }
781
Daniel Dunbareec0f322013-01-18 01:26:07 +0000782 // Add the data-in-code load command size, if used.
783 unsigned NumDataRegions = Asm.getDataRegions().size();
784 if (NumDataRegions) {
785 ++NumLoadCommands;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000786 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000787 }
788
Tim Northover53d32512014-03-29 07:34:53 +0000789 // Add the loh load command size, if used.
790 uint64_t LOHRawSize = Asm.getLOHContainer().getEmitSize(*this, Layout);
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000791 uint64_t LOHSize = alignTo(LOHRawSize, is64Bit() ? 8 : 4);
Tim Northover53d32512014-03-29 07:34:53 +0000792 if (LOHSize) {
793 ++NumLoadCommands;
794 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
795 }
796
Bill Wendlingeb872e02011-06-22 21:07:27 +0000797 // Add the symbol table load command sizes, if used.
798 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
799 UndefinedSymbolData.size();
800 if (NumSymbols) {
801 NumLoadCommands += 2;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000802 LoadCommandsSize += (sizeof(MachO::symtab_command) +
803 sizeof(MachO::dysymtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000804 }
805
Daniel Dunbareec0f322013-01-18 01:26:07 +0000806 // Add the linker option load commands sizes.
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000807 for (const auto &Option : Asm.getLinkerOptions()) {
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000808 ++NumLoadCommands;
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000809 LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(Option, is64Bit());
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000810 }
NAKAMURA Takumia9cb5382015-09-22 11:14:39 +0000811
Bill Wendlingeb872e02011-06-22 21:07:27 +0000812 // Compute the total size of the section data, as well as its file size and vm
813 // size.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000814 uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) :
815 sizeof(MachO::mach_header)) + LoadCommandsSize;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000816 uint64_t SectionDataSize = 0;
817 uint64_t SectionDataFileSize = 0;
818 uint64_t VMSize = 0;
Rafael Espindola63702e22015-06-01 01:30:01 +0000819 for (const MCSection &Sec : Asm) {
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000820 uint64_t Address = getSectionAddress(&Sec);
821 uint64_t Size = Layout.getSectionAddressSize(&Sec);
822 uint64_t FileSize = Layout.getSectionFileSize(&Sec);
823 FileSize += getPaddingSize(&Sec, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000824
825 VMSize = std::max(VMSize, Address + Size);
826
Rafael Espindola63702e22015-06-01 01:30:01 +0000827 if (Sec.isVirtualSection())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000828 continue;
829
830 SectionDataSize = std::max(SectionDataSize, Address + Size);
831 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
832 }
833
834 // The section data is padded to 4 bytes.
835 //
836 // FIXME: Is this machine dependent?
Guillaume Chateletaf11cc72019-09-12 15:20:36 +0000837 unsigned SectionDataPadding =
Guillaume Chatelet18f805a2019-09-27 12:54:21 +0000838 offsetToAlignment(SectionDataFileSize, Align(4));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000839 SectionDataFileSize += SectionDataPadding;
840
841 // Write the prolog, starting with the header and load command...
Frederic Riss75c0c702015-08-26 05:09:46 +0000842 writeHeader(MachO::MH_OBJECT, NumLoadCommands, LoadCommandsSize,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000843 Asm.getSubsectionsViaSymbols());
Frederic Riss75c0c702015-08-26 05:09:46 +0000844 uint32_t Prot =
845 MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE;
846 writeSegmentLoadCommand("", NumSections, 0, VMSize, SectionDataStart,
847 SectionDataSize, Prot, Prot);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000848
849 // ... and then the section headers.
850 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
Frederic Riss75c0c702015-08-26 05:09:46 +0000851 for (const MCSection &Section : Asm) {
852 const auto &Sec = cast<MCSectionMachO>(Section);
Rafael Espindola63702e22015-06-01 01:30:01 +0000853 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
Bill Wendlingeb872e02011-06-22 21:07:27 +0000854 unsigned NumRelocs = Relocs.size();
Rafael Espindola63702e22015-06-01 01:30:01 +0000855 uint64_t SectionStart = SectionDataStart + getSectionAddress(&Sec);
Frederic Riss75c0c702015-08-26 05:09:46 +0000856 unsigned Flags = Sec.getTypeAndAttributes();
857 if (Sec.hasInstructions())
858 Flags |= MachO::S_ATTR_SOME_INSTRUCTIONS;
859 writeSection(Layout, Sec, getSectionAddress(&Sec), SectionStart, Flags,
860 RelocTableEnd, NumRelocs);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000861 RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000862 }
863
Jim Grosbach448334a2014-03-18 22:09:05 +0000864 // Write out the deployment target information, if it's available.
865 if (VersionInfo.Major != 0) {
Alex Lorenzafa75d72018-12-14 01:14:10 +0000866 auto EncodeVersion = [](VersionTuple V) -> uint32_t {
867 assert(!V.empty() && "empty version");
868 unsigned Update = V.getSubminor() ? *V.getSubminor() : 0;
869 unsigned Minor = V.getMinor() ? *V.getMinor() : 0;
870 assert(Update < 256 && "unencodable update target version");
871 assert(Minor < 256 && "unencodable minor target version");
872 assert(V.getMajor() < 65536 && "unencodable major target version");
873 return Update | (Minor << 8) | (V.getMajor() << 16);
874 };
875 uint32_t EncodedVersion = EncodeVersion(
876 VersionTuple(VersionInfo.Major, VersionInfo.Minor, VersionInfo.Update));
877 uint32_t SDKVersion = !VersionInfo.SDKVersion.empty()
878 ? EncodeVersion(VersionInfo.SDKVersion)
879 : 0;
Matthias Braun0148c882017-12-14 00:12:46 +0000880 if (VersionInfo.EmitBuildVersion) {
881 // FIXME: Currently empty tools. Add clang version in the future.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000882 W.write<uint32_t>(MachO::LC_BUILD_VERSION);
883 W.write<uint32_t>(sizeof(MachO::build_version_command));
884 W.write<uint32_t>(VersionInfo.TypeOrPlatform.Platform);
885 W.write<uint32_t>(EncodedVersion);
Alex Lorenzafa75d72018-12-14 01:14:10 +0000886 W.write<uint32_t>(SDKVersion);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000887 W.write<uint32_t>(0); // Empty tools list.
Matthias Braun0148c882017-12-14 00:12:46 +0000888 } else {
889 MachO::LoadCommandType LCType
890 = getLCFromMCVM(VersionInfo.TypeOrPlatform.Type);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000891 W.write<uint32_t>(LCType);
892 W.write<uint32_t>(sizeof(MachO::version_min_command));
893 W.write<uint32_t>(EncodedVersion);
Alex Lorenzafa75d72018-12-14 01:14:10 +0000894 W.write<uint32_t>(SDKVersion);
Tim Northover2d4d1612015-10-28 22:36:05 +0000895 }
Jim Grosbach448334a2014-03-18 22:09:05 +0000896 }
897
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000898 // Write the data-in-code load command, if used.
899 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
900 if (NumDataRegions) {
901 uint64_t DataRegionsOffset = RelocTableEnd;
902 uint64_t DataRegionsSize = NumDataRegions * 8;
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000903 writeLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset,
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000904 DataRegionsSize);
905 }
906
Tim Northover53d32512014-03-29 07:34:53 +0000907 // Write the loh load command, if used.
908 uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize;
909 if (LOHSize)
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000910 writeLinkeditLoadCommand(MachO::LC_LINKER_OPTIMIZATION_HINT,
Tim Northover53d32512014-03-29 07:34:53 +0000911 DataInCodeTableEnd, LOHSize);
912
Bill Wendlingeb872e02011-06-22 21:07:27 +0000913 // Write the symbol table load command, if used.
914 if (NumSymbols) {
915 unsigned FirstLocalSymbol = 0;
916 unsigned NumLocalSymbols = LocalSymbolData.size();
917 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
918 unsigned NumExternalSymbols = ExternalSymbolData.size();
919 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
920 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
921 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
922 unsigned NumSymTabSymbols =
923 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
924 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
925 uint64_t IndirectSymbolOffset = 0;
926
927 // If used, the indirect symbols are written after the section data.
928 if (NumIndirectSymbols)
Tim Northover53d32512014-03-29 07:34:53 +0000929 IndirectSymbolOffset = LOHTableEnd;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000930
931 // The symbol table is written after the indirect symbol data.
Tim Northover53d32512014-03-29 07:34:53 +0000932 uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000933
934 // The string table is written after symbol table.
935 uint64_t StringTableOffset =
Charles Davis8bdfafd2013-09-01 04:28:48 +0000936 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ?
937 sizeof(MachO::nlist_64) :
938 sizeof(MachO::nlist));
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000939 writeSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
Rafael Espindola39751af2016-10-04 22:43:25 +0000940 StringTableOffset, StringTable.getSize());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000941
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000942 writeDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000943 FirstExternalSymbol, NumExternalSymbols,
944 FirstUndefinedSymbol, NumUndefinedSymbols,
945 IndirectSymbolOffset, NumIndirectSymbols);
946 }
947
Daniel Dunbareec0f322013-01-18 01:26:07 +0000948 // Write the linker options load commands.
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000949 for (const auto &Option : Asm.getLinkerOptions())
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000950 writeLinkerOptionsLoadCommand(Option);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000951
Bill Wendlingeb872e02011-06-22 21:07:27 +0000952 // Write the actual section data.
Rafael Espindola63702e22015-06-01 01:30:01 +0000953 for (const MCSection &Sec : Asm) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000954 Asm.writeSectionData(W.OS, &Sec, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000955
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000956 uint64_t Pad = getPaddingSize(&Sec, Layout);
Peter Collingbournef17b1492018-05-21 18:17:42 +0000957 W.OS.write_zeros(Pad);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000958 }
959
960 // Write the extra padding.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000961 W.OS.write_zeros(SectionDataPadding);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000962
963 // Write the relocation entries.
Rafael Espindola63702e22015-06-01 01:30:01 +0000964 for (const MCSection &Sec : Asm) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000965 // Write the section relocation entries, in reverse order to match 'as'
966 // (approximately, the exact algorithm is more complicated than this).
Rafael Espindola63702e22015-06-01 01:30:01 +0000967 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000968 for (const RelAndSymbol &Rel : make_range(Relocs.rbegin(), Relocs.rend())) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000969 W.write<uint32_t>(Rel.MRE.r_word0);
970 W.write<uint32_t>(Rel.MRE.r_word1);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000971 }
972 }
973
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000974 // Write out the data-in-code region payload, if there is one.
975 for (MCAssembler::const_data_region_iterator
976 it = Asm.data_region_begin(), ie = Asm.data_region_end();
977 it != ie; ++it) {
978 const DataRegionData *Data = &(*it);
Duncan P. N. Exon Smith99d8a8e2015-05-20 00:02:39 +0000979 uint64_t Start = getSymbolAddress(*Data->Start, Layout);
Gerolf Hoflehnerbf82e992018-02-12 07:19:05 +0000980 uint64_t End;
Fangrui Songf78650a2018-07-30 19:41:25 +0000981 if (Data->End)
Gerolf Hoflehnerbf82e992018-02-12 07:19:05 +0000982 End = getSymbolAddress(*Data->End, Layout);
983 else
984 report_fatal_error("Data region not terminated");
985
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000986 LLVM_DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
987 << " start: " << Start << "(" << Data->Start->getName()
988 << ")"
989 << " end: " << End << "(" << Data->End->getName() << ")"
990 << " size: " << End - Start << "\n");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000991 W.write<uint32_t>(Start);
992 W.write<uint16_t>(End - Start);
993 W.write<uint16_t>(Data->Kind);
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000994 }
995
Tim Northover53d32512014-03-29 07:34:53 +0000996 // Write out the loh commands, if there is one.
997 if (LOHSize) {
998#ifndef NDEBUG
Peter Collingbournef17b1492018-05-21 18:17:42 +0000999 unsigned Start = W.OS.tell();
Tim Northover53d32512014-03-29 07:34:53 +00001000#endif
Jim Grosbach249af2a2015-06-01 23:55:06 +00001001 Asm.getLOHContainer().emit(*this, Layout);
Tim Northover53d32512014-03-29 07:34:53 +00001002 // Pad to a multiple of the pointer size.
Guillaume Chatelet18f805a2019-09-27 12:54:21 +00001003 W.OS.write_zeros(
1004 offsetToAlignment(LOHRawSize, is64Bit() ? Align(8) : Align(4)));
Peter Collingbournef17b1492018-05-21 18:17:42 +00001005 assert(W.OS.tell() - Start == LOHSize);
Tim Northover53d32512014-03-29 07:34:53 +00001006 }
1007
Bill Wendlingeb872e02011-06-22 21:07:27 +00001008 // Write the symbol table data, if used.
1009 if (NumSymbols) {
1010 // Write the indirect symbol entries.
1011 for (MCAssembler::const_indirect_symbol_iterator
1012 it = Asm.indirect_symbol_begin(),
1013 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
Alp Tokerf907b892013-12-05 05:44:44 +00001014 // Indirect symbols in the non-lazy symbol pointer section have some
Bill Wendlingeb872e02011-06-22 21:07:27 +00001015 // special handling.
1016 const MCSectionMachO &Section =
Rafael Espindola64acc7f2015-05-26 02:17:21 +00001017 static_cast<const MCSectionMachO &>(*it->Section);
David Majnemer7b583052014-03-07 07:36:05 +00001018 if (Section.getType() == MachO::S_NON_LAZY_SYMBOL_POINTERS) {
Bill Wendlingeb872e02011-06-22 21:07:27 +00001019 // If this symbol is defined and internal, mark it as such.
Rafael Espindola4d37b2a2015-05-29 21:45:01 +00001020 if (it->Symbol->isDefined() && !it->Symbol->isExternal()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +00001021 uint32_t Flags = MachO::INDIRECT_SYMBOL_LOCAL;
Bill Wendlingeb872e02011-06-22 21:07:27 +00001022 if (it->Symbol->isAbsolute())
Charles Davis8bdfafd2013-09-01 04:28:48 +00001023 Flags |= MachO::INDIRECT_SYMBOL_ABS;
Peter Collingbournef17b1492018-05-21 18:17:42 +00001024 W.write<uint32_t>(Flags);
Bill Wendlingeb872e02011-06-22 21:07:27 +00001025 continue;
1026 }
1027 }
1028
Peter Collingbournef17b1492018-05-21 18:17:42 +00001029 W.write<uint32_t>(it->Symbol->getIndex());
Bill Wendlingeb872e02011-06-22 21:07:27 +00001030 }
1031
1032 // FIXME: Check that offsets match computed ones.
1033
1034 // Write the symbol table entries.
Benjamin Kramer1ec70d82015-06-04 21:17:27 +00001035 for (auto *SymbolData :
1036 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
1037 for (MachSymbolData &Entry : *SymbolData)
Jim Grosbach56ed0bb2015-06-04 23:25:54 +00001038 writeNlist(Entry, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +00001039
1040 // Write the string table.
Peter Collingbournef17b1492018-05-21 18:17:42 +00001041 StringTable.write(W.OS);
Bill Wendlingeb872e02011-06-22 21:07:27 +00001042 }
Peter Collingbourne438390f2018-05-21 18:23:50 +00001043
1044 return W.OS.tell() - StartOffset;
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +00001045}
1046
Lang Hames60fbc7c2017-10-10 16:28:07 +00001047std::unique_ptr<MCObjectWriter>
Lang Hames9b206a72017-10-09 22:38:13 +00001048llvm::createMachObjectWriter(std::unique_ptr<MCMachObjectTargetWriter> MOTW,
1049 raw_pwrite_stream &OS, bool IsLittleEndian) {
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00001050 return std::make_unique<MachObjectWriter>(std::move(MOTW), OS,
Lang Hames60fbc7c2017-10-10 16:28:07 +00001051 IsLittleEndian);
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +00001052}