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