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