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