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