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