1 //===- SyntheticSections.cpp ---------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "SyntheticSections.h"
10 #include "Config.h"
11 #include "ExportTrie.h"
12 #include "InputFiles.h"
13 #include "MachOStructs.h"
14 #include "MergedOutputSection.h"
15 #include "OutputSegment.h"
16 #include "SymbolTable.h"
17 #include "Symbols.h"
18 #include "Writer.h"
19 
20 #include "lld/Common/ErrorHandler.h"
21 #include "lld/Common/Memory.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Config/config.h"
24 #include "llvm/Support/EndianStream.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/LEB128.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/SHA256.h"
29 
30 #if defined(__APPLE__)
31 #include <sys/mman.h>
32 #endif
33 
34 #ifdef HAVE_LIBXAR
35 #include <fcntl.h>
36 #include <xar/xar.h>
37 #endif
38 
39 using namespace llvm;
40 using namespace llvm::MachO;
41 using namespace llvm::support;
42 using namespace llvm::support::endian;
43 using namespace lld;
44 using namespace lld::macho;
45 
46 InStruct macho::in;
47 std::vector<SyntheticSection *> macho::syntheticSections;
48 
49 SyntheticSection::SyntheticSection(const char *segname, const char *name)
50     : OutputSection(SyntheticKind, name), segname(segname) {
51   isec = make<InputSection>();
52   isec->segname = segname;
53   isec->name = name;
54   isec->parent = this;
55   isec->outSecOff = 0;
56   syntheticSections.push_back(this);
57 }
58 
59 // dyld3's MachOLoaded::getSlide() assumes that the __TEXT segment starts
60 // from the beginning of the file (i.e. the header).
61 MachHeaderSection::MachHeaderSection()
62     : SyntheticSection(segment_names::text, section_names::header) {
63   // XXX: This is a hack. (See D97007)
64   // Setting the index to 1 to pretend that this section is the text
65   // section.
66   index = 1;
67   isec->isFinal = true;
68 }
69 
70 void MachHeaderSection::addLoadCommand(LoadCommand *lc) {
71   loadCommands.push_back(lc);
72   sizeOfCmds += lc->getSize();
73 }
74 
75 uint64_t MachHeaderSection::getSize() const {
76   uint64_t size = target->headerSize + sizeOfCmds + config->headerPad;
77   // If we are emitting an encryptable binary, our load commands must have a
78   // separate (non-encrypted) page to themselves.
79   if (config->emitEncryptionInfo)
80     size = alignTo(size, target->getPageSize());
81   return size;
82 }
83 
84 static uint32_t cpuSubtype() {
85   uint32_t subtype = target->cpuSubtype;
86 
87   if (config->outputType == MH_EXECUTE && !config->staticLink &&
88       target->cpuSubtype == CPU_SUBTYPE_X86_64_ALL &&
89       config->platform() == PlatformKind::macOS &&
90       config->platformInfo.minimum >= VersionTuple(10, 5))
91     subtype |= CPU_SUBTYPE_LIB64;
92 
93   return subtype;
94 }
95 
96 void MachHeaderSection::writeTo(uint8_t *buf) const {
97   auto *hdr = reinterpret_cast<mach_header *>(buf);
98   hdr->magic = target->magic;
99   hdr->cputype = target->cpuType;
100   hdr->cpusubtype = cpuSubtype();
101   hdr->filetype = config->outputType;
102   hdr->ncmds = loadCommands.size();
103   hdr->sizeofcmds = sizeOfCmds;
104   hdr->flags = MH_DYLDLINK;
105 
106   if (config->namespaceKind == NamespaceKind::twolevel)
107     hdr->flags |= MH_NOUNDEFS | MH_TWOLEVEL;
108 
109   if (config->outputType == MH_DYLIB && !config->hasReexports)
110     hdr->flags |= MH_NO_REEXPORTED_DYLIBS;
111 
112   if (config->markDeadStrippableDylib)
113     hdr->flags |= MH_DEAD_STRIPPABLE_DYLIB;
114 
115   if (config->outputType == MH_EXECUTE && config->isPic)
116     hdr->flags |= MH_PIE;
117 
118   if (in.exports->hasWeakSymbol || in.weakBinding->hasNonWeakDefinition())
119     hdr->flags |= MH_WEAK_DEFINES;
120 
121   if (in.exports->hasWeakSymbol || in.weakBinding->hasEntry())
122     hdr->flags |= MH_BINDS_TO_WEAK;
123 
124   for (const OutputSegment *seg : outputSegments) {
125     for (const OutputSection *osec : seg->getSections()) {
126       if (isThreadLocalVariables(osec->flags)) {
127         hdr->flags |= MH_HAS_TLV_DESCRIPTORS;
128         break;
129       }
130     }
131   }
132 
133   uint8_t *p = reinterpret_cast<uint8_t *>(hdr) + target->headerSize;
134   for (const LoadCommand *lc : loadCommands) {
135     lc->writeTo(p);
136     p += lc->getSize();
137   }
138 }
139 
140 PageZeroSection::PageZeroSection()
141     : SyntheticSection(segment_names::pageZero, section_names::pageZero) {}
142 
143 RebaseSection::RebaseSection()
144     : LinkEditSection(segment_names::linkEdit, section_names::rebase) {}
145 
146 namespace {
147 struct Rebase {
148   OutputSegment *segment = nullptr;
149   uint64_t offset = 0;
150   uint64_t consecutiveCount = 0;
151 };
152 } // namespace
153 
154 // Rebase opcodes allow us to describe a contiguous sequence of rebase location
155 // using a single DO_REBASE opcode. To take advantage of it, we delay emitting
156 // `DO_REBASE` until we have reached the end of a contiguous sequence.
157 static void encodeDoRebase(Rebase &rebase, raw_svector_ostream &os) {
158   assert(rebase.consecutiveCount != 0);
159   if (rebase.consecutiveCount <= REBASE_IMMEDIATE_MASK) {
160     os << static_cast<uint8_t>(REBASE_OPCODE_DO_REBASE_IMM_TIMES |
161                                rebase.consecutiveCount);
162   } else {
163     os << static_cast<uint8_t>(REBASE_OPCODE_DO_REBASE_ULEB_TIMES);
164     encodeULEB128(rebase.consecutiveCount, os);
165   }
166   rebase.consecutiveCount = 0;
167 }
168 
169 static void encodeRebase(const OutputSection *osec, uint64_t outSecOff,
170                          Rebase &lastRebase, raw_svector_ostream &os) {
171   OutputSegment *seg = osec->parent;
172   uint64_t offset = osec->getSegmentOffset() + outSecOff;
173   if (lastRebase.segment != seg || lastRebase.offset != offset) {
174     if (lastRebase.consecutiveCount != 0)
175       encodeDoRebase(lastRebase, os);
176 
177     if (lastRebase.segment != seg) {
178       os << static_cast<uint8_t>(REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB |
179                                  seg->index);
180       encodeULEB128(offset, os);
181       lastRebase.segment = seg;
182       lastRebase.offset = offset;
183     } else {
184       assert(lastRebase.offset != offset);
185       os << static_cast<uint8_t>(REBASE_OPCODE_ADD_ADDR_ULEB);
186       encodeULEB128(offset - lastRebase.offset, os);
187       lastRebase.offset = offset;
188     }
189   }
190   ++lastRebase.consecutiveCount;
191   // DO_REBASE causes dyld to both perform the binding and increment the offset
192   lastRebase.offset += target->wordSize;
193 }
194 
195 void RebaseSection::finalizeContents() {
196   if (locations.empty())
197     return;
198 
199   raw_svector_ostream os{contents};
200   Rebase lastRebase;
201 
202   os << static_cast<uint8_t>(REBASE_OPCODE_SET_TYPE_IMM | REBASE_TYPE_POINTER);
203 
204   llvm::sort(locations, [](const Location &a, const Location &b) {
205     return a.isec->getVA() < b.isec->getVA();
206   });
207   for (const Location &loc : locations)
208     encodeRebase(loc.isec->parent, loc.isec->outSecOff + loc.offset, lastRebase,
209                  os);
210   if (lastRebase.consecutiveCount != 0)
211     encodeDoRebase(lastRebase, os);
212 
213   os << static_cast<uint8_t>(REBASE_OPCODE_DONE);
214 }
215 
216 void RebaseSection::writeTo(uint8_t *buf) const {
217   memcpy(buf, contents.data(), contents.size());
218 }
219 
220 NonLazyPointerSectionBase::NonLazyPointerSectionBase(const char *segname,
221                                                      const char *name)
222     : SyntheticSection(segname, name) {
223   align = target->wordSize;
224   flags = S_NON_LAZY_SYMBOL_POINTERS;
225 }
226 
227 void macho::addNonLazyBindingEntries(const Symbol *sym,
228                                      const InputSection *isec, uint64_t offset,
229                                      int64_t addend) {
230   if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) {
231     in.binding->addEntry(dysym, isec, offset, addend);
232     if (dysym->isWeakDef())
233       in.weakBinding->addEntry(sym, isec, offset, addend);
234   } else if (const auto *defined = dyn_cast<Defined>(sym)) {
235     in.rebase->addEntry(isec, offset);
236     if (defined->isExternalWeakDef())
237       in.weakBinding->addEntry(sym, isec, offset, addend);
238   } else {
239     // Undefined symbols are filtered out in scanRelocations(); we should never
240     // get here
241     llvm_unreachable("cannot bind to an undefined symbol");
242   }
243 }
244 
245 void NonLazyPointerSectionBase::addEntry(Symbol *sym) {
246   if (entries.insert(sym)) {
247     assert(!sym->isInGot());
248     sym->gotIndex = entries.size() - 1;
249 
250     addNonLazyBindingEntries(sym, isec, sym->gotIndex * target->wordSize);
251   }
252 }
253 
254 void NonLazyPointerSectionBase::writeTo(uint8_t *buf) const {
255   for (size_t i = 0, n = entries.size(); i < n; ++i)
256     if (auto *defined = dyn_cast<Defined>(entries[i]))
257       write64le(&buf[i * target->wordSize], defined->getVA());
258 }
259 
260 BindingSection::BindingSection()
261     : LinkEditSection(segment_names::linkEdit, section_names::binding) {}
262 
263 namespace {
264 struct Binding {
265   OutputSegment *segment = nullptr;
266   uint64_t offset = 0;
267   int64_t addend = 0;
268   int16_t ordinal = 0;
269 };
270 } // namespace
271 
272 // Encode a sequence of opcodes that tell dyld to write the address of symbol +
273 // addend at osec->addr + outSecOff.
274 //
275 // The bind opcode "interpreter" remembers the values of each binding field, so
276 // we only need to encode the differences between bindings. Hence the use of
277 // lastBinding.
278 static void encodeBinding(const Symbol *sym, const OutputSection *osec,
279                           uint64_t outSecOff, int64_t addend,
280                           bool isWeakBinding, Binding &lastBinding,
281                           raw_svector_ostream &os) {
282   OutputSegment *seg = osec->parent;
283   uint64_t offset = osec->getSegmentOffset() + outSecOff;
284   if (lastBinding.segment != seg) {
285     os << static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB |
286                                seg->index);
287     encodeULEB128(offset, os);
288     lastBinding.segment = seg;
289     lastBinding.offset = offset;
290   } else if (lastBinding.offset != offset) {
291     os << static_cast<uint8_t>(BIND_OPCODE_ADD_ADDR_ULEB);
292     encodeULEB128(offset - lastBinding.offset, os);
293     lastBinding.offset = offset;
294   }
295 
296   if (lastBinding.addend != addend) {
297     os << static_cast<uint8_t>(BIND_OPCODE_SET_ADDEND_SLEB);
298     encodeSLEB128(addend, os);
299     lastBinding.addend = addend;
300   }
301 
302   uint8_t flags = BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM;
303   if (!isWeakBinding && sym->isWeakRef())
304     flags |= BIND_SYMBOL_FLAGS_WEAK_IMPORT;
305 
306   os << flags << sym->getName() << '\0'
307      << static_cast<uint8_t>(BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER)
308      << static_cast<uint8_t>(BIND_OPCODE_DO_BIND);
309   // DO_BIND causes dyld to both perform the binding and increment the offset
310   lastBinding.offset += target->wordSize;
311 }
312 
313 // Non-weak bindings need to have their dylib ordinal encoded as well.
314 static int16_t ordinalForDylibSymbol(const DylibSymbol &dysym) {
315   return config->namespaceKind == NamespaceKind::flat || dysym.isDynamicLookup()
316              ? static_cast<int16_t>(BIND_SPECIAL_DYLIB_FLAT_LOOKUP)
317              : dysym.getFile()->ordinal;
318 }
319 
320 static void encodeDylibOrdinal(int16_t ordinal, raw_svector_ostream &os) {
321   if (ordinal <= 0) {
322     os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM |
323                                (ordinal & BIND_IMMEDIATE_MASK));
324   } else if (ordinal <= BIND_IMMEDIATE_MASK) {
325     os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | ordinal);
326   } else {
327     os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB);
328     encodeULEB128(ordinal, os);
329   }
330 }
331 
332 static void encodeWeakOverride(const Defined *defined,
333                                raw_svector_ostream &os) {
334   os << static_cast<uint8_t>(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM |
335                              BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
336      << defined->getName() << '\0';
337 }
338 
339 // Emit bind opcodes, which are a stream of byte-sized opcodes that dyld
340 // interprets to update a record with the following fields:
341 //  * segment index (of the segment to write the symbol addresses to, typically
342 //    the __DATA_CONST segment which contains the GOT)
343 //  * offset within the segment, indicating the next location to write a binding
344 //  * symbol type
345 //  * symbol library ordinal (the index of its library's LC_LOAD_DYLIB command)
346 //  * symbol name
347 //  * addend
348 // When dyld sees BIND_OPCODE_DO_BIND, it uses the current record state to bind
349 // a symbol in the GOT, and increments the segment offset to point to the next
350 // entry. It does *not* clear the record state after doing the bind, so
351 // subsequent opcodes only need to encode the differences between bindings.
352 void BindingSection::finalizeContents() {
353   raw_svector_ostream os{contents};
354   Binding lastBinding;
355 
356   // Since bindings are delta-encoded, sorting them allows for a more compact
357   // result. Note that sorting by address alone ensures that bindings for the
358   // same segment / section are located together.
359   llvm::sort(bindings, [](const BindingEntry &a, const BindingEntry &b) {
360     return a.target.getVA() < b.target.getVA();
361   });
362   for (const BindingEntry &b : bindings) {
363     int16_t ordinal = ordinalForDylibSymbol(*b.dysym);
364     if (ordinal != lastBinding.ordinal) {
365       encodeDylibOrdinal(ordinal, os);
366       lastBinding.ordinal = ordinal;
367     }
368     encodeBinding(b.dysym, b.target.isec->parent,
369                   b.target.isec->outSecOff + b.target.offset, b.addend,
370                   /*isWeakBinding=*/false, lastBinding, os);
371   }
372   if (!bindings.empty())
373     os << static_cast<uint8_t>(BIND_OPCODE_DONE);
374 }
375 
376 void BindingSection::writeTo(uint8_t *buf) const {
377   memcpy(buf, contents.data(), contents.size());
378 }
379 
380 WeakBindingSection::WeakBindingSection()
381     : LinkEditSection(segment_names::linkEdit, section_names::weakBinding) {}
382 
383 void WeakBindingSection::finalizeContents() {
384   raw_svector_ostream os{contents};
385   Binding lastBinding;
386 
387   for (const Defined *defined : definitions)
388     encodeWeakOverride(defined, os);
389 
390   // Since bindings are delta-encoded, sorting them allows for a more compact
391   // result.
392   llvm::sort(bindings,
393              [](const WeakBindingEntry &a, const WeakBindingEntry &b) {
394                return a.target.getVA() < b.target.getVA();
395              });
396   for (const WeakBindingEntry &b : bindings)
397     encodeBinding(b.symbol, b.target.isec->parent,
398                   b.target.isec->outSecOff + b.target.offset, b.addend,
399                   /*isWeakBinding=*/true, lastBinding, os);
400   if (!bindings.empty() || !definitions.empty())
401     os << static_cast<uint8_t>(BIND_OPCODE_DONE);
402 }
403 
404 void WeakBindingSection::writeTo(uint8_t *buf) const {
405   memcpy(buf, contents.data(), contents.size());
406 }
407 
408 StubsSection::StubsSection()
409     : SyntheticSection(segment_names::text, section_names::stubs) {
410   flags = S_SYMBOL_STUBS | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
411   // The stubs section comprises machine instructions, which are aligned to
412   // 4 bytes on the archs we care about.
413   align = 4;
414   reserved2 = target->stubSize;
415 }
416 
417 uint64_t StubsSection::getSize() const {
418   return entries.size() * target->stubSize;
419 }
420 
421 void StubsSection::writeTo(uint8_t *buf) const {
422   size_t off = 0;
423   for (const Symbol *sym : entries) {
424     target->writeStub(buf + off, *sym);
425     off += target->stubSize;
426   }
427 }
428 
429 void StubsSection::finalize() { isFinal = true; }
430 
431 bool StubsSection::addEntry(Symbol *sym) {
432   bool inserted = entries.insert(sym);
433   if (inserted)
434     sym->stubsIndex = entries.size() - 1;
435   return inserted;
436 }
437 
438 StubHelperSection::StubHelperSection()
439     : SyntheticSection(segment_names::text, section_names::stubHelper) {
440   flags = S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
441   align = 4; // This section comprises machine instructions
442 }
443 
444 uint64_t StubHelperSection::getSize() const {
445   return target->stubHelperHeaderSize +
446          in.lazyBinding->getEntries().size() * target->stubHelperEntrySize;
447 }
448 
449 bool StubHelperSection::isNeeded() const { return in.lazyBinding->isNeeded(); }
450 
451 void StubHelperSection::writeTo(uint8_t *buf) const {
452   target->writeStubHelperHeader(buf);
453   size_t off = target->stubHelperHeaderSize;
454   for (const DylibSymbol *sym : in.lazyBinding->getEntries()) {
455     target->writeStubHelperEntry(buf + off, *sym, addr + off);
456     off += target->stubHelperEntrySize;
457   }
458 }
459 
460 void StubHelperSection::setup() {
461   stubBinder = dyn_cast_or_null<DylibSymbol>(symtab->find("dyld_stub_binder"));
462   if (stubBinder == nullptr) {
463     error("symbol dyld_stub_binder not found (normally in libSystem.dylib). "
464           "Needed to perform lazy binding.");
465     return;
466   }
467   stubBinder->refState = RefState::Strong;
468   in.got->addEntry(stubBinder);
469 
470   inputSections.push_back(in.imageLoaderCache);
471   dyldPrivate =
472       make<Defined>("__dyld_private", nullptr, in.imageLoaderCache, 0, 0,
473                     /*isWeakDef=*/false,
474                     /*isExternal=*/false, /*isPrivateExtern=*/false,
475                     /*isThumb=*/false);
476 }
477 
478 ImageLoaderCacheSection::ImageLoaderCacheSection() {
479   segname = segment_names::data;
480   name = section_names::data;
481   uint8_t *arr = bAlloc.Allocate<uint8_t>(target->wordSize);
482   memset(arr, 0, target->wordSize);
483   data = {arr, target->wordSize};
484   align = target->wordSize;
485 }
486 
487 LazyPointerSection::LazyPointerSection()
488     : SyntheticSection(segment_names::data, section_names::lazySymbolPtr) {
489   align = target->wordSize;
490   flags = S_LAZY_SYMBOL_POINTERS;
491 }
492 
493 uint64_t LazyPointerSection::getSize() const {
494   return in.stubs->getEntries().size() * target->wordSize;
495 }
496 
497 bool LazyPointerSection::isNeeded() const {
498   return !in.stubs->getEntries().empty();
499 }
500 
501 void LazyPointerSection::writeTo(uint8_t *buf) const {
502   size_t off = 0;
503   for (const Symbol *sym : in.stubs->getEntries()) {
504     if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) {
505       if (dysym->hasStubsHelper()) {
506         uint64_t stubHelperOffset =
507             target->stubHelperHeaderSize +
508             dysym->stubsHelperIndex * target->stubHelperEntrySize;
509         write64le(buf + off, in.stubHelper->addr + stubHelperOffset);
510       }
511     } else {
512       write64le(buf + off, sym->getVA());
513     }
514     off += target->wordSize;
515   }
516 }
517 
518 LazyBindingSection::LazyBindingSection()
519     : LinkEditSection(segment_names::linkEdit, section_names::lazyBinding) {}
520 
521 void LazyBindingSection::finalizeContents() {
522   // TODO: Just precompute output size here instead of writing to a temporary
523   // buffer
524   for (DylibSymbol *sym : entries)
525     sym->lazyBindOffset = encode(*sym);
526 }
527 
528 void LazyBindingSection::writeTo(uint8_t *buf) const {
529   memcpy(buf, contents.data(), contents.size());
530 }
531 
532 void LazyBindingSection::addEntry(DylibSymbol *dysym) {
533   if (entries.insert(dysym)) {
534     dysym->stubsHelperIndex = entries.size() - 1;
535     in.rebase->addEntry(in.lazyPointers->isec,
536                         dysym->stubsIndex * target->wordSize);
537   }
538 }
539 
540 // Unlike the non-lazy binding section, the bind opcodes in this section aren't
541 // interpreted all at once. Rather, dyld will start interpreting opcodes at a
542 // given offset, typically only binding a single symbol before it finds a
543 // BIND_OPCODE_DONE terminator. As such, unlike in the non-lazy-binding case,
544 // we cannot encode just the differences between symbols; we have to emit the
545 // complete bind information for each symbol.
546 uint32_t LazyBindingSection::encode(const DylibSymbol &sym) {
547   uint32_t opstreamOffset = contents.size();
548   OutputSegment *dataSeg = in.lazyPointers->parent;
549   os << static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB |
550                              dataSeg->index);
551   uint64_t offset = in.lazyPointers->addr - dataSeg->firstSection()->addr +
552                     sym.stubsIndex * target->wordSize;
553   encodeULEB128(offset, os);
554   encodeDylibOrdinal(ordinalForDylibSymbol(sym), os);
555 
556   uint8_t flags = BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM;
557   if (sym.isWeakRef())
558     flags |= BIND_SYMBOL_FLAGS_WEAK_IMPORT;
559 
560   os << flags << sym.getName() << '\0'
561      << static_cast<uint8_t>(BIND_OPCODE_DO_BIND)
562      << static_cast<uint8_t>(BIND_OPCODE_DONE);
563   return opstreamOffset;
564 }
565 
566 ExportSection::ExportSection()
567     : LinkEditSection(segment_names::linkEdit, section_names::export_) {}
568 
569 static void validateExportSymbol(const Defined *defined) {
570   StringRef symbolName = defined->getName();
571   if (defined->privateExtern && config->exportedSymbols.match(symbolName))
572     error("cannot export hidden symbol " + symbolName + "\n>>> defined in " +
573           toString(defined->getFile()));
574 }
575 
576 static bool shouldExportSymbol(const Defined *defined) {
577   if (defined->privateExtern) {
578     assert(defined->isExternal() && "invalid input file");
579     return false;
580   }
581   // TODO: Is this a performance bottleneck? If a build has mostly
582   // global symbols in the input but uses -exported_symbols to filter
583   // out most of them, then it would be better to set the value of
584   // privateExtern at parse time instead of calling
585   // exportedSymbols.match() more than once.
586   //
587   // Measurements show that symbol ordering (which again looks up
588   // every symbol in a hashmap) is the biggest bottleneck when linking
589   // chromium_framework, so this will likely be worth optimizing.
590   return config->exportedSymbols.empty()
591              ? !config->unexportedSymbols.match(defined->getName())
592              : config->exportedSymbols.match(defined->getName());
593 }
594 
595 void ExportSection::finalizeContents() {
596   trieBuilder.setImageBase(in.header->addr);
597   for (const Symbol *sym : symtab->getSymbols()) {
598     if (const auto *defined = dyn_cast<Defined>(sym)) {
599       validateExportSymbol(defined);
600       if (!shouldExportSymbol(defined))
601         continue;
602       trieBuilder.addSymbol(*defined);
603       hasWeakSymbol = hasWeakSymbol || sym->isWeakDef();
604     }
605   }
606   size = trieBuilder.build();
607 }
608 
609 void ExportSection::writeTo(uint8_t *buf) const { trieBuilder.writeTo(buf); }
610 
611 FunctionStartsSection::FunctionStartsSection()
612     : LinkEditSection(segment_names::linkEdit, section_names::functionStarts) {}
613 
614 void FunctionStartsSection::finalizeContents() {
615   raw_svector_ostream os{contents};
616   uint64_t addr = in.header->addr;
617   for (const Symbol *sym : symtab->getSymbols()) {
618     if (const auto *defined = dyn_cast<Defined>(sym)) {
619       if (!defined->isec || !isCodeSection(defined->isec))
620         continue;
621       // TODO: Add support for thumbs, in that case
622       // the lowest bit of nextAddr needs to be set to 1.
623       uint64_t nextAddr = defined->getVA();
624       uint64_t delta = nextAddr - addr;
625       if (delta == 0)
626         continue;
627       encodeULEB128(delta, os);
628       addr = nextAddr;
629     }
630   }
631   os << '\0';
632 }
633 
634 void FunctionStartsSection::writeTo(uint8_t *buf) const {
635   memcpy(buf, contents.data(), contents.size());
636 }
637 
638 SymtabSection::SymtabSection(StringTableSection &stringTableSection)
639     : LinkEditSection(segment_names::linkEdit, section_names::symbolTable),
640       stringTableSection(stringTableSection) {}
641 
642 void SymtabSection::emitBeginSourceStab(DWARFUnit *compileUnit) {
643   StabsEntry stab(N_SO);
644   SmallString<261> dir(compileUnit->getCompilationDir());
645   StringRef sep = sys::path::get_separator();
646   // We don't use `path::append` here because we want an empty `dir` to result
647   // in an absolute path. `append` would give us a relative path for that case.
648   if (!dir.endswith(sep))
649     dir += sep;
650   stab.strx = stringTableSection.addString(
651       saver.save(dir + compileUnit->getUnitDIE().getShortName()));
652   stabs.emplace_back(std::move(stab));
653 }
654 
655 void SymtabSection::emitEndSourceStab() {
656   StabsEntry stab(N_SO);
657   stab.sect = 1;
658   stabs.emplace_back(std::move(stab));
659 }
660 
661 void SymtabSection::emitObjectFileStab(ObjFile *file) {
662   StabsEntry stab(N_OSO);
663   stab.sect = target->cpuSubtype;
664   SmallString<261> path(!file->archiveName.empty() ? file->archiveName
665                                                    : file->getName());
666   std::error_code ec = sys::fs::make_absolute(path);
667   if (ec)
668     fatal("failed to get absolute path for " + path);
669 
670   if (!file->archiveName.empty())
671     path.append({"(", file->getName(), ")"});
672 
673   stab.strx = stringTableSection.addString(saver.save(path.str()));
674   stab.desc = 1;
675   stab.value = file->modTime;
676   stabs.emplace_back(std::move(stab));
677 }
678 
679 void SymtabSection::emitEndFunStab(Defined *defined) {
680   StabsEntry stab(N_FUN);
681   stab.value = defined->size;
682   stabs.emplace_back(std::move(stab));
683 }
684 
685 void SymtabSection::emitStabs() {
686   for (const std::string &s : config->astPaths) {
687     StabsEntry astStab(N_AST);
688     astStab.strx = stringTableSection.addString(s);
689     stabs.emplace_back(std::move(astStab));
690   }
691 
692   std::vector<Defined *> symbolsNeedingStabs;
693   for (const SymtabEntry &entry :
694        concat<SymtabEntry>(localSymbols, externalSymbols)) {
695     Symbol *sym = entry.sym;
696     if (auto *defined = dyn_cast<Defined>(sym)) {
697       if (defined->isAbsolute())
698         continue;
699       InputSection *isec = defined->isec;
700       ObjFile *file = dyn_cast_or_null<ObjFile>(isec->file);
701       if (!file || !file->compileUnit)
702         continue;
703       symbolsNeedingStabs.push_back(defined);
704     }
705   }
706 
707   llvm::stable_sort(symbolsNeedingStabs, [&](Defined *a, Defined *b) {
708     return a->isec->file->id < b->isec->file->id;
709   });
710 
711   // Emit STABS symbols so that dsymutil and/or the debugger can map address
712   // regions in the final binary to the source and object files from which they
713   // originated.
714   InputFile *lastFile = nullptr;
715   for (Defined *defined : symbolsNeedingStabs) {
716     InputSection *isec = defined->isec;
717     ObjFile *file = cast<ObjFile>(isec->file);
718 
719     if (lastFile == nullptr || lastFile != file) {
720       if (lastFile != nullptr)
721         emitEndSourceStab();
722       lastFile = file;
723 
724       emitBeginSourceStab(file->compileUnit);
725       emitObjectFileStab(file);
726     }
727 
728     StabsEntry symStab;
729     symStab.sect = defined->isec->parent->index;
730     symStab.strx = stringTableSection.addString(defined->getName());
731     symStab.value = defined->getVA();
732 
733     if (isCodeSection(isec)) {
734       symStab.type = N_FUN;
735       stabs.emplace_back(std::move(symStab));
736       emitEndFunStab(defined);
737     } else {
738       symStab.type = defined->isExternal() ? N_GSYM : N_STSYM;
739       stabs.emplace_back(std::move(symStab));
740     }
741   }
742 
743   if (!stabs.empty())
744     emitEndSourceStab();
745 }
746 
747 void SymtabSection::finalizeContents() {
748   auto addSymbol = [&](std::vector<SymtabEntry> &symbols, Symbol *sym) {
749     uint32_t strx = stringTableSection.addString(sym->getName());
750     symbols.push_back({sym, strx});
751   };
752 
753   // Local symbols aren't in the SymbolTable, so we walk the list of object
754   // files to gather them.
755   for (const InputFile *file : inputFiles) {
756     if (auto *objFile = dyn_cast<ObjFile>(file)) {
757       for (Symbol *sym : objFile->symbols) {
758         if (sym == nullptr)
759           continue;
760         // TODO: when we implement -dead_strip, we should filter out symbols
761         // that belong to dead sections.
762         if (auto *defined = dyn_cast<Defined>(sym)) {
763           if (!defined->isExternal()) {
764             StringRef name = defined->getName();
765             if (!name.startswith("l") && !name.startswith("L"))
766               addSymbol(localSymbols, sym);
767           }
768         }
769       }
770     }
771   }
772 
773   // __dyld_private is a local symbol too. It's linker-created and doesn't
774   // exist in any object file.
775   if (Defined *dyldPrivate = in.stubHelper->dyldPrivate)
776     addSymbol(localSymbols, dyldPrivate);
777 
778   for (Symbol *sym : symtab->getSymbols()) {
779     if (auto *defined = dyn_cast<Defined>(sym)) {
780       if (!defined->includeInSymtab)
781         continue;
782       assert(defined->isExternal());
783       addSymbol(externalSymbols, defined);
784     } else if (auto *dysym = dyn_cast<DylibSymbol>(sym)) {
785       if (dysym->isReferenced())
786         addSymbol(undefinedSymbols, sym);
787     }
788   }
789 
790   emitStabs();
791   uint32_t symtabIndex = stabs.size();
792   for (const SymtabEntry &entry :
793        concat<SymtabEntry>(localSymbols, externalSymbols, undefinedSymbols)) {
794     entry.sym->symtabIndex = symtabIndex++;
795   }
796 }
797 
798 uint32_t SymtabSection::getNumSymbols() const {
799   return stabs.size() + localSymbols.size() + externalSymbols.size() +
800          undefinedSymbols.size();
801 }
802 
803 // This serves to hide (type-erase) the template parameter from SymtabSection.
804 template <class LP> class SymtabSectionImpl : public SymtabSection {
805 public:
806   SymtabSectionImpl(StringTableSection &stringTableSection)
807       : SymtabSection(stringTableSection) {}
808   uint64_t getRawSize() const override;
809   void writeTo(uint8_t *buf) const override;
810 };
811 
812 template <class LP> uint64_t SymtabSectionImpl<LP>::getRawSize() const {
813   return getNumSymbols() * sizeof(typename LP::nlist);
814 }
815 
816 template <class LP> void SymtabSectionImpl<LP>::writeTo(uint8_t *buf) const {
817   auto *nList = reinterpret_cast<typename LP::nlist *>(buf);
818   // Emit the stabs entries before the "real" symbols. We cannot emit them
819   // after as that would render Symbol::symtabIndex inaccurate.
820   for (const StabsEntry &entry : stabs) {
821     nList->n_strx = entry.strx;
822     nList->n_type = entry.type;
823     nList->n_sect = entry.sect;
824     nList->n_desc = entry.desc;
825     nList->n_value = entry.value;
826     ++nList;
827   }
828 
829   for (const SymtabEntry &entry : concat<const SymtabEntry>(
830            localSymbols, externalSymbols, undefinedSymbols)) {
831     nList->n_strx = entry.strx;
832     // TODO populate n_desc with more flags
833     if (auto *defined = dyn_cast<Defined>(entry.sym)) {
834       uint8_t scope = 0;
835       if (!shouldExportSymbol(defined)) {
836         // Private external -- dylib scoped symbol.
837         // Promote to non-external at link time.
838         scope = N_PEXT;
839       } else if (defined->isExternal()) {
840         // Normal global symbol.
841         scope = N_EXT;
842       } else {
843         // TU-local symbol from localSymbols.
844         scope = 0;
845       }
846 
847       if (defined->isAbsolute()) {
848         nList->n_type = scope | N_ABS;
849         nList->n_sect = NO_SECT;
850         nList->n_value = defined->value;
851       } else {
852         nList->n_type = scope | N_SECT;
853         nList->n_sect = defined->isec->parent->index;
854         // For the N_SECT symbol type, n_value is the address of the symbol
855         nList->n_value = defined->getVA();
856       }
857       nList->n_desc |= defined->thumb ? N_ARM_THUMB_DEF : 0;
858       nList->n_desc |= defined->isExternalWeakDef() ? N_WEAK_DEF : 0;
859     } else if (auto *dysym = dyn_cast<DylibSymbol>(entry.sym)) {
860       uint16_t n_desc = nList->n_desc;
861       int16_t ordinal = ordinalForDylibSymbol(*dysym);
862       if (ordinal == BIND_SPECIAL_DYLIB_FLAT_LOOKUP)
863         SET_LIBRARY_ORDINAL(n_desc, DYNAMIC_LOOKUP_ORDINAL);
864       else if (ordinal == BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE)
865         SET_LIBRARY_ORDINAL(n_desc, EXECUTABLE_ORDINAL);
866       else {
867         assert(ordinal > 0);
868         SET_LIBRARY_ORDINAL(n_desc, static_cast<uint8_t>(ordinal));
869       }
870 
871       nList->n_type = N_EXT;
872       n_desc |= dysym->isWeakDef() ? N_WEAK_DEF : 0;
873       n_desc |= dysym->isWeakRef() ? N_WEAK_REF : 0;
874       nList->n_desc = n_desc;
875     }
876     ++nList;
877   }
878 }
879 
880 template <class LP>
881 SymtabSection *
882 macho::makeSymtabSection(StringTableSection &stringTableSection) {
883   return make<SymtabSectionImpl<LP>>(stringTableSection);
884 }
885 
886 IndirectSymtabSection::IndirectSymtabSection()
887     : LinkEditSection(segment_names::linkEdit,
888                       section_names::indirectSymbolTable) {}
889 
890 uint32_t IndirectSymtabSection::getNumSymbols() const {
891   return in.got->getEntries().size() + in.tlvPointers->getEntries().size() +
892          in.stubs->getEntries().size();
893 }
894 
895 bool IndirectSymtabSection::isNeeded() const {
896   return in.got->isNeeded() || in.tlvPointers->isNeeded() ||
897          in.stubs->isNeeded();
898 }
899 
900 void IndirectSymtabSection::finalizeContents() {
901   uint32_t off = 0;
902   in.got->reserved1 = off;
903   off += in.got->getEntries().size();
904   in.tlvPointers->reserved1 = off;
905   off += in.tlvPointers->getEntries().size();
906   // There is a 1:1 correspondence between stubs and LazyPointerSection
907   // entries, so they can share the same sub-array in the table.
908   in.stubs->reserved1 = in.lazyPointers->reserved1 = off;
909 }
910 
911 static uint32_t indirectValue(const Symbol *sym) {
912   return sym->symtabIndex != UINT32_MAX ? sym->symtabIndex
913                                         : INDIRECT_SYMBOL_LOCAL;
914 }
915 
916 void IndirectSymtabSection::writeTo(uint8_t *buf) const {
917   uint32_t off = 0;
918   for (const Symbol *sym : in.got->getEntries()) {
919     write32le(buf + off * sizeof(uint32_t), indirectValue(sym));
920     ++off;
921   }
922   for (const Symbol *sym : in.tlvPointers->getEntries()) {
923     write32le(buf + off * sizeof(uint32_t), indirectValue(sym));
924     ++off;
925   }
926   for (const Symbol *sym : in.stubs->getEntries()) {
927     write32le(buf + off * sizeof(uint32_t), indirectValue(sym));
928     ++off;
929   }
930 }
931 
932 StringTableSection::StringTableSection()
933     : LinkEditSection(segment_names::linkEdit, section_names::stringTable) {}
934 
935 uint32_t StringTableSection::addString(StringRef str) {
936   uint32_t strx = size;
937   strings.push_back(str); // TODO: consider deduplicating strings
938   size += str.size() + 1; // account for null terminator
939   return strx;
940 }
941 
942 void StringTableSection::writeTo(uint8_t *buf) const {
943   uint32_t off = 0;
944   for (StringRef str : strings) {
945     memcpy(buf + off, str.data(), str.size());
946     off += str.size() + 1; // account for null terminator
947   }
948 }
949 
950 CodeSignatureSection::CodeSignatureSection()
951     : LinkEditSection(segment_names::linkEdit, section_names::codeSignature) {
952   align = 16; // required by libstuff
953   fileName = config->outputFile;
954   size_t slashIndex = fileName.rfind("/");
955   if (slashIndex != std::string::npos)
956     fileName = fileName.drop_front(slashIndex + 1);
957   allHeadersSize = alignTo<16>(fixedHeadersSize + fileName.size() + 1);
958   fileNamePad = allHeadersSize - fixedHeadersSize - fileName.size();
959 }
960 
961 uint32_t CodeSignatureSection::getBlockCount() const {
962   return (fileOff + blockSize - 1) / blockSize;
963 }
964 
965 uint64_t CodeSignatureSection::getRawSize() const {
966   return allHeadersSize + getBlockCount() * hashSize;
967 }
968 
969 void CodeSignatureSection::writeHashes(uint8_t *buf) const {
970   uint8_t *code = buf;
971   uint8_t *codeEnd = buf + fileOff;
972   uint8_t *hashes = codeEnd + allHeadersSize;
973   while (code < codeEnd) {
974     StringRef block(reinterpret_cast<char *>(code),
975                     std::min(codeEnd - code, static_cast<ssize_t>(blockSize)));
976     SHA256 hasher;
977     hasher.update(block);
978     StringRef hash = hasher.final();
979     assert(hash.size() == hashSize);
980     memcpy(hashes, hash.data(), hashSize);
981     code += blockSize;
982     hashes += hashSize;
983   }
984 #if defined(__APPLE__)
985   // This is macOS-specific work-around and makes no sense for any
986   // other host OS. See https://openradar.appspot.com/FB8914231
987   //
988   // The macOS kernel maintains a signature-verification cache to
989   // quickly validate applications at time of execve(2).  The trouble
990   // is that for the kernel creates the cache entry at the time of the
991   // mmap(2) call, before we have a chance to write either the code to
992   // sign or the signature header+hashes.  The fix is to invalidate
993   // all cached data associated with the output file, thus discarding
994   // the bogus prematurely-cached signature.
995   msync(buf, fileOff + getSize(), MS_INVALIDATE);
996 #endif
997 }
998 
999 void CodeSignatureSection::writeTo(uint8_t *buf) const {
1000   uint32_t signatureSize = static_cast<uint32_t>(getSize());
1001   auto *superBlob = reinterpret_cast<CS_SuperBlob *>(buf);
1002   write32be(&superBlob->magic, CSMAGIC_EMBEDDED_SIGNATURE);
1003   write32be(&superBlob->length, signatureSize);
1004   write32be(&superBlob->count, 1);
1005   auto *blobIndex = reinterpret_cast<CS_BlobIndex *>(&superBlob[1]);
1006   write32be(&blobIndex->type, CSSLOT_CODEDIRECTORY);
1007   write32be(&blobIndex->offset, blobHeadersSize);
1008   auto *codeDirectory =
1009       reinterpret_cast<CS_CodeDirectory *>(buf + blobHeadersSize);
1010   write32be(&codeDirectory->magic, CSMAGIC_CODEDIRECTORY);
1011   write32be(&codeDirectory->length, signatureSize - blobHeadersSize);
1012   write32be(&codeDirectory->version, CS_SUPPORTSEXECSEG);
1013   write32be(&codeDirectory->flags, CS_ADHOC | CS_LINKER_SIGNED);
1014   write32be(&codeDirectory->hashOffset,
1015             sizeof(CS_CodeDirectory) + fileName.size() + fileNamePad);
1016   write32be(&codeDirectory->identOffset, sizeof(CS_CodeDirectory));
1017   codeDirectory->nSpecialSlots = 0;
1018   write32be(&codeDirectory->nCodeSlots, getBlockCount());
1019   write32be(&codeDirectory->codeLimit, fileOff);
1020   codeDirectory->hashSize = static_cast<uint8_t>(hashSize);
1021   codeDirectory->hashType = kSecCodeSignatureHashSHA256;
1022   codeDirectory->platform = 0;
1023   codeDirectory->pageSize = blockSizeShift;
1024   codeDirectory->spare2 = 0;
1025   codeDirectory->scatterOffset = 0;
1026   codeDirectory->teamOffset = 0;
1027   codeDirectory->spare3 = 0;
1028   codeDirectory->codeLimit64 = 0;
1029   OutputSegment *textSeg = getOrCreateOutputSegment(segment_names::text);
1030   write64be(&codeDirectory->execSegBase, textSeg->fileOff);
1031   write64be(&codeDirectory->execSegLimit, textSeg->fileSize);
1032   write64be(&codeDirectory->execSegFlags,
1033             config->outputType == MH_EXECUTE ? CS_EXECSEG_MAIN_BINARY : 0);
1034   auto *id = reinterpret_cast<char *>(&codeDirectory[1]);
1035   memcpy(id, fileName.begin(), fileName.size());
1036   memset(id + fileName.size(), 0, fileNamePad);
1037 }
1038 
1039 BitcodeBundleSection::BitcodeBundleSection()
1040     : SyntheticSection(segment_names::llvm, section_names::bitcodeBundle) {}
1041 
1042 class ErrorCodeWrapper {
1043 public:
1044   explicit ErrorCodeWrapper(std::error_code ec) : errorCode(ec.value()) {}
1045   explicit ErrorCodeWrapper(int ec) : errorCode(ec) {}
1046   operator int() const { return errorCode; }
1047 
1048 private:
1049   int errorCode;
1050 };
1051 
1052 #define CHECK_EC(exp)                                                          \
1053   do {                                                                         \
1054     ErrorCodeWrapper ec(exp);                                                  \
1055     if (ec)                                                                    \
1056       fatal(Twine("operation failed with error code ") + Twine(ec) + ": " +    \
1057             #exp);                                                             \
1058   } while (0);
1059 
1060 void BitcodeBundleSection::finalize() {
1061 #ifdef HAVE_LIBXAR
1062   using namespace llvm::sys::fs;
1063   CHECK_EC(createTemporaryFile("bitcode-bundle", "xar", xarPath));
1064 
1065   xar_t xar(xar_open(xarPath.data(), O_RDWR));
1066   if (!xar)
1067     fatal("failed to open XAR temporary file at " + xarPath);
1068   CHECK_EC(xar_opt_set(xar, XAR_OPT_COMPRESSION, XAR_OPT_VAL_NONE));
1069   // FIXME: add more data to XAR
1070   CHECK_EC(xar_close(xar));
1071 
1072   file_size(xarPath, xarSize);
1073 #endif // defined(HAVE_LIBXAR)
1074 }
1075 
1076 void BitcodeBundleSection::writeTo(uint8_t *buf) const {
1077   using namespace llvm::sys::fs;
1078   file_t handle =
1079       CHECK(openNativeFile(xarPath, CD_OpenExisting, FA_Read, OF_None),
1080             "failed to open XAR file");
1081   std::error_code ec;
1082   mapped_file_region xarMap(handle, mapped_file_region::mapmode::readonly,
1083                             xarSize, 0, ec);
1084   if (ec)
1085     fatal("failed to map XAR file");
1086   memcpy(buf, xarMap.const_data(), xarSize);
1087 
1088   closeFile(handle);
1089   remove(xarPath);
1090 }
1091 
1092 void macho::createSyntheticSymbols() {
1093   auto addHeaderSymbol = [](const char *name) {
1094     symtab->addSynthetic(name, in.header->isec, 0,
1095                          /*privateExtern=*/true,
1096                          /*includeInSymtab=*/false);
1097   };
1098 
1099   switch (config->outputType) {
1100     // FIXME: Assign the right address value for these symbols
1101     // (rather than 0). But we need to do that after assignAddresses().
1102   case MH_EXECUTE:
1103     // If linking PIE, __mh_execute_header is a defined symbol in
1104     //  __TEXT, __text)
1105     // Otherwise, it's an absolute symbol.
1106     if (config->isPic)
1107       symtab->addSynthetic("__mh_execute_header", in.header->isec, /*value=*/0,
1108                            /*privateExtern=*/false,
1109                            /*includeInSymtab=*/true);
1110     else
1111       symtab->addSynthetic("__mh_execute_header",
1112                            /*isec*/ nullptr, /*value=*/0,
1113                            /*privateExtern=*/false,
1114                            /*includeInSymtab=*/true);
1115     break;
1116 
1117     // The following symbols are  N_SECT symbols, even though the header is not
1118     // part of any section and that they are private to the bundle/dylib/object
1119     // they are part of.
1120   case MH_BUNDLE:
1121     addHeaderSymbol("__mh_bundle_header");
1122     break;
1123   case MH_DYLIB:
1124     addHeaderSymbol("__mh_dylib_header");
1125     break;
1126   case MH_DYLINKER:
1127     addHeaderSymbol("__mh_dylinker_header");
1128     break;
1129   case MH_OBJECT:
1130     addHeaderSymbol("__mh_object_header");
1131     break;
1132   default:
1133     llvm_unreachable("unexpected outputType");
1134     break;
1135   }
1136 
1137   // The Itanium C++ ABI requires dylibs to pass a pointer to __cxa_atexit
1138   // which does e.g. cleanup of static global variables. The ABI document
1139   // says that the pointer can point to any address in one of the dylib's
1140   // segments, but in practice ld64 seems to set it to point to the header,
1141   // so that's what's implemented here.
1142   addHeaderSymbol("___dso_handle");
1143 }
1144 
1145 template SymtabSection *macho::makeSymtabSection<LP64>(StringTableSection &);
1146 template SymtabSection *macho::makeSymtabSection<ILP32>(StringTableSection &);
1147