blob: 62bf0a58fdfa927d9b7628e9639845e08a24b28f [file] [log] [blame]
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +00001//===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Eugene Zelenko1d435522017-02-07 23:02:00 +000010#include "llvm/ADT/DenseMap.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000011#include "llvm/ADT/Twine.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000012#include "llvm/ADT/iterator_range.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000013#include "llvm/BinaryFormat/MachO.h"
Evan Cheng5928e692011-07-25 23:24:55 +000014#include "llvm/MC/MCAsmBackend.h"
Daniel Dunbar7c969552010-03-24 03:43:40 +000015#include "llvm/MC/MCAsmLayout.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/MC/MCAssembler.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
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000144 uint64_t Start = getStream().tell();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000145 (void) Start;
146
Jim Grosbach36e60e92015-06-04 22:24:41 +0000147 write32(is64Bit() ? MachO::MH_MAGIC_64 : MachO::MH_MAGIC);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000148
Jim Grosbach36e60e92015-06-04 22:24:41 +0000149 write32(TargetObjectWriter->getCPUType());
150 write32(TargetObjectWriter->getCPUSubtype());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000151
Frederic Riss75c0c702015-08-26 05:09:46 +0000152 write32(Type);
Jim Grosbach36e60e92015-06-04 22:24:41 +0000153 write32(NumLoadCommands);
154 write32(LoadCommandsSize);
155 write32(Flags);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000156 if (is64Bit())
Jim Grosbach36e60e92015-06-04 22:24:41 +0000157 write32(0); // reserved
Bill Wendlingeb872e02011-06-22 21:07:27 +0000158
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000159 assert(
160 getStream().tell() - Start ==
161 (is64Bit() ? sizeof(MachO::mach_header_64) : sizeof(MachO::mach_header)));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000162}
163
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000164/// writeSegmentLoadCommand - Write a segment load command.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000165///
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000166/// \param NumSections The number of sections in this segment.
167/// \param SectionDataSize The total size of the sections.
Frederic Riss75c0c702015-08-26 05:09:46 +0000168void MachObjectWriter::writeSegmentLoadCommand(
169 StringRef Name, unsigned NumSections, uint64_t VMAddr, uint64_t VMSize,
170 uint64_t SectionDataStartOffset, uint64_t SectionDataSize, uint32_t MaxProt,
171 uint32_t InitProt) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000172 // struct segment_command (56 bytes) or
173 // struct segment_command_64 (72 bytes)
174
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000175 uint64_t Start = getStream().tell();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000176 (void) Start;
177
178 unsigned SegmentLoadCommandSize =
Charles Davis8bdfafd2013-09-01 04:28:48 +0000179 is64Bit() ? sizeof(MachO::segment_command_64):
180 sizeof(MachO::segment_command);
Jim Grosbach36e60e92015-06-04 22:24:41 +0000181 write32(is64Bit() ? MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT);
182 write32(SegmentLoadCommandSize +
Charles Davis8bdfafd2013-09-01 04:28:48 +0000183 NumSections * (is64Bit() ? sizeof(MachO::section_64) :
184 sizeof(MachO::section)));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000185
Frederic Riss75c0c702015-08-26 05:09:46 +0000186 assert(Name.size() <= 16);
187 writeBytes(Name, 16);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000188 if (is64Bit()) {
Frederic Riss75c0c702015-08-26 05:09:46 +0000189 write64(VMAddr); // vmaddr
Jim Grosbach36e60e92015-06-04 22:24:41 +0000190 write64(VMSize); // vmsize
191 write64(SectionDataStartOffset); // file offset
192 write64(SectionDataSize); // file size
Bill Wendlingeb872e02011-06-22 21:07:27 +0000193 } else {
Frederic Riss75c0c702015-08-26 05:09:46 +0000194 write32(VMAddr); // vmaddr
Jim Grosbach36e60e92015-06-04 22:24:41 +0000195 write32(VMSize); // vmsize
196 write32(SectionDataStartOffset); // file offset
197 write32(SectionDataSize); // file size
Bill Wendlingeb872e02011-06-22 21:07:27 +0000198 }
Nick Kledzikfe6813f2013-09-04 23:53:44 +0000199 // maxprot
Frederic Riss75c0c702015-08-26 05:09:46 +0000200 write32(MaxProt);
Nick Kledzikfe6813f2013-09-04 23:53:44 +0000201 // initprot
Frederic Riss75c0c702015-08-26 05:09:46 +0000202 write32(InitProt);
Jim Grosbach36e60e92015-06-04 22:24:41 +0000203 write32(NumSections);
204 write32(0); // flags
Bill Wendlingeb872e02011-06-22 21:07:27 +0000205
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000206 assert(getStream().tell() - Start == SegmentLoadCommandSize);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000207}
208
Frederic Riss75c0c702015-08-26 05:09:46 +0000209void MachObjectWriter::writeSection(const MCAsmLayout &Layout,
210 const MCSection &Sec, uint64_t VMAddr,
211 uint64_t FileOffset, unsigned Flags,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000212 uint64_t RelocationsStart,
213 unsigned NumRelocations) {
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000214 uint64_t SectionSize = Layout.getSectionAddressSize(&Sec);
Rafael Espindola61e724a2015-05-26 01:15:30 +0000215 const MCSectionMachO &Section = cast<MCSectionMachO>(Sec);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000216
217 // The offset is unused for virtual sections.
Rafael Espindola967d6a62015-05-21 21:02:35 +0000218 if (Section.isVirtualSection()) {
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000219 assert(Layout.getSectionFileSize(&Sec) == 0 && "Invalid file size!");
Bill Wendlingeb872e02011-06-22 21:07:27 +0000220 FileOffset = 0;
221 }
222
223 // struct section (68 bytes) or
224 // struct section_64 (80 bytes)
225
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000226 uint64_t Start = getStream().tell();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000227 (void) Start;
228
Jim Grosbach36e60e92015-06-04 22:24:41 +0000229 writeBytes(Section.getSectionName(), 16);
230 writeBytes(Section.getSegmentName(), 16);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000231 if (is64Bit()) {
Frederic Riss75c0c702015-08-26 05:09:46 +0000232 write64(VMAddr); // address
Jim Grosbach36e60e92015-06-04 22:24:41 +0000233 write64(SectionSize); // size
Bill Wendlingeb872e02011-06-22 21:07:27 +0000234 } else {
Frederic Riss75c0c702015-08-26 05:09:46 +0000235 write32(VMAddr); // address
Jim Grosbach36e60e92015-06-04 22:24:41 +0000236 write32(SectionSize); // size
Bill Wendlingeb872e02011-06-22 21:07:27 +0000237 }
Jim Grosbach36e60e92015-06-04 22:24:41 +0000238 write32(FileOffset);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000239
Rafael Espindola967d6a62015-05-21 21:02:35 +0000240 assert(isPowerOf2_32(Section.getAlignment()) && "Invalid alignment!");
Jim Grosbach36e60e92015-06-04 22:24:41 +0000241 write32(Log2_32(Section.getAlignment()));
242 write32(NumRelocations ? RelocationsStart : 0);
243 write32(NumRelocations);
244 write32(Flags);
245 write32(IndirectSymBase.lookup(&Sec)); // reserved1
246 write32(Section.getStubSize()); // reserved2
Bill Wendlingeb872e02011-06-22 21:07:27 +0000247 if (is64Bit())
Jim Grosbach36e60e92015-06-04 22:24:41 +0000248 write32(0); // reserved3
Bill Wendlingeb872e02011-06-22 21:07:27 +0000249
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000250 assert(getStream().tell() - Start ==
251 (is64Bit() ? sizeof(MachO::section_64) : sizeof(MachO::section)));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000252}
253
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000254void MachObjectWriter::writeSymtabLoadCommand(uint32_t SymbolOffset,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000255 uint32_t NumSymbols,
256 uint32_t StringTableOffset,
257 uint32_t StringTableSize) {
258 // struct symtab_command (24 bytes)
259
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000260 uint64_t Start = getStream().tell();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000261 (void) Start;
262
Jim Grosbach36e60e92015-06-04 22:24:41 +0000263 write32(MachO::LC_SYMTAB);
264 write32(sizeof(MachO::symtab_command));
265 write32(SymbolOffset);
266 write32(NumSymbols);
267 write32(StringTableOffset);
268 write32(StringTableSize);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000269
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000270 assert(getStream().tell() - Start == sizeof(MachO::symtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000271}
272
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000273void MachObjectWriter::writeDysymtabLoadCommand(uint32_t FirstLocalSymbol,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000274 uint32_t NumLocalSymbols,
275 uint32_t FirstExternalSymbol,
276 uint32_t NumExternalSymbols,
277 uint32_t FirstUndefinedSymbol,
278 uint32_t NumUndefinedSymbols,
279 uint32_t IndirectSymbolOffset,
280 uint32_t NumIndirectSymbols) {
281 // struct dysymtab_command (80 bytes)
282
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000283 uint64_t Start = getStream().tell();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000284 (void) Start;
285
Jim Grosbach36e60e92015-06-04 22:24:41 +0000286 write32(MachO::LC_DYSYMTAB);
287 write32(sizeof(MachO::dysymtab_command));
288 write32(FirstLocalSymbol);
289 write32(NumLocalSymbols);
290 write32(FirstExternalSymbol);
291 write32(NumExternalSymbols);
292 write32(FirstUndefinedSymbol);
293 write32(NumUndefinedSymbols);
294 write32(0); // tocoff
295 write32(0); // ntoc
296 write32(0); // modtaboff
297 write32(0); // nmodtab
298 write32(0); // extrefsymoff
299 write32(0); // nextrefsyms
300 write32(IndirectSymbolOffset);
301 write32(NumIndirectSymbols);
302 write32(0); // extreloff
303 write32(0); // nextrel
304 write32(0); // locreloff
305 write32(0); // nlocrel
Bill Wendlingeb872e02011-06-22 21:07:27 +0000306
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000307 assert(getStream().tell() - Start == sizeof(MachO::dysymtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000308}
309
Tim Northovereaef0742014-05-30 13:22:59 +0000310MachObjectWriter::MachSymbolData *
311MachObjectWriter::findSymbolData(const MCSymbol &Sym) {
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000312 for (auto *SymbolData :
313 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
314 for (MachSymbolData &Entry : *SymbolData)
315 if (Entry.Symbol == &Sym)
316 return &Entry;
Tim Northovereaef0742014-05-30 13:22:59 +0000317
318 return nullptr;
319}
320
Rafael Espindola7f4e07b2015-04-17 12:28:43 +0000321const MCSymbol &MachObjectWriter::findAliasedSymbol(const MCSymbol &Sym) const {
322 const MCSymbol *S = &Sym;
323 while (S->isVariable()) {
324 const MCExpr *Value = S->getVariableValue();
325 const auto *Ref = dyn_cast<MCSymbolRefExpr>(Value);
326 if (!Ref)
327 return *S;
328 S = &Ref->getSymbol();
329 }
330 return *S;
331}
332
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000333void MachObjectWriter::writeNlist(MachSymbolData &MSD,
Bill Wendling21162212011-06-23 00:09:43 +0000334 const MCAsmLayout &Layout) {
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +0000335 const MCSymbol *Symbol = MSD.Symbol;
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000336 const MCSymbol &Data = *Symbol;
Rafael Espindola7f4e07b2015-04-17 12:28:43 +0000337 const MCSymbol *AliasedSymbol = &findAliasedSymbol(*Symbol);
Tim Northovereaef0742014-05-30 13:22:59 +0000338 uint8_t SectionIndex = MSD.SectionIndex;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000339 uint8_t Type = 0;
Jim Grosbacha3171602011-08-09 22:12:37 +0000340 uint64_t Address = 0;
Tim Northovereaef0742014-05-30 13:22:59 +0000341 bool IsAlias = Symbol != AliasedSymbol;
342
Duncan P. N. Exon Smith24f47752015-05-21 00:39:24 +0000343 const MCSymbol &OrigSymbol = *Symbol;
Tim Northovereaef0742014-05-30 13:22:59 +0000344 MachSymbolData *AliaseeInfo;
345 if (IsAlias) {
346 AliaseeInfo = findSymbolData(*AliasedSymbol);
347 if (AliaseeInfo)
348 SectionIndex = AliaseeInfo->SectionIndex;
349 Symbol = AliasedSymbol;
Lang Hames1b640e02016-03-15 01:43:05 +0000350 // FIXME: Should this update Data as well?
Tim Northovereaef0742014-05-30 13:22:59 +0000351 }
Bill Wendlingeb872e02011-06-22 21:07:27 +0000352
353 // Set the N_TYPE bits. See <mach-o/nlist.h>.
354 //
355 // FIXME: Are the prebound or indirect fields possible here?
Tim Northovereaef0742014-05-30 13:22:59 +0000356 if (IsAlias && Symbol->isUndefined())
357 Type = MachO::N_INDR;
358 else if (Symbol->isUndefined())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000359 Type = MachO::N_UNDF;
Tim Northovereaef0742014-05-30 13:22:59 +0000360 else if (Symbol->isAbsolute())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000361 Type = MachO::N_ABS;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000362 else
Charles Davis8bdfafd2013-09-01 04:28:48 +0000363 Type = MachO::N_SECT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000364
365 // FIXME: Set STAB bits.
366
367 if (Data.isPrivateExtern())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000368 Type |= MachO::N_PEXT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000369
370 // Set external bit.
Tim Northovereaef0742014-05-30 13:22:59 +0000371 if (Data.isExternal() || (!IsAlias && Symbol->isUndefined()))
Charles Davis8bdfafd2013-09-01 04:28:48 +0000372 Type |= MachO::N_EXT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000373
374 // Compute the symbol address.
Tim Northovereaef0742014-05-30 13:22:59 +0000375 if (IsAlias && Symbol->isUndefined())
376 Address = AliaseeInfo->StringIndex;
377 else if (Symbol->isDefined())
Duncan P. N. Exon Smith24f47752015-05-21 00:39:24 +0000378 Address = getSymbolAddress(OrigSymbol, Layout);
Rafael Espindola14672502015-05-29 17:48:04 +0000379 else if (Symbol->isCommon()) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000380 // Common symbols are encoded with the size in the address
381 // field, and their alignment in the flags.
Rafael Espindola14672502015-05-29 17:48:04 +0000382 Address = Symbol->getCommonSize();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000383 }
384
385 // struct nlist (12 bytes)
386
Jim Grosbach36e60e92015-06-04 22:24:41 +0000387 write32(MSD.StringIndex);
388 write8(Type);
389 write8(SectionIndex);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000390
391 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
392 // value.
Lang Hames1b640e02016-03-15 01:43:05 +0000393 bool EncodeAsAltEntry =
394 IsAlias && cast<MCSymbolMachO>(OrigSymbol).isAltEntry();
395 write16(cast<MCSymbolMachO>(Symbol)->getEncodedFlags(EncodeAsAltEntry));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000396 if (is64Bit())
Jim Grosbach36e60e92015-06-04 22:24:41 +0000397 write64(Address);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000398 else
Jim Grosbach36e60e92015-06-04 22:24:41 +0000399 write32(Address);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000400}
401
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000402void MachObjectWriter::writeLinkeditLoadCommand(uint32_t Type,
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000403 uint32_t DataOffset,
404 uint32_t DataSize) {
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000405 uint64_t Start = getStream().tell();
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000406 (void) Start;
407
Jim Grosbach36e60e92015-06-04 22:24:41 +0000408 write32(Type);
409 write32(sizeof(MachO::linkedit_data_command));
410 write32(DataOffset);
411 write32(DataSize);
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000412
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000413 assert(getStream().tell() - Start == sizeof(MachO::linkedit_data_command));
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000414}
415
Daniel Dunbareec0f322013-01-18 01:26:07 +0000416static unsigned ComputeLinkerOptionsLoadCommandSize(
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000417 const std::vector<std::string> &Options, bool is64Bit)
Daniel Dunbareec0f322013-01-18 01:26:07 +0000418{
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +0000419 unsigned Size = sizeof(MachO::linker_option_command);
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000420 for (const std::string &Option : Options)
421 Size += Option.size() + 1;
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000422 return alignTo(Size, is64Bit ? 8 : 4);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000423}
424
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000425void MachObjectWriter::writeLinkerOptionsLoadCommand(
Daniel Dunbareec0f322013-01-18 01:26:07 +0000426 const std::vector<std::string> &Options)
427{
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000428 unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit());
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000429 uint64_t Start = getStream().tell();
Daniel Dunbareec0f322013-01-18 01:26:07 +0000430 (void) Start;
431
Jim Grosbach36e60e92015-06-04 22:24:41 +0000432 write32(MachO::LC_LINKER_OPTION);
433 write32(Size);
434 write32(Options.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +0000435 uint64_t BytesWritten = sizeof(MachO::linker_option_command);
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000436 for (const std::string &Option : Options) {
Daniel Dunbareec0f322013-01-18 01:26:07 +0000437 // Write each string, including the null byte.
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000438 writeBytes(Option, Option.size() + 1);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000439 BytesWritten += Option.size() + 1;
440 }
441
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000442 // Pad to a multiple of the pointer size.
Jim Grosbach36e60e92015-06-04 22:24:41 +0000443 writeBytes("", OffsetToAlignment(BytesWritten, is64Bit() ? 8 : 4));
Daniel Dunbareec0f322013-01-18 01:26:07 +0000444
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000445 assert(getStream().tell() - Start == Size);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000446}
447
Jim Grosbach36e60e92015-06-04 22:24:41 +0000448void MachObjectWriter::recordRelocation(MCAssembler &Asm,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000449 const MCAsmLayout &Layout,
450 const MCFragment *Fragment,
Rafael Espindola26585542015-01-19 21:11:14 +0000451 const MCFixup &Fixup, MCValue Target,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000452 uint64_t &FixedValue) {
Jim Grosbach36e60e92015-06-04 22:24:41 +0000453 TargetObjectWriter->recordRelocation(this, Asm, Layout, Fragment, Fixup,
Jim Grosbach28fcafb2011-06-24 23:44:37 +0000454 Target, FixedValue);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000455}
456
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000457void MachObjectWriter::bindIndirectSymbols(MCAssembler &Asm) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000458 // This is the point where 'as' creates actual symbols for indirect symbols
459 // (in the following two passes). It would be easier for us to do this sooner
460 // when we see the attribute, but that makes getting the order in the symbol
461 // table much more complicated than it is worth.
462 //
463 // FIXME: Revisit this when the dust settles.
464
Kevin Enderby3aeada22013-08-28 17:50:59 +0000465 // Report errors for use of .indirect_symbol not in a symbol pointer section
466 // or stub section.
467 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
468 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000469 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
Kevin Enderby3aeada22013-08-28 17:50:59 +0000470
David Majnemer7b583052014-03-07 07:36:05 +0000471 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
472 Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
Tim Northover5c3140f2016-04-25 21:12:04 +0000473 Section.getType() != MachO::S_THREAD_LOCAL_VARIABLE_POINTERS &&
David Majnemer7b583052014-03-07 07:36:05 +0000474 Section.getType() != MachO::S_SYMBOL_STUBS) {
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +0000475 MCSymbol &Symbol = *it->Symbol;
476 report_fatal_error("indirect symbol '" + Symbol.getName() +
477 "' not in a symbol pointer or stub section");
Kevin Enderby3aeada22013-08-28 17:50:59 +0000478 }
479 }
480
Alp Tokerf907b892013-12-05 05:44:44 +0000481 // Bind non-lazy symbol pointers first.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000482 unsigned IndirectIndex = 0;
483 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
484 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000485 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000486
Tim Northover43978372016-04-26 18:29:16 +0000487 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
488 Section.getType() != MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
Bill Wendlingeb872e02011-06-22 21:07:27 +0000489 continue;
490
491 // Initialize the section indirect symbol base, if necessary.
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000492 IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000493
Rafael Espindolab5d316b2015-05-29 20:21:02 +0000494 Asm.registerSymbol(*it->Symbol);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000495 }
496
497 // Then lazy symbol pointers and symbol stubs.
498 IndirectIndex = 0;
499 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
500 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000501 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000502
David Majnemer7b583052014-03-07 07:36:05 +0000503 if (Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
504 Section.getType() != MachO::S_SYMBOL_STUBS)
Bill Wendlingeb872e02011-06-22 21:07:27 +0000505 continue;
506
507 // Initialize the section indirect symbol base, if necessary.
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000508 IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000509
510 // Set the symbol type to undefined lazy, but only on construction.
511 //
512 // FIXME: Do not hardcode.
513 bool Created;
Rafael Espindolab5d316b2015-05-29 20:21:02 +0000514 Asm.registerSymbol(*it->Symbol, &Created);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000515 if (Created)
Pete Cooper916f79e2015-06-08 17:17:28 +0000516 cast<MCSymbolMachO>(it->Symbol)->setReferenceTypeUndefinedLazy(true);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000517 }
518}
519
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000520/// computeSymbolTable - Compute the symbol table data
521void MachObjectWriter::computeSymbolTable(
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000522 MCAssembler &Asm, std::vector<MachSymbolData> &LocalSymbolData,
523 std::vector<MachSymbolData> &ExternalSymbolData,
524 std::vector<MachSymbolData> &UndefinedSymbolData) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000525 // Build section lookup table.
526 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
527 unsigned Index = 1;
528 for (MCAssembler::iterator it = Asm.begin(),
529 ie = Asm.end(); it != ie; ++it, ++Index)
Rafael Espindolaa554c052015-05-25 23:14:17 +0000530 SectionIndexMap[&*it] = Index;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000531 assert(Index <= 256 && "Too many sections!");
532
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000533 // Build the string table.
Duncan P. N. Exon Smithf48de1c2015-05-16 00:35:24 +0000534 for (const MCSymbol &Symbol : Asm.symbols()) {
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000535 if (!Asm.isSymbolLinkerVisible(Symbol))
536 continue;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000537
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000538 StringTable.add(Symbol.getName());
539 }
Rafael Espindola21956e42015-10-23 21:48:05 +0000540 StringTable.finalize();
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000541
542 // Build the symbol arrays but only for non-local symbols.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000543 //
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000544 // The particular order that we collect and then sort the symbols is chosen to
545 // match 'as'. Even though it doesn't matter for correctness, this is
546 // important for letting us diff .o files.
Duncan P. N. Exon Smithf48de1c2015-05-16 00:35:24 +0000547 for (const MCSymbol &Symbol : Asm.symbols()) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000548 // Ignore non-linker visible symbols.
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000549 if (!Asm.isSymbolLinkerVisible(Symbol))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000550 continue;
551
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000552 if (!Symbol.isExternal() && !Symbol.isUndefined())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000553 continue;
554
Bill Wendlingeb872e02011-06-22 21:07:27 +0000555 MachSymbolData MSD;
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +0000556 MSD.Symbol = &Symbol;
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000557 MSD.StringIndex = StringTable.getOffset(Symbol.getName());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000558
559 if (Symbol.isUndefined()) {
560 MSD.SectionIndex = 0;
561 UndefinedSymbolData.push_back(MSD);
562 } else if (Symbol.isAbsolute()) {
563 MSD.SectionIndex = 0;
564 ExternalSymbolData.push_back(MSD);
565 } else {
566 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
567 assert(MSD.SectionIndex && "Invalid section index!");
568 ExternalSymbolData.push_back(MSD);
569 }
570 }
571
572 // Now add the data for local symbols.
Duncan P. N. Exon Smithf48de1c2015-05-16 00:35:24 +0000573 for (const MCSymbol &Symbol : Asm.symbols()) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000574 // Ignore non-linker visible symbols.
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000575 if (!Asm.isSymbolLinkerVisible(Symbol))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000576 continue;
577
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000578 if (Symbol.isExternal() || Symbol.isUndefined())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000579 continue;
580
Bill Wendlingeb872e02011-06-22 21:07:27 +0000581 MachSymbolData MSD;
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +0000582 MSD.Symbol = &Symbol;
Daniel Jasper41de8022015-06-23 11:31:32 +0000583 MSD.StringIndex = StringTable.getOffset(Symbol.getName());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000584
585 if (Symbol.isAbsolute()) {
586 MSD.SectionIndex = 0;
587 LocalSymbolData.push_back(MSD);
588 } else {
589 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
590 assert(MSD.SectionIndex && "Invalid section index!");
591 LocalSymbolData.push_back(MSD);
592 }
593 }
594
595 // External and undefined symbols are required to be in lexicographic order.
596 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
597 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
598
599 // Set the symbol indices.
600 Index = 0;
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000601 for (auto *SymbolData :
602 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
603 for (MachSymbolData &Entry : *SymbolData)
604 Entry.Symbol->setIndex(Index++);
Rafael Espindola26585542015-01-19 21:11:14 +0000605
Rafael Espindolaa554c052015-05-25 23:14:17 +0000606 for (const MCSection &Section : Asm) {
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000607 for (RelAndSymbol &Rel : Relocations[&Section]) {
Rafael Espindola26585542015-01-19 21:11:14 +0000608 if (!Rel.Sym)
609 continue;
610
611 // Set the Index and the IsExtern bit.
Duncan P. N. Exon Smith1247bbd2015-05-22 05:54:01 +0000612 unsigned Index = Rel.Sym->getIndex();
Rafael Espindola26585542015-01-19 21:11:14 +0000613 assert(isInt<24>(Index));
614 if (IsLittleEndian)
Justin Bognerd4e08a02015-05-14 23:54:49 +0000615 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & (~0U << 24)) | Index | (1 << 27);
Rafael Espindola26585542015-01-19 21:11:14 +0000616 else
617 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & 0xff) | Index << 8 | (1 << 4);
618 }
619 }
Bill Wendlingeb872e02011-06-22 21:07:27 +0000620}
621
622void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
623 const MCAsmLayout &Layout) {
624 uint64_t StartAddress = 0;
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000625 for (const MCSection *Sec : Layout.getSectionOrder()) {
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000626 StartAddress = alignTo(StartAddress, Sec->getAlignment());
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000627 SectionAddress[Sec] = StartAddress;
628 StartAddress += Layout.getSectionAddressSize(Sec);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000629
630 // Explicitly pad the section to match the alignment requirements of the
631 // following one. This is for 'gas' compatibility, it shouldn't
632 /// strictly be necessary.
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000633 StartAddress += getPaddingSize(Sec, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000634 }
635}
636
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000637void MachObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
Bill Wendling21162212011-06-23 00:09:43 +0000638 const MCAsmLayout &Layout) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000639 computeSectionAddresses(Asm, Layout);
640
641 // Create symbol data for any indirect symbols.
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000642 bindIndirectSymbols(Asm);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000643}
644
Jim Grosbach36e60e92015-06-04 22:24:41 +0000645bool MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
Rafael Espindolae3a20f52015-10-05 12:07:05 +0000646 const MCAssembler &Asm, const MCSymbol &A, const MCSymbol &B,
647 bool InSet) const {
648 // FIXME: We don't handle things like
649 // foo = .
650 // creating atoms.
651 if (A.isVariable() || B.isVariable())
652 return false;
653 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, A, B,
654 InSet);
655}
656
657bool MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
Duncan P. N. Exon Smithd81ba532015-05-16 01:01:55 +0000658 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
Rafael Espindola35d61892015-04-17 21:15:17 +0000659 bool InSet, bool IsPCRel) const {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000660 if (InSet)
661 return true;
662
663 // The effective address is
664 // addr(atom(A)) + offset(A)
665 // - addr(atom(B)) - offset(B)
666 // and the offsets are not relocatable, so the fixup is fully resolved when
667 // addr(atom(A)) - addr(atom(B)) == 0.
Duncan P. N. Exon Smithd81ba532015-05-16 01:01:55 +0000668 const MCSymbol &SA = findAliasedSymbol(SymA);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000669 const MCSection &SecA = SA.getSection();
Rafael Espindola7549f872015-05-26 00:36:57 +0000670 const MCSection &SecB = *FB.getParent();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000671
672 if (IsPCRel) {
673 // The simple (Darwin, except on x86_64) way of dealing with this was to
674 // assume that any reference to a temporary symbol *must* be a temporary
675 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
676 // relocation to a temporary symbol (in the same section) is fully
677 // resolved. This also works in conjunction with absolutized .set, which
678 // requires the compiler to use .set to absolutize the differences between
679 // symbols which the compiler knows to be assembly time constants, so we
680 // don't need to worry about considering symbol differences fully resolved.
Jim Grosbachd6ae4ba2011-12-07 19:46:59 +0000681 //
682 // If the file isn't using sub-sections-via-symbols, we can make the
683 // same assumptions about any symbol that we normally make about
684 // assembler locals.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000685
Rafael Espindolaa063bdd2014-03-11 21:22:57 +0000686 bool hasReliableSymbolDifference = isX86_64();
687 if (!hasReliableSymbolDifference) {
Jim Grosbach40455072012-01-17 22:14:39 +0000688 if (!SA.isInSection() || &SecA != &SecB ||
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000689 (!SA.isTemporary() && FB.getAtom() != SA.getFragment()->getAtom() &&
Jim Grosbach35bc8f92012-01-24 21:45:25 +0000690 Asm.getSubsectionsViaSymbols()))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000691 return false;
692 return true;
693 }
Kevin Enderby7b46bb82011-09-08 20:53:44 +0000694 // For Darwin x86_64, there is one special case when the reference IsPCRel.
695 // If the fragment with the reference does not have a base symbol but meets
696 // the simple way of dealing with this, in that it is a temporary symbol in
697 // the same atom then it is assumed to be fully resolved. This is needed so
Eric Christopher460be992011-09-08 22:17:40 +0000698 // a relocation entry is not created and so the static linker does not
Kevin Enderby7b46bb82011-09-08 20:53:44 +0000699 // mess up the reference later.
700 else if(!FB.getAtom() &&
701 SA.isTemporary() && SA.isInSection() && &SecA == &SecB){
702 return true;
703 }
Bill Wendlingeb872e02011-06-22 21:07:27 +0000704 }
705
Rafael Espindolabfd0f012014-11-04 22:10:33 +0000706 // If they are not in the same section, we can't compute the diff.
707 if (&SecA != &SecB)
708 return false;
709
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000710 const MCFragment *FA = SA.getFragment();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000711
Benjamin Kramer91ea5112011-08-12 01:51:29 +0000712 // Bail if the symbol has no fragment.
713 if (!FA)
714 return false;
715
Bill Wendlingeb872e02011-06-22 21:07:27 +0000716 // If the atoms are the same, they are guaranteed to have the same address.
Duncan P. N. Exon Smith09bfa582015-05-16 00:48:58 +0000717 if (FA->getAtom() == FB.getAtom())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000718 return true;
719
720 // Otherwise, we can't prove this is fully resolved.
721 return false;
722}
723
Jim Grosbach36e60e92015-06-04 22:24:41 +0000724void MachObjectWriter::writeObject(MCAssembler &Asm,
Jim Grosbach46be3012011-12-06 00:13:09 +0000725 const MCAsmLayout &Layout) {
Rafael Espindola26585542015-01-19 21:11:14 +0000726 // Compute symbol table information and bind symbol indices.
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000727 computeSymbolTable(Asm, LocalSymbolData, ExternalSymbolData,
Rafael Espindola26585542015-01-19 21:11:14 +0000728 UndefinedSymbolData);
729
Bill Wendlingeb872e02011-06-22 21:07:27 +0000730 unsigned NumSections = Asm.size();
Jim Grosbach448334a2014-03-18 22:09:05 +0000731 const MCAssembler::VersionMinInfoType &VersionInfo =
732 Layout.getAssembler().getVersionMinInfo();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000733
734 // The section data starts after the header, the segment load command (and
735 // section headers) and the symbol table.
736 unsigned NumLoadCommands = 1;
737 uint64_t LoadCommandsSize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +0000738 sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64):
739 sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000740
Jim Grosbach448334a2014-03-18 22:09:05 +0000741 // Add the deployment target version info load command size, if used.
742 if (VersionInfo.Major != 0) {
743 ++NumLoadCommands;
744 LoadCommandsSize += sizeof(MachO::version_min_command);
745 }
746
Daniel Dunbareec0f322013-01-18 01:26:07 +0000747 // Add the data-in-code load command size, if used.
748 unsigned NumDataRegions = Asm.getDataRegions().size();
749 if (NumDataRegions) {
750 ++NumLoadCommands;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000751 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000752 }
753
Tim Northover53d32512014-03-29 07:34:53 +0000754 // Add the loh load command size, if used.
755 uint64_t LOHRawSize = Asm.getLOHContainer().getEmitSize(*this, Layout);
Rui Ueyamada00f2f2016-01-14 21:06:47 +0000756 uint64_t LOHSize = alignTo(LOHRawSize, is64Bit() ? 8 : 4);
Tim Northover53d32512014-03-29 07:34:53 +0000757 if (LOHSize) {
758 ++NumLoadCommands;
759 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
760 }
761
Bill Wendlingeb872e02011-06-22 21:07:27 +0000762 // Add the symbol table load command sizes, if used.
763 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
764 UndefinedSymbolData.size();
765 if (NumSymbols) {
766 NumLoadCommands += 2;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000767 LoadCommandsSize += (sizeof(MachO::symtab_command) +
768 sizeof(MachO::dysymtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000769 }
770
Daniel Dunbareec0f322013-01-18 01:26:07 +0000771 // Add the linker option load commands sizes.
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000772 for (const auto &Option : Asm.getLinkerOptions()) {
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000773 ++NumLoadCommands;
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000774 LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(Option, is64Bit());
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000775 }
NAKAMURA Takumia9cb5382015-09-22 11:14:39 +0000776
Bill Wendlingeb872e02011-06-22 21:07:27 +0000777 // Compute the total size of the section data, as well as its file size and vm
778 // size.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000779 uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) :
780 sizeof(MachO::mach_header)) + LoadCommandsSize;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000781 uint64_t SectionDataSize = 0;
782 uint64_t SectionDataFileSize = 0;
783 uint64_t VMSize = 0;
Rafael Espindola63702e22015-06-01 01:30:01 +0000784 for (const MCSection &Sec : Asm) {
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000785 uint64_t Address = getSectionAddress(&Sec);
786 uint64_t Size = Layout.getSectionAddressSize(&Sec);
787 uint64_t FileSize = Layout.getSectionFileSize(&Sec);
788 FileSize += getPaddingSize(&Sec, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000789
790 VMSize = std::max(VMSize, Address + Size);
791
Rafael Espindola63702e22015-06-01 01:30:01 +0000792 if (Sec.isVirtualSection())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000793 continue;
794
795 SectionDataSize = std::max(SectionDataSize, Address + Size);
796 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
797 }
798
799 // The section data is padded to 4 bytes.
800 //
801 // FIXME: Is this machine dependent?
802 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
803 SectionDataFileSize += SectionDataPadding;
804
805 // Write the prolog, starting with the header and load command...
Frederic Riss75c0c702015-08-26 05:09:46 +0000806 writeHeader(MachO::MH_OBJECT, NumLoadCommands, LoadCommandsSize,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000807 Asm.getSubsectionsViaSymbols());
Frederic Riss75c0c702015-08-26 05:09:46 +0000808 uint32_t Prot =
809 MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE;
810 writeSegmentLoadCommand("", NumSections, 0, VMSize, SectionDataStart,
811 SectionDataSize, Prot, Prot);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000812
813 // ... and then the section headers.
814 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
Frederic Riss75c0c702015-08-26 05:09:46 +0000815 for (const MCSection &Section : Asm) {
816 const auto &Sec = cast<MCSectionMachO>(Section);
Rafael Espindola63702e22015-06-01 01:30:01 +0000817 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
Bill Wendlingeb872e02011-06-22 21:07:27 +0000818 unsigned NumRelocs = Relocs.size();
Rafael Espindola63702e22015-06-01 01:30:01 +0000819 uint64_t SectionStart = SectionDataStart + getSectionAddress(&Sec);
Frederic Riss75c0c702015-08-26 05:09:46 +0000820 unsigned Flags = Sec.getTypeAndAttributes();
821 if (Sec.hasInstructions())
822 Flags |= MachO::S_ATTR_SOME_INSTRUCTIONS;
823 writeSection(Layout, Sec, getSectionAddress(&Sec), SectionStart, Flags,
824 RelocTableEnd, NumRelocs);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000825 RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000826 }
827
Jim Grosbach448334a2014-03-18 22:09:05 +0000828 // Write out the deployment target information, if it's available.
829 if (VersionInfo.Major != 0) {
830 assert(VersionInfo.Update < 256 && "unencodable update target version");
831 assert(VersionInfo.Minor < 256 && "unencodable minor target version");
832 assert(VersionInfo.Major < 65536 && "unencodable major target version");
833 uint32_t EncodedVersion = VersionInfo.Update | (VersionInfo.Minor << 8) |
834 (VersionInfo.Major << 16);
Tim Northover2d4d1612015-10-28 22:36:05 +0000835 MachO::LoadCommandType LCType;
836 switch (VersionInfo.Kind) {
837 case MCVM_OSXVersionMin:
838 LCType = MachO::LC_VERSION_MIN_MACOSX;
839 break;
840 case MCVM_IOSVersionMin:
841 LCType = MachO::LC_VERSION_MIN_IPHONEOS;
842 break;
843 case MCVM_TvOSVersionMin:
844 LCType = MachO::LC_VERSION_MIN_TVOS;
845 break;
846 case MCVM_WatchOSVersionMin:
847 LCType = MachO::LC_VERSION_MIN_WATCHOS;
848 break;
849 }
850 write32(LCType);
Jim Grosbach36e60e92015-06-04 22:24:41 +0000851 write32(sizeof(MachO::version_min_command));
852 write32(EncodedVersion);
853 write32(0); // reserved.
Jim Grosbach448334a2014-03-18 22:09:05 +0000854 }
855
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000856 // Write the data-in-code load command, if used.
857 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
858 if (NumDataRegions) {
859 uint64_t DataRegionsOffset = RelocTableEnd;
860 uint64_t DataRegionsSize = NumDataRegions * 8;
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000861 writeLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset,
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000862 DataRegionsSize);
863 }
864
Tim Northover53d32512014-03-29 07:34:53 +0000865 // Write the loh load command, if used.
866 uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize;
867 if (LOHSize)
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000868 writeLinkeditLoadCommand(MachO::LC_LINKER_OPTIMIZATION_HINT,
Tim Northover53d32512014-03-29 07:34:53 +0000869 DataInCodeTableEnd, LOHSize);
870
Bill Wendlingeb872e02011-06-22 21:07:27 +0000871 // Write the symbol table load command, if used.
872 if (NumSymbols) {
873 unsigned FirstLocalSymbol = 0;
874 unsigned NumLocalSymbols = LocalSymbolData.size();
875 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
876 unsigned NumExternalSymbols = ExternalSymbolData.size();
877 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
878 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
879 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
880 unsigned NumSymTabSymbols =
881 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
882 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
883 uint64_t IndirectSymbolOffset = 0;
884
885 // If used, the indirect symbols are written after the section data.
886 if (NumIndirectSymbols)
Tim Northover53d32512014-03-29 07:34:53 +0000887 IndirectSymbolOffset = LOHTableEnd;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000888
889 // The symbol table is written after the indirect symbol data.
Tim Northover53d32512014-03-29 07:34:53 +0000890 uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000891
892 // The string table is written after symbol table.
893 uint64_t StringTableOffset =
Charles Davis8bdfafd2013-09-01 04:28:48 +0000894 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ?
895 sizeof(MachO::nlist_64) :
896 sizeof(MachO::nlist));
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000897 writeSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
Rafael Espindola39751af2016-10-04 22:43:25 +0000898 StringTableOffset, StringTable.getSize());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000899
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000900 writeDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000901 FirstExternalSymbol, NumExternalSymbols,
902 FirstUndefinedSymbol, NumUndefinedSymbols,
903 IndirectSymbolOffset, NumIndirectSymbols);
904 }
905
Daniel Dunbareec0f322013-01-18 01:26:07 +0000906 // Write the linker options load commands.
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000907 for (const auto &Option : Asm.getLinkerOptions())
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000908 writeLinkerOptionsLoadCommand(Option);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000909
Bill Wendlingeb872e02011-06-22 21:07:27 +0000910 // Write the actual section data.
Rafael Espindola63702e22015-06-01 01:30:01 +0000911 for (const MCSection &Sec : Asm) {
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000912 Asm.writeSectionData(&Sec, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000913
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000914 uint64_t Pad = getPaddingSize(&Sec, Layout);
Benjamin Kramer97fbdd52015-04-17 11:12:43 +0000915 WriteZeros(Pad);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000916 }
917
918 // Write the extra padding.
919 WriteZeros(SectionDataPadding);
920
921 // Write the relocation entries.
Rafael Espindola63702e22015-06-01 01:30:01 +0000922 for (const MCSection &Sec : Asm) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000923 // Write the section relocation entries, in reverse order to match 'as'
924 // (approximately, the exact algorithm is more complicated than this).
Rafael Espindola63702e22015-06-01 01:30:01 +0000925 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000926 for (const RelAndSymbol &Rel : make_range(Relocs.rbegin(), Relocs.rend())) {
Jim Grosbach36e60e92015-06-04 22:24:41 +0000927 write32(Rel.MRE.r_word0);
928 write32(Rel.MRE.r_word1);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000929 }
930 }
931
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000932 // Write out the data-in-code region payload, if there is one.
933 for (MCAssembler::const_data_region_iterator
934 it = Asm.data_region_begin(), ie = Asm.data_region_end();
935 it != ie; ++it) {
936 const DataRegionData *Data = &(*it);
Duncan P. N. Exon Smith99d8a8e2015-05-20 00:02:39 +0000937 uint64_t Start = getSymbolAddress(*Data->Start, Layout);
938 uint64_t End = getSymbolAddress(*Data->End, Layout);
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000939 DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
940 << " start: " << Start << "(" << Data->Start->getName() << ")"
941 << " end: " << End << "(" << Data->End->getName() << ")"
942 << " size: " << End - Start
943 << "\n");
Jim Grosbach36e60e92015-06-04 22:24:41 +0000944 write32(Start);
945 write16(End - Start);
946 write16(Data->Kind);
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000947 }
948
Tim Northover53d32512014-03-29 07:34:53 +0000949 // Write out the loh commands, if there is one.
950 if (LOHSize) {
951#ifndef NDEBUG
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000952 unsigned Start = getStream().tell();
Tim Northover53d32512014-03-29 07:34:53 +0000953#endif
Jim Grosbach249af2a2015-06-01 23:55:06 +0000954 Asm.getLOHContainer().emit(*this, Layout);
Tim Northover53d32512014-03-29 07:34:53 +0000955 // Pad to a multiple of the pointer size.
Jim Grosbach36e60e92015-06-04 22:24:41 +0000956 writeBytes("", OffsetToAlignment(LOHRawSize, is64Bit() ? 8 : 4));
David Majnemerabdb2d2a2015-09-01 16:19:03 +0000957 assert(getStream().tell() - Start == LOHSize);
Tim Northover53d32512014-03-29 07:34:53 +0000958 }
959
Bill Wendlingeb872e02011-06-22 21:07:27 +0000960 // Write the symbol table data, if used.
961 if (NumSymbols) {
962 // Write the indirect symbol entries.
963 for (MCAssembler::const_indirect_symbol_iterator
964 it = Asm.indirect_symbol_begin(),
965 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
Alp Tokerf907b892013-12-05 05:44:44 +0000966 // Indirect symbols in the non-lazy symbol pointer section have some
Bill Wendlingeb872e02011-06-22 21:07:27 +0000967 // special handling.
968 const MCSectionMachO &Section =
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000969 static_cast<const MCSectionMachO &>(*it->Section);
David Majnemer7b583052014-03-07 07:36:05 +0000970 if (Section.getType() == MachO::S_NON_LAZY_SYMBOL_POINTERS) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000971 // If this symbol is defined and internal, mark it as such.
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000972 if (it->Symbol->isDefined() && !it->Symbol->isExternal()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000973 uint32_t Flags = MachO::INDIRECT_SYMBOL_LOCAL;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000974 if (it->Symbol->isAbsolute())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000975 Flags |= MachO::INDIRECT_SYMBOL_ABS;
Jim Grosbach36e60e92015-06-04 22:24:41 +0000976 write32(Flags);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000977 continue;
978 }
979 }
980
Jim Grosbach36e60e92015-06-04 22:24:41 +0000981 write32(it->Symbol->getIndex());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000982 }
983
984 // FIXME: Check that offsets match computed ones.
985
986 // Write the symbol table entries.
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000987 for (auto *SymbolData :
988 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
989 for (MachSymbolData &Entry : *SymbolData)
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000990 writeNlist(Entry, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000991
992 // Write the string table.
Rafael Espindola39751af2016-10-04 22:43:25 +0000993 StringTable.write(getStream());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000994 }
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +0000995}
996
Daniel Dunbar8888a962010-12-16 16:09:19 +0000997MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000998 raw_pwrite_stream &OS,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000999 bool IsLittleEndian) {
Daniel Dunbar03fcccb2010-12-16 17:21:02 +00001000 return new MachObjectWriter(MOTW, OS, IsLittleEndian);
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +00001001}