blob: d7934ad80c64f42734d47eb6811522de547889c1 [file] [log] [blame]
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +00001//===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Dunbar8888a962010-12-16 16:09:19 +000010#include "llvm/MC/MCMachObjectWriter.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000011#include "llvm/ADT/StringMap.h"
12#include "llvm/ADT/Twine.h"
Evan Cheng5928e692011-07-25 23:24:55 +000013#include "llvm/MC/MCAsmBackend.h"
Daniel Dunbar7c969552010-03-24 03:43:40 +000014#include "llvm/MC/MCAsmLayout.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/MC/MCAssembler.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000016#include "llvm/MC/MCExpr.h"
Craig Topper6e80c282012-03-26 06:58:25 +000017#include "llvm/MC/MCFixupKindInfo.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000018#include "llvm/MC/MCObjectWriter.h"
19#include "llvm/MC/MCSectionMachO.h"
Pete Cooper916f79e2015-06-08 17:17:28 +000020#include "llvm/MC/MCSymbolMachO.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000021#include "llvm/MC/MCValue.h"
Jim Grosbach4b63d2a2012-05-18 19:12:01 +000022#include "llvm/Support/Debug.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000023#include "llvm/Support/ErrorHandling.h"
Charles Davis8bdfafd2013-09-01 04:28:48 +000024#include "llvm/Support/MachO.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000025#include "llvm/Support/raw_ostream.h"
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000026#include <vector>
27using namespace llvm;
28
Chandler Carruthe96dd892014-04-21 22:55:11 +000029#define DEBUG_TYPE "mc"
30
Pedro Artigasb95c53e2012-12-14 18:52:11 +000031void MachObjectWriter::reset() {
32 Relocations.clear();
33 IndirectSymBase.clear();
34 StringTable.clear();
35 LocalSymbolData.clear();
36 ExternalSymbolData.clear();
37 UndefinedSymbolData.clear();
38 MCObjectWriter::reset();
39}
40
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +000041bool MachObjectWriter::doesSymbolRequireExternRelocation(const MCSymbol &S) {
Daniel Dunbar7de31062010-05-10 23:15:13 +000042 // Undefined symbols are always extern.
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +000043 if (S.isUndefined())
Daniel Dunbar7de31062010-05-10 23:15:13 +000044 return true;
45
46 // References to weak definitions require external relocation entries; the
47 // definition may not always be the one in the same object file.
Pete Cooper916f79e2015-06-08 17:17:28 +000048 if (cast<MCSymbolMachO>(S).isWeakDefinition())
Daniel Dunbar7de31062010-05-10 23:15:13 +000049 return true;
50
51 // Otherwise, we can use an internal relocation.
52 return false;
53}
54
Jim Grosbach28fcafb2011-06-24 23:44:37 +000055bool MachObjectWriter::
56MachSymbolData::operator<(const MachSymbolData &RHS) const {
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +000057 return Symbol->getName() < RHS.Symbol->getName();
Jim Grosbach28fcafb2011-06-24 23:44:37 +000058}
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000059
Jim Grosbach28fcafb2011-06-24 23:44:37 +000060bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
61 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
62 (MCFixupKind) Kind);
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000063
Jim Grosbach28fcafb2011-06-24 23:44:37 +000064 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
65}
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +000066
Jim Grosbach28fcafb2011-06-24 23:44:37 +000067uint64_t MachObjectWriter::getFragmentAddress(const MCFragment *Fragment,
68 const MCAsmLayout &Layout) const {
Rafael Espindola079027e2015-05-26 00:52:18 +000069 return getSectionAddress(Fragment->getParent()) +
Rafael Espindola7549f872015-05-26 00:36:57 +000070 Layout.getFragmentOffset(Fragment);
Jim Grosbach28fcafb2011-06-24 23:44:37 +000071}
Bill Wendlingeb872e02011-06-22 21:07:27 +000072
Duncan P. N. Exon Smith99d8a8e2015-05-20 00:02:39 +000073uint64_t MachObjectWriter::getSymbolAddress(const MCSymbol &S,
Bill Wendlingeb872e02011-06-22 21:07:27 +000074 const MCAsmLayout &Layout) const {
Bill Wendlingeb872e02011-06-22 21:07:27 +000075 // If this is a variable, then recursively evaluate now.
76 if (S.isVariable()) {
Jim Grosbachd96ef192012-09-13 23:11:25 +000077 if (const MCConstantExpr *C =
78 dyn_cast<const MCConstantExpr>(S.getVariableValue()))
79 return C->getValue();
80
81
Bill Wendlingeb872e02011-06-22 21:07:27 +000082 MCValue Target;
Jim Grosbach13760bd2015-05-30 01:25:56 +000083 if (!S.getVariableValue()->evaluateAsRelocatable(Target, &Layout, nullptr))
Bill Wendlingeb872e02011-06-22 21:07:27 +000084 report_fatal_error("unable to evaluate offset for variable '" +
85 S.getName() + "'");
86
87 // Verify that any used symbols are defined.
88 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
89 report_fatal_error("unable to evaluate offset to undefined symbol '" +
90 Target.getSymA()->getSymbol().getName() + "'");
91 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
92 report_fatal_error("unable to evaluate offset to undefined symbol '" +
93 Target.getSymB()->getSymbol().getName() + "'");
94
95 uint64_t Address = Target.getConstant();
96 if (Target.getSymA())
Duncan P. N. Exon Smith99d8a8e2015-05-20 00:02:39 +000097 Address += getSymbolAddress(Target.getSymA()->getSymbol(), Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +000098 if (Target.getSymB())
Duncan P. N. Exon Smith99d8a8e2015-05-20 00:02:39 +000099 Address += getSymbolAddress(Target.getSymB()->getSymbol(), Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000100 return Address;
101 }
102
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000103 return getSectionAddress(S.getFragment()->getParent()) +
Duncan P. N. Exon Smith2a404832015-05-19 23:53:20 +0000104 Layout.getSymbolOffset(S);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000105}
106
Rafael Espindola61e724a2015-05-26 01:15:30 +0000107uint64_t MachObjectWriter::getPaddingSize(const MCSection *Sec,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000108 const MCAsmLayout &Layout) const {
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000109 uint64_t EndAddr = getSectionAddress(Sec) + Layout.getSectionAddressSize(Sec);
Rafael Espindola61e724a2015-05-26 01:15:30 +0000110 unsigned Next = Sec->getLayoutOrder() + 1;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000111 if (Next >= Layout.getSectionOrder().size())
112 return 0;
113
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000114 const MCSection &NextSec = *Layout.getSectionOrder()[Next];
115 if (NextSec.isVirtualSection())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000116 return 0;
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000117 return OffsetToAlignment(EndAddr, NextSec.getAlignment());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000118}
119
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000120void MachObjectWriter::writeHeader(unsigned NumLoadCommands,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000121 unsigned LoadCommandsSize,
122 bool SubsectionsViaSymbols) {
123 uint32_t Flags = 0;
124
125 if (SubsectionsViaSymbols)
Charles Davis8bdfafd2013-09-01 04:28:48 +0000126 Flags |= MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000127
128 // struct mach_header (28 bytes) or
129 // struct mach_header_64 (32 bytes)
130
131 uint64_t Start = OS.tell();
132 (void) Start;
133
Jim Grosbach36e60e92015-06-04 22:24:41 +0000134 write32(is64Bit() ? MachO::MH_MAGIC_64 : MachO::MH_MAGIC);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000135
Jim Grosbach36e60e92015-06-04 22:24:41 +0000136 write32(TargetObjectWriter->getCPUType());
137 write32(TargetObjectWriter->getCPUSubtype());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000138
Jim Grosbach36e60e92015-06-04 22:24:41 +0000139 write32(MachO::MH_OBJECT);
140 write32(NumLoadCommands);
141 write32(LoadCommandsSize);
142 write32(Flags);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000143 if (is64Bit())
Jim Grosbach36e60e92015-06-04 22:24:41 +0000144 write32(0); // reserved
Bill Wendlingeb872e02011-06-22 21:07:27 +0000145
146 assert(OS.tell() - Start ==
Charles Davis8bdfafd2013-09-01 04:28:48 +0000147 (is64Bit()?sizeof(MachO::mach_header_64): sizeof(MachO::mach_header)));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000148}
149
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000150/// writeSegmentLoadCommand - Write a segment load command.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000151///
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000152/// \param NumSections The number of sections in this segment.
153/// \param SectionDataSize The total size of the sections.
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000154void MachObjectWriter::writeSegmentLoadCommand(unsigned NumSections,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000155 uint64_t VMSize,
156 uint64_t SectionDataStartOffset,
157 uint64_t SectionDataSize) {
158 // struct segment_command (56 bytes) or
159 // struct segment_command_64 (72 bytes)
160
161 uint64_t Start = OS.tell();
162 (void) Start;
163
164 unsigned SegmentLoadCommandSize =
Charles Davis8bdfafd2013-09-01 04:28:48 +0000165 is64Bit() ? sizeof(MachO::segment_command_64):
166 sizeof(MachO::segment_command);
Jim Grosbach36e60e92015-06-04 22:24:41 +0000167 write32(is64Bit() ? MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT);
168 write32(SegmentLoadCommandSize +
Charles Davis8bdfafd2013-09-01 04:28:48 +0000169 NumSections * (is64Bit() ? sizeof(MachO::section_64) :
170 sizeof(MachO::section)));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000171
Jim Grosbach36e60e92015-06-04 22:24:41 +0000172 writeBytes("", 16);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000173 if (is64Bit()) {
Jim Grosbach36e60e92015-06-04 22:24:41 +0000174 write64(0); // vmaddr
175 write64(VMSize); // vmsize
176 write64(SectionDataStartOffset); // file offset
177 write64(SectionDataSize); // file size
Bill Wendlingeb872e02011-06-22 21:07:27 +0000178 } else {
Jim Grosbach36e60e92015-06-04 22:24:41 +0000179 write32(0); // vmaddr
180 write32(VMSize); // vmsize
181 write32(SectionDataStartOffset); // file offset
182 write32(SectionDataSize); // file size
Bill Wendlingeb872e02011-06-22 21:07:27 +0000183 }
Nick Kledzikfe6813f2013-09-04 23:53:44 +0000184 // maxprot
Jim Grosbach36e60e92015-06-04 22:24:41 +0000185 write32(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE);
Nick Kledzikfe6813f2013-09-04 23:53:44 +0000186 // initprot
Jim Grosbach36e60e92015-06-04 22:24:41 +0000187 write32(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE);
188 write32(NumSections);
189 write32(0); // flags
Bill Wendlingeb872e02011-06-22 21:07:27 +0000190
191 assert(OS.tell() - Start == SegmentLoadCommandSize);
192}
193
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000194void MachObjectWriter::writeSection(const MCAssembler &Asm,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000195 const MCAsmLayout &Layout,
Rafael Espindola61e724a2015-05-26 01:15:30 +0000196 const MCSection &Sec, uint64_t FileOffset,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000197 uint64_t RelocationsStart,
198 unsigned NumRelocations) {
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000199 uint64_t SectionSize = Layout.getSectionAddressSize(&Sec);
Rafael Espindola61e724a2015-05-26 01:15:30 +0000200 const MCSectionMachO &Section = cast<MCSectionMachO>(Sec);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000201
202 // The offset is unused for virtual sections.
Rafael Espindola967d6a62015-05-21 21:02:35 +0000203 if (Section.isVirtualSection()) {
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000204 assert(Layout.getSectionFileSize(&Sec) == 0 && "Invalid file size!");
Bill Wendlingeb872e02011-06-22 21:07:27 +0000205 FileOffset = 0;
206 }
207
208 // struct section (68 bytes) or
209 // struct section_64 (80 bytes)
210
211 uint64_t Start = OS.tell();
212 (void) Start;
213
Jim Grosbach36e60e92015-06-04 22:24:41 +0000214 writeBytes(Section.getSectionName(), 16);
215 writeBytes(Section.getSegmentName(), 16);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000216 if (is64Bit()) {
Jim Grosbach36e60e92015-06-04 22:24:41 +0000217 write64(getSectionAddress(&Sec)); // address
218 write64(SectionSize); // size
Bill Wendlingeb872e02011-06-22 21:07:27 +0000219 } else {
Jim Grosbach36e60e92015-06-04 22:24:41 +0000220 write32(getSectionAddress(&Sec)); // address
221 write32(SectionSize); // size
Bill Wendlingeb872e02011-06-22 21:07:27 +0000222 }
Jim Grosbach36e60e92015-06-04 22:24:41 +0000223 write32(FileOffset);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000224
225 unsigned Flags = Section.getTypeAndAttributes();
Rafael Espindolacd625182015-05-25 18:34:26 +0000226 if (Section.hasInstructions())
David Majnemer7b583052014-03-07 07:36:05 +0000227 Flags |= MachO::S_ATTR_SOME_INSTRUCTIONS;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000228
Rafael Espindola967d6a62015-05-21 21:02:35 +0000229 assert(isPowerOf2_32(Section.getAlignment()) && "Invalid alignment!");
Jim Grosbach36e60e92015-06-04 22:24:41 +0000230 write32(Log2_32(Section.getAlignment()));
231 write32(NumRelocations ? RelocationsStart : 0);
232 write32(NumRelocations);
233 write32(Flags);
234 write32(IndirectSymBase.lookup(&Sec)); // reserved1
235 write32(Section.getStubSize()); // reserved2
Bill Wendlingeb872e02011-06-22 21:07:27 +0000236 if (is64Bit())
Jim Grosbach36e60e92015-06-04 22:24:41 +0000237 write32(0); // reserved3
Bill Wendlingeb872e02011-06-22 21:07:27 +0000238
Charles Davis8bdfafd2013-09-01 04:28:48 +0000239 assert(OS.tell() - Start == (is64Bit() ? sizeof(MachO::section_64) :
240 sizeof(MachO::section)));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000241}
242
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000243void MachObjectWriter::writeSymtabLoadCommand(uint32_t SymbolOffset,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000244 uint32_t NumSymbols,
245 uint32_t StringTableOffset,
246 uint32_t StringTableSize) {
247 // struct symtab_command (24 bytes)
248
249 uint64_t Start = OS.tell();
250 (void) Start;
251
Jim Grosbach36e60e92015-06-04 22:24:41 +0000252 write32(MachO::LC_SYMTAB);
253 write32(sizeof(MachO::symtab_command));
254 write32(SymbolOffset);
255 write32(NumSymbols);
256 write32(StringTableOffset);
257 write32(StringTableSize);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000258
Charles Davis8bdfafd2013-09-01 04:28:48 +0000259 assert(OS.tell() - Start == sizeof(MachO::symtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000260}
261
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000262void MachObjectWriter::writeDysymtabLoadCommand(uint32_t FirstLocalSymbol,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000263 uint32_t NumLocalSymbols,
264 uint32_t FirstExternalSymbol,
265 uint32_t NumExternalSymbols,
266 uint32_t FirstUndefinedSymbol,
267 uint32_t NumUndefinedSymbols,
268 uint32_t IndirectSymbolOffset,
269 uint32_t NumIndirectSymbols) {
270 // struct dysymtab_command (80 bytes)
271
272 uint64_t Start = OS.tell();
273 (void) Start;
274
Jim Grosbach36e60e92015-06-04 22:24:41 +0000275 write32(MachO::LC_DYSYMTAB);
276 write32(sizeof(MachO::dysymtab_command));
277 write32(FirstLocalSymbol);
278 write32(NumLocalSymbols);
279 write32(FirstExternalSymbol);
280 write32(NumExternalSymbols);
281 write32(FirstUndefinedSymbol);
282 write32(NumUndefinedSymbols);
283 write32(0); // tocoff
284 write32(0); // ntoc
285 write32(0); // modtaboff
286 write32(0); // nmodtab
287 write32(0); // extrefsymoff
288 write32(0); // nextrefsyms
289 write32(IndirectSymbolOffset);
290 write32(NumIndirectSymbols);
291 write32(0); // extreloff
292 write32(0); // nextrel
293 write32(0); // locreloff
294 write32(0); // nlocrel
Bill Wendlingeb872e02011-06-22 21:07:27 +0000295
Charles Davis8bdfafd2013-09-01 04:28:48 +0000296 assert(OS.tell() - Start == sizeof(MachO::dysymtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000297}
298
Tim Northovereaef0742014-05-30 13:22:59 +0000299MachObjectWriter::MachSymbolData *
300MachObjectWriter::findSymbolData(const MCSymbol &Sym) {
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000301 for (auto *SymbolData :
302 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
303 for (MachSymbolData &Entry : *SymbolData)
304 if (Entry.Symbol == &Sym)
305 return &Entry;
Tim Northovereaef0742014-05-30 13:22:59 +0000306
307 return nullptr;
308}
309
Rafael Espindola7f4e07b2015-04-17 12:28:43 +0000310const MCSymbol &MachObjectWriter::findAliasedSymbol(const MCSymbol &Sym) const {
311 const MCSymbol *S = &Sym;
312 while (S->isVariable()) {
313 const MCExpr *Value = S->getVariableValue();
314 const auto *Ref = dyn_cast<MCSymbolRefExpr>(Value);
315 if (!Ref)
316 return *S;
317 S = &Ref->getSymbol();
318 }
319 return *S;
320}
321
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000322void MachObjectWriter::writeNlist(MachSymbolData &MSD,
Bill Wendling21162212011-06-23 00:09:43 +0000323 const MCAsmLayout &Layout) {
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +0000324 const MCSymbol *Symbol = MSD.Symbol;
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000325 const MCSymbol &Data = *Symbol;
Rafael Espindola7f4e07b2015-04-17 12:28:43 +0000326 const MCSymbol *AliasedSymbol = &findAliasedSymbol(*Symbol);
Tim Northovereaef0742014-05-30 13:22:59 +0000327 uint8_t SectionIndex = MSD.SectionIndex;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000328 uint8_t Type = 0;
Jim Grosbacha3171602011-08-09 22:12:37 +0000329 uint64_t Address = 0;
Tim Northovereaef0742014-05-30 13:22:59 +0000330 bool IsAlias = Symbol != AliasedSymbol;
331
Duncan P. N. Exon Smith24f47752015-05-21 00:39:24 +0000332 const MCSymbol &OrigSymbol = *Symbol;
Tim Northovereaef0742014-05-30 13:22:59 +0000333 MachSymbolData *AliaseeInfo;
334 if (IsAlias) {
335 AliaseeInfo = findSymbolData(*AliasedSymbol);
336 if (AliaseeInfo)
337 SectionIndex = AliaseeInfo->SectionIndex;
338 Symbol = AliasedSymbol;
Duncan P. N. Exon Smith24f47752015-05-21 00:39:24 +0000339 // FIXME: Should this update Data as well? Do we need OrigSymbol at all?
Tim Northovereaef0742014-05-30 13:22:59 +0000340 }
Bill Wendlingeb872e02011-06-22 21:07:27 +0000341
342 // Set the N_TYPE bits. See <mach-o/nlist.h>.
343 //
344 // FIXME: Are the prebound or indirect fields possible here?
Tim Northovereaef0742014-05-30 13:22:59 +0000345 if (IsAlias && Symbol->isUndefined())
346 Type = MachO::N_INDR;
347 else if (Symbol->isUndefined())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000348 Type = MachO::N_UNDF;
Tim Northovereaef0742014-05-30 13:22:59 +0000349 else if (Symbol->isAbsolute())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000350 Type = MachO::N_ABS;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000351 else
Charles Davis8bdfafd2013-09-01 04:28:48 +0000352 Type = MachO::N_SECT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000353
354 // FIXME: Set STAB bits.
355
356 if (Data.isPrivateExtern())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000357 Type |= MachO::N_PEXT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000358
359 // Set external bit.
Tim Northovereaef0742014-05-30 13:22:59 +0000360 if (Data.isExternal() || (!IsAlias && Symbol->isUndefined()))
Charles Davis8bdfafd2013-09-01 04:28:48 +0000361 Type |= MachO::N_EXT;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000362
363 // Compute the symbol address.
Tim Northovereaef0742014-05-30 13:22:59 +0000364 if (IsAlias && Symbol->isUndefined())
365 Address = AliaseeInfo->StringIndex;
366 else if (Symbol->isDefined())
Duncan P. N. Exon Smith24f47752015-05-21 00:39:24 +0000367 Address = getSymbolAddress(OrigSymbol, Layout);
Rafael Espindola14672502015-05-29 17:48:04 +0000368 else if (Symbol->isCommon()) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000369 // Common symbols are encoded with the size in the address
370 // field, and their alignment in the flags.
Rafael Espindola14672502015-05-29 17:48:04 +0000371 Address = Symbol->getCommonSize();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000372 }
373
374 // struct nlist (12 bytes)
375
Jim Grosbach36e60e92015-06-04 22:24:41 +0000376 write32(MSD.StringIndex);
377 write8(Type);
378 write8(SectionIndex);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000379
380 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
381 // value.
Pete Cooper916f79e2015-06-08 17:17:28 +0000382 write16(cast<MCSymbolMachO>(Symbol)->getEncodedFlags());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000383 if (is64Bit())
Jim Grosbach36e60e92015-06-04 22:24:41 +0000384 write64(Address);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000385 else
Jim Grosbach36e60e92015-06-04 22:24:41 +0000386 write32(Address);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000387}
388
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000389void MachObjectWriter::writeLinkeditLoadCommand(uint32_t Type,
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000390 uint32_t DataOffset,
391 uint32_t DataSize) {
392 uint64_t Start = OS.tell();
393 (void) Start;
394
Jim Grosbach36e60e92015-06-04 22:24:41 +0000395 write32(Type);
396 write32(sizeof(MachO::linkedit_data_command));
397 write32(DataOffset);
398 write32(DataSize);
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000399
Charles Davis8bdfafd2013-09-01 04:28:48 +0000400 assert(OS.tell() - Start == sizeof(MachO::linkedit_data_command));
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000401}
402
Daniel Dunbareec0f322013-01-18 01:26:07 +0000403static unsigned ComputeLinkerOptionsLoadCommandSize(
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000404 const std::vector<std::string> &Options, bool is64Bit)
Daniel Dunbareec0f322013-01-18 01:26:07 +0000405{
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +0000406 unsigned Size = sizeof(MachO::linker_option_command);
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000407 for (const std::string &Option : Options)
408 Size += Option.size() + 1;
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000409 return RoundUpToAlignment(Size, is64Bit ? 8 : 4);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000410}
411
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000412void MachObjectWriter::writeLinkerOptionsLoadCommand(
Daniel Dunbareec0f322013-01-18 01:26:07 +0000413 const std::vector<std::string> &Options)
414{
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000415 unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit());
Daniel Dunbareec0f322013-01-18 01:26:07 +0000416 uint64_t Start = OS.tell();
417 (void) Start;
418
Jim Grosbach36e60e92015-06-04 22:24:41 +0000419 write32(MachO::LC_LINKER_OPTION);
420 write32(Size);
421 write32(Options.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +0000422 uint64_t BytesWritten = sizeof(MachO::linker_option_command);
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000423 for (const std::string &Option : Options) {
Daniel Dunbareec0f322013-01-18 01:26:07 +0000424 // Write each string, including the null byte.
Jim Grosbach36e60e92015-06-04 22:24:41 +0000425 writeBytes(Option.c_str(), Option.size() + 1);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000426 BytesWritten += Option.size() + 1;
427 }
428
Daniel Dunbar34ea79f2013-01-22 03:42:49 +0000429 // Pad to a multiple of the pointer size.
Jim Grosbach36e60e92015-06-04 22:24:41 +0000430 writeBytes("", OffsetToAlignment(BytesWritten, is64Bit() ? 8 : 4));
Daniel Dunbareec0f322013-01-18 01:26:07 +0000431
432 assert(OS.tell() - Start == Size);
433}
434
Jim Grosbach36e60e92015-06-04 22:24:41 +0000435void MachObjectWriter::recordRelocation(MCAssembler &Asm,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000436 const MCAsmLayout &Layout,
437 const MCFragment *Fragment,
Rafael Espindola26585542015-01-19 21:11:14 +0000438 const MCFixup &Fixup, MCValue Target,
439 bool &IsPCRel, uint64_t &FixedValue) {
Jim Grosbach36e60e92015-06-04 22:24:41 +0000440 TargetObjectWriter->recordRelocation(this, Asm, Layout, Fragment, Fixup,
Jim Grosbach28fcafb2011-06-24 23:44:37 +0000441 Target, FixedValue);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000442}
443
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000444void MachObjectWriter::bindIndirectSymbols(MCAssembler &Asm) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000445 // This is the point where 'as' creates actual symbols for indirect symbols
446 // (in the following two passes). It would be easier for us to do this sooner
447 // when we see the attribute, but that makes getting the order in the symbol
448 // table much more complicated than it is worth.
449 //
450 // FIXME: Revisit this when the dust settles.
451
Kevin Enderby3aeada22013-08-28 17:50:59 +0000452 // Report errors for use of .indirect_symbol not in a symbol pointer section
453 // or stub section.
454 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
455 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000456 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
Kevin Enderby3aeada22013-08-28 17:50:59 +0000457
David Majnemer7b583052014-03-07 07:36:05 +0000458 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
459 Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
460 Section.getType() != MachO::S_SYMBOL_STUBS) {
Kevin Enderby3aeada22013-08-28 17:50:59 +0000461 MCSymbol &Symbol = *it->Symbol;
462 report_fatal_error("indirect symbol '" + Symbol.getName() +
463 "' not in a symbol pointer or stub section");
464 }
465 }
466
Alp Tokerf907b892013-12-05 05:44:44 +0000467 // Bind non-lazy symbol pointers first.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000468 unsigned IndirectIndex = 0;
469 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
470 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000471 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000472
David Majnemer7b583052014-03-07 07:36:05 +0000473 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS)
Bill Wendlingeb872e02011-06-22 21:07:27 +0000474 continue;
475
476 // Initialize the section indirect symbol base, if necessary.
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000477 IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000478
Rafael Espindolab5d316b2015-05-29 20:21:02 +0000479 Asm.registerSymbol(*it->Symbol);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000480 }
481
482 // Then lazy symbol pointers and symbol stubs.
483 IndirectIndex = 0;
484 for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
485 ie = Asm.indirect_symbol_end(); it != ie; ++it, ++IndirectIndex) {
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000486 const MCSectionMachO &Section = cast<MCSectionMachO>(*it->Section);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000487
David Majnemer7b583052014-03-07 07:36:05 +0000488 if (Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
489 Section.getType() != MachO::S_SYMBOL_STUBS)
Bill Wendlingeb872e02011-06-22 21:07:27 +0000490 continue;
491
492 // Initialize the section indirect symbol base, if necessary.
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000493 IndirectSymBase.insert(std::make_pair(it->Section, IndirectIndex));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000494
495 // Set the symbol type to undefined lazy, but only on construction.
496 //
497 // FIXME: Do not hardcode.
498 bool Created;
Rafael Espindolab5d316b2015-05-29 20:21:02 +0000499 Asm.registerSymbol(*it->Symbol, &Created);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000500 if (Created)
Pete Cooper916f79e2015-06-08 17:17:28 +0000501 cast<MCSymbolMachO>(it->Symbol)->setReferenceTypeUndefinedLazy(true);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000502 }
503}
504
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000505/// computeSymbolTable - Compute the symbol table data
506void MachObjectWriter::computeSymbolTable(
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000507 MCAssembler &Asm, std::vector<MachSymbolData> &LocalSymbolData,
508 std::vector<MachSymbolData> &ExternalSymbolData,
509 std::vector<MachSymbolData> &UndefinedSymbolData) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000510 // Build section lookup table.
511 DenseMap<const MCSection*, uint8_t> SectionIndexMap;
512 unsigned Index = 1;
513 for (MCAssembler::iterator it = Asm.begin(),
514 ie = Asm.end(); it != ie; ++it, ++Index)
Rafael Espindolaa554c052015-05-25 23:14:17 +0000515 SectionIndexMap[&*it] = Index;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000516 assert(Index <= 256 && "Too many sections!");
517
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000518 // Build the string table.
Duncan P. N. Exon Smithf48de1c2015-05-16 00:35:24 +0000519 for (const MCSymbol &Symbol : Asm.symbols()) {
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000520 if (!Asm.isSymbolLinkerVisible(Symbol))
521 continue;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000522
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000523 StringTable.add(Symbol.getName());
524 }
525 StringTable.finalize(StringTableBuilder::MachO);
526
527 // Build the symbol arrays but only for non-local symbols.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000528 //
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000529 // The particular order that we collect and then sort the symbols is chosen to
530 // match 'as'. Even though it doesn't matter for correctness, this is
531 // important for letting us diff .o files.
Duncan P. N. Exon Smithf48de1c2015-05-16 00:35:24 +0000532 for (const MCSymbol &Symbol : Asm.symbols()) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000533 // Ignore non-linker visible symbols.
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000534 if (!Asm.isSymbolLinkerVisible(Symbol))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000535 continue;
536
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000537 if (!Symbol.isExternal() && !Symbol.isUndefined())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000538 continue;
539
Bill Wendlingeb872e02011-06-22 21:07:27 +0000540 MachSymbolData MSD;
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +0000541 MSD.Symbol = &Symbol;
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000542 MSD.StringIndex = StringTable.getOffset(Symbol.getName());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000543
544 if (Symbol.isUndefined()) {
545 MSD.SectionIndex = 0;
546 UndefinedSymbolData.push_back(MSD);
547 } else if (Symbol.isAbsolute()) {
548 MSD.SectionIndex = 0;
549 ExternalSymbolData.push_back(MSD);
550 } else {
551 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
552 assert(MSD.SectionIndex && "Invalid section index!");
553 ExternalSymbolData.push_back(MSD);
554 }
555 }
556
557 // Now add the data for local symbols.
Duncan P. N. Exon Smithf48de1c2015-05-16 00:35:24 +0000558 for (const MCSymbol &Symbol : Asm.symbols()) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000559 // Ignore non-linker visible symbols.
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000560 if (!Asm.isSymbolLinkerVisible(Symbol))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000561 continue;
562
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000563 if (Symbol.isExternal() || Symbol.isUndefined())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000564 continue;
565
Bill Wendlingeb872e02011-06-22 21:07:27 +0000566 MachSymbolData MSD;
Duncan P. N. Exon Smith08b87262015-05-20 15:16:14 +0000567 MSD.Symbol = &Symbol;
Rafael Espindola2d6bae22015-06-22 17:52:52 +0000568 StringRef Name = Symbol.getName();
569 MSD.StringIndex = Name.empty() ? 0 : StringTable.getOffset(Name);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000570
571 if (Symbol.isAbsolute()) {
572 MSD.SectionIndex = 0;
573 LocalSymbolData.push_back(MSD);
574 } else {
575 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
576 assert(MSD.SectionIndex && "Invalid section index!");
577 LocalSymbolData.push_back(MSD);
578 }
579 }
580
581 // External and undefined symbols are required to be in lexicographic order.
582 std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
583 std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
584
585 // Set the symbol indices.
586 Index = 0;
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000587 for (auto *SymbolData :
588 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
589 for (MachSymbolData &Entry : *SymbolData)
590 Entry.Symbol->setIndex(Index++);
Rafael Espindola26585542015-01-19 21:11:14 +0000591
Rafael Espindolaa554c052015-05-25 23:14:17 +0000592 for (const MCSection &Section : Asm) {
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000593 for (RelAndSymbol &Rel : Relocations[&Section]) {
Rafael Espindola26585542015-01-19 21:11:14 +0000594 if (!Rel.Sym)
595 continue;
596
597 // Set the Index and the IsExtern bit.
Duncan P. N. Exon Smith1247bbd2015-05-22 05:54:01 +0000598 unsigned Index = Rel.Sym->getIndex();
Rafael Espindola26585542015-01-19 21:11:14 +0000599 assert(isInt<24>(Index));
600 if (IsLittleEndian)
Justin Bognerd4e08a02015-05-14 23:54:49 +0000601 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & (~0U << 24)) | Index | (1 << 27);
Rafael Espindola26585542015-01-19 21:11:14 +0000602 else
603 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & 0xff) | Index << 8 | (1 << 4);
604 }
605 }
Bill Wendlingeb872e02011-06-22 21:07:27 +0000606}
607
608void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm,
609 const MCAsmLayout &Layout) {
610 uint64_t StartAddress = 0;
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000611 for (const MCSection *Sec : Layout.getSectionOrder()) {
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000612 StartAddress = RoundUpToAlignment(StartAddress, Sec->getAlignment());
613 SectionAddress[Sec] = StartAddress;
614 StartAddress += Layout.getSectionAddressSize(Sec);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000615
616 // Explicitly pad the section to match the alignment requirements of the
617 // following one. This is for 'gas' compatibility, it shouldn't
618 /// strictly be necessary.
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000619 StartAddress += getPaddingSize(Sec, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000620 }
621}
622
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000623void MachObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
Bill Wendling21162212011-06-23 00:09:43 +0000624 const MCAsmLayout &Layout) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000625 computeSectionAddresses(Asm, Layout);
626
627 // Create symbol data for any indirect symbols.
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000628 bindIndirectSymbols(Asm);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000629}
630
Jim Grosbach36e60e92015-06-04 22:24:41 +0000631bool MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
Duncan P. N. Exon Smithd81ba532015-05-16 01:01:55 +0000632 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
Rafael Espindola35d61892015-04-17 21:15:17 +0000633 bool InSet, bool IsPCRel) const {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000634 if (InSet)
635 return true;
636
637 // The effective address is
638 // addr(atom(A)) + offset(A)
639 // - addr(atom(B)) - offset(B)
640 // and the offsets are not relocatable, so the fixup is fully resolved when
641 // addr(atom(A)) - addr(atom(B)) == 0.
Duncan P. N. Exon Smithd81ba532015-05-16 01:01:55 +0000642 const MCSymbol &SA = findAliasedSymbol(SymA);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000643 const MCSection &SecA = SA.getSection();
Rafael Espindola7549f872015-05-26 00:36:57 +0000644 const MCSection &SecB = *FB.getParent();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000645
646 if (IsPCRel) {
647 // The simple (Darwin, except on x86_64) way of dealing with this was to
648 // assume that any reference to a temporary symbol *must* be a temporary
649 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
650 // relocation to a temporary symbol (in the same section) is fully
651 // resolved. This also works in conjunction with absolutized .set, which
652 // requires the compiler to use .set to absolutize the differences between
653 // symbols which the compiler knows to be assembly time constants, so we
654 // don't need to worry about considering symbol differences fully resolved.
Jim Grosbachd6ae4ba2011-12-07 19:46:59 +0000655 //
656 // If the file isn't using sub-sections-via-symbols, we can make the
657 // same assumptions about any symbol that we normally make about
658 // assembler locals.
Bill Wendlingeb872e02011-06-22 21:07:27 +0000659
Rafael Espindolaa063bdd2014-03-11 21:22:57 +0000660 bool hasReliableSymbolDifference = isX86_64();
661 if (!hasReliableSymbolDifference) {
Jim Grosbach40455072012-01-17 22:14:39 +0000662 if (!SA.isInSection() || &SecA != &SecB ||
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000663 (!SA.isTemporary() && FB.getAtom() != SA.getFragment()->getAtom() &&
Jim Grosbach35bc8f92012-01-24 21:45:25 +0000664 Asm.getSubsectionsViaSymbols()))
Bill Wendlingeb872e02011-06-22 21:07:27 +0000665 return false;
666 return true;
667 }
Kevin Enderby7b46bb82011-09-08 20:53:44 +0000668 // For Darwin x86_64, there is one special case when the reference IsPCRel.
669 // If the fragment with the reference does not have a base symbol but meets
670 // the simple way of dealing with this, in that it is a temporary symbol in
671 // the same atom then it is assumed to be fully resolved. This is needed so
Eric Christopher460be992011-09-08 22:17:40 +0000672 // a relocation entry is not created and so the static linker does not
Kevin Enderby7b46bb82011-09-08 20:53:44 +0000673 // mess up the reference later.
674 else if(!FB.getAtom() &&
675 SA.isTemporary() && SA.isInSection() && &SecA == &SecB){
676 return true;
677 }
Bill Wendlingeb872e02011-06-22 21:07:27 +0000678 }
679
Rafael Espindolabfd0f012014-11-04 22:10:33 +0000680 // If they are not in the same section, we can't compute the diff.
681 if (&SecA != &SecB)
682 return false;
683
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000684 const MCFragment *FA = SA.getFragment();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000685
Benjamin Kramer91ea5112011-08-12 01:51:29 +0000686 // Bail if the symbol has no fragment.
687 if (!FA)
688 return false;
689
Bill Wendlingeb872e02011-06-22 21:07:27 +0000690 // If the atoms are the same, they are guaranteed to have the same address.
Duncan P. N. Exon Smith09bfa582015-05-16 00:48:58 +0000691 if (FA->getAtom() == FB.getAtom())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000692 return true;
693
694 // Otherwise, we can't prove this is fully resolved.
695 return false;
696}
697
Jim Grosbach36e60e92015-06-04 22:24:41 +0000698void MachObjectWriter::writeObject(MCAssembler &Asm,
Jim Grosbach46be3012011-12-06 00:13:09 +0000699 const MCAsmLayout &Layout) {
Rafael Espindola26585542015-01-19 21:11:14 +0000700 // Compute symbol table information and bind symbol indices.
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000701 computeSymbolTable(Asm, LocalSymbolData, ExternalSymbolData,
Rafael Espindola26585542015-01-19 21:11:14 +0000702 UndefinedSymbolData);
703
Bill Wendlingeb872e02011-06-22 21:07:27 +0000704 unsigned NumSections = Asm.size();
Jim Grosbach448334a2014-03-18 22:09:05 +0000705 const MCAssembler::VersionMinInfoType &VersionInfo =
706 Layout.getAssembler().getVersionMinInfo();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000707
708 // The section data starts after the header, the segment load command (and
709 // section headers) and the symbol table.
710 unsigned NumLoadCommands = 1;
711 uint64_t LoadCommandsSize = is64Bit() ?
Charles Davis8bdfafd2013-09-01 04:28:48 +0000712 sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64):
713 sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000714
Jim Grosbach448334a2014-03-18 22:09:05 +0000715 // Add the deployment target version info load command size, if used.
716 if (VersionInfo.Major != 0) {
717 ++NumLoadCommands;
718 LoadCommandsSize += sizeof(MachO::version_min_command);
719 }
720
Daniel Dunbareec0f322013-01-18 01:26:07 +0000721 // Add the data-in-code load command size, if used.
722 unsigned NumDataRegions = Asm.getDataRegions().size();
723 if (NumDataRegions) {
724 ++NumLoadCommands;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000725 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000726 }
727
Tim Northover53d32512014-03-29 07:34:53 +0000728 // Add the loh load command size, if used.
729 uint64_t LOHRawSize = Asm.getLOHContainer().getEmitSize(*this, Layout);
730 uint64_t LOHSize = RoundUpToAlignment(LOHRawSize, is64Bit() ? 8 : 4);
731 if (LOHSize) {
732 ++NumLoadCommands;
733 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
734 }
735
Bill Wendlingeb872e02011-06-22 21:07:27 +0000736 // Add the symbol table load command sizes, if used.
737 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
738 UndefinedSymbolData.size();
739 if (NumSymbols) {
740 NumLoadCommands += 2;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000741 LoadCommandsSize += (sizeof(MachO::symtab_command) +
742 sizeof(MachO::dysymtab_command));
Bill Wendlingeb872e02011-06-22 21:07:27 +0000743 }
744
Daniel Dunbareec0f322013-01-18 01:26:07 +0000745 // Add the linker option load commands sizes.
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000746 for (const auto &Option : Asm.getLinkerOptions()) {
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000747 ++NumLoadCommands;
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000748 LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(Option, is64Bit());
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000749 }
Daniel Dunbareec0f322013-01-18 01:26:07 +0000750
Bill Wendlingeb872e02011-06-22 21:07:27 +0000751 // Compute the total size of the section data, as well as its file size and vm
752 // size.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000753 uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) :
754 sizeof(MachO::mach_header)) + LoadCommandsSize;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000755 uint64_t SectionDataSize = 0;
756 uint64_t SectionDataFileSize = 0;
757 uint64_t VMSize = 0;
Rafael Espindola63702e22015-06-01 01:30:01 +0000758 for (const MCSection &Sec : Asm) {
Rafael Espindola5a1e80b2015-05-26 02:00:36 +0000759 uint64_t Address = getSectionAddress(&Sec);
760 uint64_t Size = Layout.getSectionAddressSize(&Sec);
761 uint64_t FileSize = Layout.getSectionFileSize(&Sec);
762 FileSize += getPaddingSize(&Sec, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000763
764 VMSize = std::max(VMSize, Address + Size);
765
Rafael Espindola63702e22015-06-01 01:30:01 +0000766 if (Sec.isVirtualSection())
Bill Wendlingeb872e02011-06-22 21:07:27 +0000767 continue;
768
769 SectionDataSize = std::max(SectionDataSize, Address + Size);
770 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
771 }
772
773 // The section data is padded to 4 bytes.
774 //
775 // FIXME: Is this machine dependent?
776 unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
777 SectionDataFileSize += SectionDataPadding;
778
779 // Write the prolog, starting with the header and load command...
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000780 writeHeader(NumLoadCommands, LoadCommandsSize,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000781 Asm.getSubsectionsViaSymbols());
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000782 writeSegmentLoadCommand(NumSections, VMSize,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000783 SectionDataStart, SectionDataSize);
784
785 // ... and then the section headers.
786 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
Rafael Espindola63702e22015-06-01 01:30:01 +0000787 for (const MCSection &Sec : Asm) {
788 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
Bill Wendlingeb872e02011-06-22 21:07:27 +0000789 unsigned NumRelocs = Relocs.size();
Rafael Espindola63702e22015-06-01 01:30:01 +0000790 uint64_t SectionStart = SectionDataStart + getSectionAddress(&Sec);
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000791 writeSection(Asm, Layout, Sec, SectionStart, RelocTableEnd, NumRelocs);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000792 RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000793 }
794
Jim Grosbach448334a2014-03-18 22:09:05 +0000795 // Write out the deployment target information, if it's available.
796 if (VersionInfo.Major != 0) {
797 assert(VersionInfo.Update < 256 && "unencodable update target version");
798 assert(VersionInfo.Minor < 256 && "unencodable minor target version");
799 assert(VersionInfo.Major < 65536 && "unencodable major target version");
800 uint32_t EncodedVersion = VersionInfo.Update | (VersionInfo.Minor << 8) |
801 (VersionInfo.Major << 16);
Jim Grosbach36e60e92015-06-04 22:24:41 +0000802 write32(VersionInfo.Kind == MCVM_OSXVersionMin ? MachO::LC_VERSION_MIN_MACOSX :
Jim Grosbach448334a2014-03-18 22:09:05 +0000803 MachO::LC_VERSION_MIN_IPHONEOS);
Jim Grosbach36e60e92015-06-04 22:24:41 +0000804 write32(sizeof(MachO::version_min_command));
805 write32(EncodedVersion);
806 write32(0); // reserved.
Jim Grosbach448334a2014-03-18 22:09:05 +0000807 }
808
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000809 // Write the data-in-code load command, if used.
810 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
811 if (NumDataRegions) {
812 uint64_t DataRegionsOffset = RelocTableEnd;
813 uint64_t DataRegionsSize = NumDataRegions * 8;
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000814 writeLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset,
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000815 DataRegionsSize);
816 }
817
Tim Northover53d32512014-03-29 07:34:53 +0000818 // Write the loh load command, if used.
819 uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize;
820 if (LOHSize)
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000821 writeLinkeditLoadCommand(MachO::LC_LINKER_OPTIMIZATION_HINT,
Tim Northover53d32512014-03-29 07:34:53 +0000822 DataInCodeTableEnd, LOHSize);
823
Bill Wendlingeb872e02011-06-22 21:07:27 +0000824 // Write the symbol table load command, if used.
825 if (NumSymbols) {
826 unsigned FirstLocalSymbol = 0;
827 unsigned NumLocalSymbols = LocalSymbolData.size();
828 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
829 unsigned NumExternalSymbols = ExternalSymbolData.size();
830 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
831 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
832 unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
833 unsigned NumSymTabSymbols =
834 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
835 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
836 uint64_t IndirectSymbolOffset = 0;
837
838 // If used, the indirect symbols are written after the section data.
839 if (NumIndirectSymbols)
Tim Northover53d32512014-03-29 07:34:53 +0000840 IndirectSymbolOffset = LOHTableEnd;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000841
842 // The symbol table is written after the indirect symbol data.
Tim Northover53d32512014-03-29 07:34:53 +0000843 uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000844
845 // The string table is written after symbol table.
846 uint64_t StringTableOffset =
Charles Davis8bdfafd2013-09-01 04:28:48 +0000847 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ?
848 sizeof(MachO::nlist_64) :
849 sizeof(MachO::nlist));
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000850 writeSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000851 StringTableOffset, StringTable.data().size());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000852
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000853 writeDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
Bill Wendlingeb872e02011-06-22 21:07:27 +0000854 FirstExternalSymbol, NumExternalSymbols,
855 FirstUndefinedSymbol, NumUndefinedSymbols,
856 IndirectSymbolOffset, NumIndirectSymbols);
857 }
858
Daniel Dunbareec0f322013-01-18 01:26:07 +0000859 // Write the linker options load commands.
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000860 for (const auto &Option : Asm.getLinkerOptions())
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000861 writeLinkerOptionsLoadCommand(Option);
Daniel Dunbareec0f322013-01-18 01:26:07 +0000862
Bill Wendlingeb872e02011-06-22 21:07:27 +0000863 // Write the actual section data.
Rafael Espindola63702e22015-06-01 01:30:01 +0000864 for (const MCSection &Sec : Asm) {
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000865 Asm.writeSectionData(&Sec, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000866
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000867 uint64_t Pad = getPaddingSize(&Sec, Layout);
Benjamin Kramer97fbdd52015-04-17 11:12:43 +0000868 WriteZeros(Pad);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000869 }
870
871 // Write the extra padding.
872 WriteZeros(SectionDataPadding);
873
874 // Write the relocation entries.
Rafael Espindola63702e22015-06-01 01:30:01 +0000875 for (const MCSection &Sec : Asm) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000876 // Write the section relocation entries, in reverse order to match 'as'
877 // (approximately, the exact algorithm is more complicated than this).
Rafael Espindola63702e22015-06-01 01:30:01 +0000878 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000879 for (const RelAndSymbol &Rel : make_range(Relocs.rbegin(), Relocs.rend())) {
Jim Grosbach36e60e92015-06-04 22:24:41 +0000880 write32(Rel.MRE.r_word0);
881 write32(Rel.MRE.r_word1);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000882 }
883 }
884
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000885 // Write out the data-in-code region payload, if there is one.
886 for (MCAssembler::const_data_region_iterator
887 it = Asm.data_region_begin(), ie = Asm.data_region_end();
888 it != ie; ++it) {
889 const DataRegionData *Data = &(*it);
Duncan P. N. Exon Smith99d8a8e2015-05-20 00:02:39 +0000890 uint64_t Start = getSymbolAddress(*Data->Start, Layout);
891 uint64_t End = getSymbolAddress(*Data->End, Layout);
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000892 DEBUG(dbgs() << "data in code region-- kind: " << Data->Kind
893 << " start: " << Start << "(" << Data->Start->getName() << ")"
894 << " end: " << End << "(" << Data->End->getName() << ")"
895 << " size: " << End - Start
896 << "\n");
Jim Grosbach36e60e92015-06-04 22:24:41 +0000897 write32(Start);
898 write16(End - Start);
899 write16(Data->Kind);
Jim Grosbach4b63d2a2012-05-18 19:12:01 +0000900 }
901
Tim Northover53d32512014-03-29 07:34:53 +0000902 // Write out the loh commands, if there is one.
903 if (LOHSize) {
904#ifndef NDEBUG
905 unsigned Start = OS.tell();
906#endif
Jim Grosbach249af2a2015-06-01 23:55:06 +0000907 Asm.getLOHContainer().emit(*this, Layout);
Tim Northover53d32512014-03-29 07:34:53 +0000908 // Pad to a multiple of the pointer size.
Jim Grosbach36e60e92015-06-04 22:24:41 +0000909 writeBytes("", OffsetToAlignment(LOHRawSize, is64Bit() ? 8 : 4));
Tim Northover53d32512014-03-29 07:34:53 +0000910 assert(OS.tell() - Start == LOHSize);
911 }
912
Bill Wendlingeb872e02011-06-22 21:07:27 +0000913 // Write the symbol table data, if used.
914 if (NumSymbols) {
915 // Write the indirect symbol entries.
916 for (MCAssembler::const_indirect_symbol_iterator
917 it = Asm.indirect_symbol_begin(),
918 ie = Asm.indirect_symbol_end(); it != ie; ++it) {
Alp Tokerf907b892013-12-05 05:44:44 +0000919 // Indirect symbols in the non-lazy symbol pointer section have some
Bill Wendlingeb872e02011-06-22 21:07:27 +0000920 // special handling.
921 const MCSectionMachO &Section =
Rafael Espindola64acc7f2015-05-26 02:17:21 +0000922 static_cast<const MCSectionMachO &>(*it->Section);
David Majnemer7b583052014-03-07 07:36:05 +0000923 if (Section.getType() == MachO::S_NON_LAZY_SYMBOL_POINTERS) {
Bill Wendlingeb872e02011-06-22 21:07:27 +0000924 // If this symbol is defined and internal, mark it as such.
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000925 if (it->Symbol->isDefined() && !it->Symbol->isExternal()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000926 uint32_t Flags = MachO::INDIRECT_SYMBOL_LOCAL;
Bill Wendlingeb872e02011-06-22 21:07:27 +0000927 if (it->Symbol->isAbsolute())
Charles Davis8bdfafd2013-09-01 04:28:48 +0000928 Flags |= MachO::INDIRECT_SYMBOL_ABS;
Jim Grosbach36e60e92015-06-04 22:24:41 +0000929 write32(Flags);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000930 continue;
931 }
932 }
933
Jim Grosbach36e60e92015-06-04 22:24:41 +0000934 write32(it->Symbol->getIndex());
Bill Wendlingeb872e02011-06-22 21:07:27 +0000935 }
936
937 // FIXME: Check that offsets match computed ones.
938
939 // Write the symbol table entries.
Benjamin Kramer1ec70d82015-06-04 21:17:27 +0000940 for (auto *SymbolData :
941 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
942 for (MachSymbolData &Entry : *SymbolData)
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000943 writeNlist(Entry, Layout);
Bill Wendlingeb872e02011-06-22 21:07:27 +0000944
945 // Write the string table.
Hans Wennborg1b1a3992014-10-06 17:05:19 +0000946 OS << StringTable.data();
Bill Wendlingeb872e02011-06-22 21:07:27 +0000947 }
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +0000948}
949
Daniel Dunbar8888a962010-12-16 16:09:19 +0000950MCObjectWriter *llvm::createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000951 raw_pwrite_stream &OS,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000952 bool IsLittleEndian) {
Daniel Dunbar03fcccb2010-12-16 17:21:02 +0000953 return new MachObjectWriter(MOTW, OS, IsLittleEndian);
Daniel Dunbar79e0e5a2010-03-19 10:43:15 +0000954}