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 
19 #include "lld/Common/CommonLinkerContext.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Config/llvm-config.h"
22 #include "llvm/Support/EndianStream.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/LEB128.h"
25 #include "llvm/Support/Parallel.h"
26 #include "llvm/Support/Path.h"
27 
28 #if defined(__APPLE__)
29 #include <sys/mman.h>
30 
31 #define COMMON_DIGEST_FOR_OPENSSL
32 #include <CommonCrypto/CommonDigest.h>
33 #else
34 #include "llvm/Support/SHA256.h"
35 #endif
36 
37 #ifdef LLVM_HAVE_LIBXAR
38 #include <fcntl.h>
39 extern "C" {
40 #include <xar/xar.h>
41 }
42 #endif
43 
44 using namespace llvm;
45 using namespace llvm::MachO;
46 using namespace llvm::support;
47 using namespace llvm::support::endian;
48 using namespace lld;
49 using namespace lld::macho;
50 
51 // Reads `len` bytes at data and writes the 32-byte SHA256 checksum to `output`.
52 static void sha256(const uint8_t *data, size_t len, uint8_t *output) {
53 #if defined(__APPLE__)
54   // FIXME: Make LLVM's SHA256 faster and use it unconditionally. See PR56121
55   // for some notes on this.
56   CC_SHA256(data, len, output);
57 #else
58   ArrayRef<uint8_t> block(data, len);
59   std::array<uint8_t, 32> hash = SHA256::hash(block);
60   assert(hash.size() == CodeSignatureSection::hashSize);
61   memcpy(output, hash.data(), hash.size());
62 #endif
63 }
64 
65 InStruct macho::in;
66 std::vector<SyntheticSection *> macho::syntheticSections;
67 
68 SyntheticSection::SyntheticSection(const char *segname, const char *name)
69     : OutputSection(SyntheticKind, name) {
70   std::tie(this->segname, this->name) = maybeRenameSection({segname, name});
71   isec = makeSyntheticInputSection(segname, name);
72   isec->parent = this;
73   syntheticSections.push_back(this);
74 }
75 
76 // dyld3's MachOLoaded::getSlide() assumes that the __TEXT segment starts
77 // from the beginning of the file (i.e. the header).
78 MachHeaderSection::MachHeaderSection()
79     : SyntheticSection(segment_names::text, section_names::header) {
80   // XXX: This is a hack. (See D97007)
81   // Setting the index to 1 to pretend that this section is the text
82   // section.
83   index = 1;
84   isec->isFinal = true;
85 }
86 
87 void MachHeaderSection::addLoadCommand(LoadCommand *lc) {
88   loadCommands.push_back(lc);
89   sizeOfCmds += lc->getSize();
90 }
91 
92 uint64_t MachHeaderSection::getSize() const {
93   uint64_t size = target->headerSize + sizeOfCmds + config->headerPad;
94   // If we are emitting an encryptable binary, our load commands must have a
95   // separate (non-encrypted) page to themselves.
96   if (config->emitEncryptionInfo)
97     size = alignTo(size, target->getPageSize());
98   return size;
99 }
100 
101 static uint32_t cpuSubtype() {
102   uint32_t subtype = target->cpuSubtype;
103 
104   if (config->outputType == MH_EXECUTE && !config->staticLink &&
105       target->cpuSubtype == CPU_SUBTYPE_X86_64_ALL &&
106       config->platform() == PLATFORM_MACOS &&
107       config->platformInfo.minimum >= VersionTuple(10, 5))
108     subtype |= CPU_SUBTYPE_LIB64;
109 
110   return subtype;
111 }
112 
113 void MachHeaderSection::writeTo(uint8_t *buf) const {
114   auto *hdr = reinterpret_cast<mach_header *>(buf);
115   hdr->magic = target->magic;
116   hdr->cputype = target->cpuType;
117   hdr->cpusubtype = cpuSubtype();
118   hdr->filetype = config->outputType;
119   hdr->ncmds = loadCommands.size();
120   hdr->sizeofcmds = sizeOfCmds;
121   hdr->flags = MH_DYLDLINK;
122 
123   if (config->namespaceKind == NamespaceKind::twolevel)
124     hdr->flags |= MH_NOUNDEFS | MH_TWOLEVEL;
125 
126   if (config->outputType == MH_DYLIB && !config->hasReexports)
127     hdr->flags |= MH_NO_REEXPORTED_DYLIBS;
128 
129   if (config->markDeadStrippableDylib)
130     hdr->flags |= MH_DEAD_STRIPPABLE_DYLIB;
131 
132   if (config->outputType == MH_EXECUTE && config->isPic)
133     hdr->flags |= MH_PIE;
134 
135   if (config->outputType == MH_DYLIB && config->applicationExtension)
136     hdr->flags |= MH_APP_EXTENSION_SAFE;
137 
138   if (in.exports->hasWeakSymbol || in.weakBinding->hasNonWeakDefinition())
139     hdr->flags |= MH_WEAK_DEFINES;
140 
141   if (in.exports->hasWeakSymbol || in.weakBinding->hasEntry())
142     hdr->flags |= MH_BINDS_TO_WEAK;
143 
144   for (const OutputSegment *seg : outputSegments) {
145     for (const OutputSection *osec : seg->getSections()) {
146       if (isThreadLocalVariables(osec->flags)) {
147         hdr->flags |= MH_HAS_TLV_DESCRIPTORS;
148         break;
149       }
150     }
151   }
152 
153   uint8_t *p = reinterpret_cast<uint8_t *>(hdr) + target->headerSize;
154   for (const LoadCommand *lc : loadCommands) {
155     lc->writeTo(p);
156     p += lc->getSize();
157   }
158 }
159 
160 PageZeroSection::PageZeroSection()
161     : SyntheticSection(segment_names::pageZero, section_names::pageZero) {}
162 
163 RebaseSection::RebaseSection()
164     : LinkEditSection(segment_names::linkEdit, section_names::rebase) {}
165 
166 namespace {
167 struct Rebase {
168   OutputSegment *segment = nullptr;
169   uint64_t offset = 0;
170   uint64_t consecutiveCount = 0;
171 };
172 } // namespace
173 
174 // Rebase opcodes allow us to describe a contiguous sequence of rebase location
175 // using a single DO_REBASE opcode. To take advantage of it, we delay emitting
176 // `DO_REBASE` until we have reached the end of a contiguous sequence.
177 static void encodeDoRebase(Rebase &rebase, raw_svector_ostream &os) {
178   assert(rebase.consecutiveCount != 0);
179   if (rebase.consecutiveCount <= REBASE_IMMEDIATE_MASK) {
180     os << static_cast<uint8_t>(REBASE_OPCODE_DO_REBASE_IMM_TIMES |
181                                rebase.consecutiveCount);
182   } else {
183     os << static_cast<uint8_t>(REBASE_OPCODE_DO_REBASE_ULEB_TIMES);
184     encodeULEB128(rebase.consecutiveCount, os);
185   }
186   rebase.consecutiveCount = 0;
187 }
188 
189 static void encodeRebase(const OutputSection *osec, uint64_t outSecOff,
190                          Rebase &lastRebase, raw_svector_ostream &os) {
191   OutputSegment *seg = osec->parent;
192   uint64_t offset = osec->getSegmentOffset() + outSecOff;
193   if (lastRebase.segment != seg || lastRebase.offset != offset) {
194     if (lastRebase.consecutiveCount != 0)
195       encodeDoRebase(lastRebase, os);
196 
197     if (lastRebase.segment != seg) {
198       os << static_cast<uint8_t>(REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB |
199                                  seg->index);
200       encodeULEB128(offset, os);
201       lastRebase.segment = seg;
202       lastRebase.offset = offset;
203     } else {
204       assert(lastRebase.offset != offset);
205       os << static_cast<uint8_t>(REBASE_OPCODE_ADD_ADDR_ULEB);
206       encodeULEB128(offset - lastRebase.offset, os);
207       lastRebase.offset = offset;
208     }
209   }
210   ++lastRebase.consecutiveCount;
211   // DO_REBASE causes dyld to both perform the binding and increment the offset
212   lastRebase.offset += target->wordSize;
213 }
214 
215 void RebaseSection::finalizeContents() {
216   if (locations.empty())
217     return;
218 
219   raw_svector_ostream os{contents};
220   Rebase lastRebase;
221 
222   os << static_cast<uint8_t>(REBASE_OPCODE_SET_TYPE_IMM | REBASE_TYPE_POINTER);
223 
224   llvm::sort(locations, [](const Location &a, const Location &b) {
225     return a.isec->getVA(a.offset) < b.isec->getVA(b.offset);
226   });
227   for (const Location &loc : locations)
228     encodeRebase(loc.isec->parent, loc.isec->getOffset(loc.offset), lastRebase,
229                  os);
230   if (lastRebase.consecutiveCount != 0)
231     encodeDoRebase(lastRebase, os);
232 
233   os << static_cast<uint8_t>(REBASE_OPCODE_DONE);
234 }
235 
236 void RebaseSection::writeTo(uint8_t *buf) const {
237   memcpy(buf, contents.data(), contents.size());
238 }
239 
240 NonLazyPointerSectionBase::NonLazyPointerSectionBase(const char *segname,
241                                                      const char *name)
242     : SyntheticSection(segname, name) {
243   align = target->wordSize;
244 }
245 
246 void macho::addNonLazyBindingEntries(const Symbol *sym,
247                                      const InputSection *isec, uint64_t offset,
248                                      int64_t addend) {
249   if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) {
250     in.binding->addEntry(dysym, isec, offset, addend);
251     if (dysym->isWeakDef())
252       in.weakBinding->addEntry(sym, isec, offset, addend);
253   } else if (const auto *defined = dyn_cast<Defined>(sym)) {
254     in.rebase->addEntry(isec, offset);
255     if (defined->isExternalWeakDef())
256       in.weakBinding->addEntry(sym, isec, offset, addend);
257     else if (defined->interposable)
258       in.binding->addEntry(sym, isec, offset, addend);
259   } else {
260     // Undefined symbols are filtered out in scanRelocations(); we should never
261     // get here
262     llvm_unreachable("cannot bind to an undefined symbol");
263   }
264 }
265 
266 void NonLazyPointerSectionBase::addEntry(Symbol *sym) {
267   if (entries.insert(sym)) {
268     assert(!sym->isInGot());
269     sym->gotIndex = entries.size() - 1;
270 
271     addNonLazyBindingEntries(sym, isec, sym->gotIndex * target->wordSize);
272   }
273 }
274 
275 void NonLazyPointerSectionBase::writeTo(uint8_t *buf) const {
276   for (size_t i = 0, n = entries.size(); i < n; ++i)
277     if (auto *defined = dyn_cast<Defined>(entries[i]))
278       write64le(&buf[i * target->wordSize], defined->getVA());
279 }
280 
281 GotSection::GotSection()
282     : NonLazyPointerSectionBase(segment_names::data, section_names::got) {
283   flags = S_NON_LAZY_SYMBOL_POINTERS;
284 }
285 
286 TlvPointerSection::TlvPointerSection()
287     : NonLazyPointerSectionBase(segment_names::data,
288                                 section_names::threadPtrs) {
289   flags = S_THREAD_LOCAL_VARIABLE_POINTERS;
290 }
291 
292 BindingSection::BindingSection()
293     : LinkEditSection(segment_names::linkEdit, section_names::binding) {}
294 
295 namespace {
296 struct Binding {
297   OutputSegment *segment = nullptr;
298   uint64_t offset = 0;
299   int64_t addend = 0;
300 };
301 struct BindIR {
302   // Default value of 0xF0 is not valid opcode and should make the program
303   // scream instead of accidentally writing "valid" values.
304   uint8_t opcode = 0xF0;
305   uint64_t data = 0;
306   uint64_t consecutiveCount = 0;
307 };
308 } // namespace
309 
310 // Encode a sequence of opcodes that tell dyld to write the address of symbol +
311 // addend at osec->addr + outSecOff.
312 //
313 // The bind opcode "interpreter" remembers the values of each binding field, so
314 // we only need to encode the differences between bindings. Hence the use of
315 // lastBinding.
316 static void encodeBinding(const OutputSection *osec, uint64_t outSecOff,
317                           int64_t addend, Binding &lastBinding,
318                           std::vector<BindIR> &opcodes) {
319   OutputSegment *seg = osec->parent;
320   uint64_t offset = osec->getSegmentOffset() + outSecOff;
321   if (lastBinding.segment != seg) {
322     opcodes.push_back(
323         {static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB |
324                               seg->index),
325          offset});
326     lastBinding.segment = seg;
327     lastBinding.offset = offset;
328   } else if (lastBinding.offset != offset) {
329     opcodes.push_back({BIND_OPCODE_ADD_ADDR_ULEB, offset - lastBinding.offset});
330     lastBinding.offset = offset;
331   }
332 
333   if (lastBinding.addend != addend) {
334     opcodes.push_back(
335         {BIND_OPCODE_SET_ADDEND_SLEB, static_cast<uint64_t>(addend)});
336     lastBinding.addend = addend;
337   }
338 
339   opcodes.push_back({BIND_OPCODE_DO_BIND, 0});
340   // DO_BIND causes dyld to both perform the binding and increment the offset
341   lastBinding.offset += target->wordSize;
342 }
343 
344 static void optimizeOpcodes(std::vector<BindIR> &opcodes) {
345   // Pass 1: Combine bind/add pairs
346   size_t i;
347   int pWrite = 0;
348   for (i = 1; i < opcodes.size(); ++i, ++pWrite) {
349     if ((opcodes[i].opcode == BIND_OPCODE_ADD_ADDR_ULEB) &&
350         (opcodes[i - 1].opcode == BIND_OPCODE_DO_BIND)) {
351       opcodes[pWrite].opcode = BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB;
352       opcodes[pWrite].data = opcodes[i].data;
353       ++i;
354     } else {
355       opcodes[pWrite] = opcodes[i - 1];
356     }
357   }
358   if (i == opcodes.size())
359     opcodes[pWrite] = opcodes[i - 1];
360   opcodes.resize(pWrite + 1);
361 
362   // Pass 2: Compress two or more bind_add opcodes
363   pWrite = 0;
364   for (i = 1; i < opcodes.size(); ++i, ++pWrite) {
365     if ((opcodes[i].opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) &&
366         (opcodes[i - 1].opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) &&
367         (opcodes[i].data == opcodes[i - 1].data)) {
368       opcodes[pWrite].opcode = BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB;
369       opcodes[pWrite].consecutiveCount = 2;
370       opcodes[pWrite].data = opcodes[i].data;
371       ++i;
372       while (i < opcodes.size() &&
373              (opcodes[i].opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) &&
374              (opcodes[i].data == opcodes[i - 1].data)) {
375         opcodes[pWrite].consecutiveCount++;
376         ++i;
377       }
378     } else {
379       opcodes[pWrite] = opcodes[i - 1];
380     }
381   }
382   if (i == opcodes.size())
383     opcodes[pWrite] = opcodes[i - 1];
384   opcodes.resize(pWrite + 1);
385 
386   // Pass 3: Use immediate encodings
387   // Every binding is the size of one pointer. If the next binding is a
388   // multiple of wordSize away that is within BIND_IMMEDIATE_MASK, the
389   // opcode can be scaled by wordSize into a single byte and dyld will
390   // expand it to the correct address.
391   for (auto &p : opcodes) {
392     // It's unclear why the check needs to be less than BIND_IMMEDIATE_MASK,
393     // but ld64 currently does this. This could be a potential bug, but
394     // for now, perform the same behavior to prevent mysterious bugs.
395     if ((p.opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) &&
396         ((p.data / target->wordSize) < BIND_IMMEDIATE_MASK) &&
397         ((p.data % target->wordSize) == 0)) {
398       p.opcode = BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED;
399       p.data /= target->wordSize;
400     }
401   }
402 }
403 
404 static void flushOpcodes(const BindIR &op, raw_svector_ostream &os) {
405   uint8_t opcode = op.opcode & BIND_OPCODE_MASK;
406   switch (opcode) {
407   case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
408   case BIND_OPCODE_ADD_ADDR_ULEB:
409   case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
410     os << op.opcode;
411     encodeULEB128(op.data, os);
412     break;
413   case BIND_OPCODE_SET_ADDEND_SLEB:
414     os << op.opcode;
415     encodeSLEB128(static_cast<int64_t>(op.data), os);
416     break;
417   case BIND_OPCODE_DO_BIND:
418     os << op.opcode;
419     break;
420   case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
421     os << op.opcode;
422     encodeULEB128(op.consecutiveCount, os);
423     encodeULEB128(op.data, os);
424     break;
425   case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
426     os << static_cast<uint8_t>(op.opcode | op.data);
427     break;
428   default:
429     llvm_unreachable("cannot bind to an unrecognized symbol");
430   }
431 }
432 
433 // Non-weak bindings need to have their dylib ordinal encoded as well.
434 static int16_t ordinalForDylibSymbol(const DylibSymbol &dysym) {
435   if (config->namespaceKind == NamespaceKind::flat || dysym.isDynamicLookup())
436     return static_cast<int16_t>(BIND_SPECIAL_DYLIB_FLAT_LOOKUP);
437   assert(dysym.getFile()->isReferenced());
438   return dysym.getFile()->ordinal;
439 }
440 
441 static int16_t ordinalForSymbol(const Symbol &sym) {
442   if (const auto *dysym = dyn_cast<DylibSymbol>(&sym))
443     return ordinalForDylibSymbol(*dysym);
444   assert(cast<Defined>(&sym)->interposable);
445   return BIND_SPECIAL_DYLIB_FLAT_LOOKUP;
446 }
447 
448 static void encodeDylibOrdinal(int16_t ordinal, raw_svector_ostream &os) {
449   if (ordinal <= 0) {
450     os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM |
451                                (ordinal & BIND_IMMEDIATE_MASK));
452   } else if (ordinal <= BIND_IMMEDIATE_MASK) {
453     os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | ordinal);
454   } else {
455     os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB);
456     encodeULEB128(ordinal, os);
457   }
458 }
459 
460 static void encodeWeakOverride(const Defined *defined,
461                                raw_svector_ostream &os) {
462   os << static_cast<uint8_t>(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM |
463                              BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
464      << defined->getName() << '\0';
465 }
466 
467 // Organize the bindings so we can encoded them with fewer opcodes.
468 //
469 // First, all bindings for a given symbol should be grouped together.
470 // BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM is the largest opcode (since it
471 // has an associated symbol string), so we only want to emit it once per symbol.
472 //
473 // Within each group, we sort the bindings by address. Since bindings are
474 // delta-encoded, sorting them allows for a more compact result. Note that
475 // sorting by address alone ensures that bindings for the same segment / section
476 // are located together, minimizing the number of times we have to emit
477 // BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB.
478 //
479 // Finally, we sort the symbols by the address of their first binding, again
480 // to facilitate the delta-encoding process.
481 template <class Sym>
482 std::vector<std::pair<const Sym *, std::vector<BindingEntry>>>
483 sortBindings(const BindingsMap<const Sym *> &bindingsMap) {
484   std::vector<std::pair<const Sym *, std::vector<BindingEntry>>> bindingsVec(
485       bindingsMap.begin(), bindingsMap.end());
486   for (auto &p : bindingsVec) {
487     std::vector<BindingEntry> &bindings = p.second;
488     llvm::sort(bindings, [](const BindingEntry &a, const BindingEntry &b) {
489       return a.target.getVA() < b.target.getVA();
490     });
491   }
492   llvm::sort(bindingsVec, [](const auto &a, const auto &b) {
493     return a.second[0].target.getVA() < b.second[0].target.getVA();
494   });
495   return bindingsVec;
496 }
497 
498 // Emit bind opcodes, which are a stream of byte-sized opcodes that dyld
499 // interprets to update a record with the following fields:
500 //  * segment index (of the segment to write the symbol addresses to, typically
501 //    the __DATA_CONST segment which contains the GOT)
502 //  * offset within the segment, indicating the next location to write a binding
503 //  * symbol type
504 //  * symbol library ordinal (the index of its library's LC_LOAD_DYLIB command)
505 //  * symbol name
506 //  * addend
507 // When dyld sees BIND_OPCODE_DO_BIND, it uses the current record state to bind
508 // a symbol in the GOT, and increments the segment offset to point to the next
509 // entry. It does *not* clear the record state after doing the bind, so
510 // subsequent opcodes only need to encode the differences between bindings.
511 void BindingSection::finalizeContents() {
512   raw_svector_ostream os{contents};
513   Binding lastBinding;
514   int16_t lastOrdinal = 0;
515 
516   for (auto &p : sortBindings(bindingsMap)) {
517     const Symbol *sym = p.first;
518     std::vector<BindingEntry> &bindings = p.second;
519     uint8_t flags = BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM;
520     if (sym->isWeakRef())
521       flags |= BIND_SYMBOL_FLAGS_WEAK_IMPORT;
522     os << flags << sym->getName() << '\0'
523        << static_cast<uint8_t>(BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER);
524     int16_t ordinal = ordinalForSymbol(*sym);
525     if (ordinal != lastOrdinal) {
526       encodeDylibOrdinal(ordinal, os);
527       lastOrdinal = ordinal;
528     }
529     std::vector<BindIR> opcodes;
530     for (const BindingEntry &b : bindings)
531       encodeBinding(b.target.isec->parent,
532                     b.target.isec->getOffset(b.target.offset), b.addend,
533                     lastBinding, opcodes);
534     if (config->optimize > 1)
535       optimizeOpcodes(opcodes);
536     for (const auto &op : opcodes)
537       flushOpcodes(op, os);
538   }
539   if (!bindingsMap.empty())
540     os << static_cast<uint8_t>(BIND_OPCODE_DONE);
541 }
542 
543 void BindingSection::writeTo(uint8_t *buf) const {
544   memcpy(buf, contents.data(), contents.size());
545 }
546 
547 WeakBindingSection::WeakBindingSection()
548     : LinkEditSection(segment_names::linkEdit, section_names::weakBinding) {}
549 
550 void WeakBindingSection::finalizeContents() {
551   raw_svector_ostream os{contents};
552   Binding lastBinding;
553 
554   for (const Defined *defined : definitions)
555     encodeWeakOverride(defined, os);
556 
557   for (auto &p : sortBindings(bindingsMap)) {
558     const Symbol *sym = p.first;
559     std::vector<BindingEntry> &bindings = p.second;
560     os << static_cast<uint8_t>(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM)
561        << sym->getName() << '\0'
562        << static_cast<uint8_t>(BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER);
563     std::vector<BindIR> opcodes;
564     for (const BindingEntry &b : bindings)
565       encodeBinding(b.target.isec->parent,
566                     b.target.isec->getOffset(b.target.offset), b.addend,
567                     lastBinding, opcodes);
568     if (config->optimize > 1)
569       optimizeOpcodes(opcodes);
570     for (const auto &op : opcodes)
571       flushOpcodes(op, os);
572   }
573   if (!bindingsMap.empty() || !definitions.empty())
574     os << static_cast<uint8_t>(BIND_OPCODE_DONE);
575 }
576 
577 void WeakBindingSection::writeTo(uint8_t *buf) const {
578   memcpy(buf, contents.data(), contents.size());
579 }
580 
581 StubsSection::StubsSection()
582     : SyntheticSection(segment_names::text, section_names::stubs) {
583   flags = S_SYMBOL_STUBS | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
584   // The stubs section comprises machine instructions, which are aligned to
585   // 4 bytes on the archs we care about.
586   align = 4;
587   reserved2 = target->stubSize;
588 }
589 
590 uint64_t StubsSection::getSize() const {
591   return entries.size() * target->stubSize;
592 }
593 
594 void StubsSection::writeTo(uint8_t *buf) const {
595   size_t off = 0;
596   for (const Symbol *sym : entries) {
597     target->writeStub(buf + off, *sym);
598     off += target->stubSize;
599   }
600 }
601 
602 void StubsSection::finalize() { isFinal = true; }
603 
604 bool StubsSection::addEntry(Symbol *sym) {
605   bool inserted = entries.insert(sym);
606   if (inserted)
607     sym->stubsIndex = entries.size() - 1;
608   return inserted;
609 }
610 
611 StubHelperSection::StubHelperSection()
612     : SyntheticSection(segment_names::text, section_names::stubHelper) {
613   flags = S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
614   align = 4; // This section comprises machine instructions
615 }
616 
617 uint64_t StubHelperSection::getSize() const {
618   return target->stubHelperHeaderSize +
619          in.lazyBinding->getEntries().size() * target->stubHelperEntrySize;
620 }
621 
622 bool StubHelperSection::isNeeded() const { return in.lazyBinding->isNeeded(); }
623 
624 void StubHelperSection::writeTo(uint8_t *buf) const {
625   target->writeStubHelperHeader(buf);
626   size_t off = target->stubHelperHeaderSize;
627   for (const Symbol *sym : in.lazyBinding->getEntries()) {
628     target->writeStubHelperEntry(buf + off, *sym, addr + off);
629     off += target->stubHelperEntrySize;
630   }
631 }
632 
633 void StubHelperSection::setup() {
634   Symbol *binder = symtab->addUndefined("dyld_stub_binder", /*file=*/nullptr,
635                                         /*isWeakRef=*/false);
636   if (auto *undefined = dyn_cast<Undefined>(binder))
637     treatUndefinedSymbol(*undefined,
638                          "lazy binding (normally in libSystem.dylib)");
639 
640   // treatUndefinedSymbol() can replace binder with a DylibSymbol; re-check.
641   stubBinder = dyn_cast_or_null<DylibSymbol>(binder);
642   if (stubBinder == nullptr)
643     return;
644 
645   in.got->addEntry(stubBinder);
646 
647   in.imageLoaderCache->parent =
648       ConcatOutputSection::getOrCreateForInput(in.imageLoaderCache);
649   inputSections.push_back(in.imageLoaderCache);
650   // Since this isn't in the symbol table or in any input file, the noDeadStrip
651   // argument doesn't matter.
652   dyldPrivate =
653       make<Defined>("__dyld_private", nullptr, in.imageLoaderCache, 0, 0,
654                     /*isWeakDef=*/false,
655                     /*isExternal=*/false, /*isPrivateExtern=*/false,
656                     /*includeInSymtab=*/true,
657                     /*isThumb=*/false, /*isReferencedDynamically=*/false,
658                     /*noDeadStrip=*/false);
659   dyldPrivate->used = true;
660 }
661 
662 LazyPointerSection::LazyPointerSection()
663     : SyntheticSection(segment_names::data, section_names::lazySymbolPtr) {
664   align = target->wordSize;
665   flags = S_LAZY_SYMBOL_POINTERS;
666 }
667 
668 uint64_t LazyPointerSection::getSize() const {
669   return in.stubs->getEntries().size() * target->wordSize;
670 }
671 
672 bool LazyPointerSection::isNeeded() const {
673   return !in.stubs->getEntries().empty();
674 }
675 
676 void LazyPointerSection::writeTo(uint8_t *buf) const {
677   size_t off = 0;
678   for (const Symbol *sym : in.stubs->getEntries()) {
679     if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) {
680       if (dysym->hasStubsHelper()) {
681         uint64_t stubHelperOffset =
682             target->stubHelperHeaderSize +
683             dysym->stubsHelperIndex * target->stubHelperEntrySize;
684         write64le(buf + off, in.stubHelper->addr + stubHelperOffset);
685       }
686     } else {
687       write64le(buf + off, sym->getVA());
688     }
689     off += target->wordSize;
690   }
691 }
692 
693 LazyBindingSection::LazyBindingSection()
694     : LinkEditSection(segment_names::linkEdit, section_names::lazyBinding) {}
695 
696 void LazyBindingSection::finalizeContents() {
697   // TODO: Just precompute output size here instead of writing to a temporary
698   // buffer
699   for (Symbol *sym : entries)
700     sym->lazyBindOffset = encode(*sym);
701 }
702 
703 void LazyBindingSection::writeTo(uint8_t *buf) const {
704   memcpy(buf, contents.data(), contents.size());
705 }
706 
707 void LazyBindingSection::addEntry(Symbol *sym) {
708   if (entries.insert(sym)) {
709     sym->stubsHelperIndex = entries.size() - 1;
710     in.rebase->addEntry(in.lazyPointers->isec,
711                         sym->stubsIndex * target->wordSize);
712   }
713 }
714 
715 // Unlike the non-lazy binding section, the bind opcodes in this section aren't
716 // interpreted all at once. Rather, dyld will start interpreting opcodes at a
717 // given offset, typically only binding a single symbol before it finds a
718 // BIND_OPCODE_DONE terminator. As such, unlike in the non-lazy-binding case,
719 // we cannot encode just the differences between symbols; we have to emit the
720 // complete bind information for each symbol.
721 uint32_t LazyBindingSection::encode(const Symbol &sym) {
722   uint32_t opstreamOffset = contents.size();
723   OutputSegment *dataSeg = in.lazyPointers->parent;
724   os << static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB |
725                              dataSeg->index);
726   uint64_t offset =
727       in.lazyPointers->addr - dataSeg->addr + sym.stubsIndex * target->wordSize;
728   encodeULEB128(offset, os);
729   encodeDylibOrdinal(ordinalForSymbol(sym), os);
730 
731   uint8_t flags = BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM;
732   if (sym.isWeakRef())
733     flags |= BIND_SYMBOL_FLAGS_WEAK_IMPORT;
734 
735   os << flags << sym.getName() << '\0'
736      << static_cast<uint8_t>(BIND_OPCODE_DO_BIND)
737      << static_cast<uint8_t>(BIND_OPCODE_DONE);
738   return opstreamOffset;
739 }
740 
741 ExportSection::ExportSection()
742     : LinkEditSection(segment_names::linkEdit, section_names::export_) {}
743 
744 void ExportSection::finalizeContents() {
745   trieBuilder.setImageBase(in.header->addr);
746   for (const Symbol *sym : symtab->getSymbols()) {
747     if (const auto *defined = dyn_cast<Defined>(sym)) {
748       if (defined->privateExtern || !defined->isLive())
749         continue;
750       trieBuilder.addSymbol(*defined);
751       hasWeakSymbol = hasWeakSymbol || sym->isWeakDef();
752     }
753   }
754   size = trieBuilder.build();
755 }
756 
757 void ExportSection::writeTo(uint8_t *buf) const { trieBuilder.writeTo(buf); }
758 
759 DataInCodeSection::DataInCodeSection()
760     : LinkEditSection(segment_names::linkEdit, section_names::dataInCode) {}
761 
762 template <class LP>
763 static std::vector<MachO::data_in_code_entry> collectDataInCodeEntries() {
764   std::vector<MachO::data_in_code_entry> dataInCodeEntries;
765   for (const InputFile *inputFile : inputFiles) {
766     if (!isa<ObjFile>(inputFile))
767       continue;
768     const ObjFile *objFile = cast<ObjFile>(inputFile);
769     ArrayRef<MachO::data_in_code_entry> entries = objFile->getDataInCode();
770     if (entries.empty())
771       continue;
772 
773     assert(is_sorted(dataInCodeEntries, [](const data_in_code_entry &lhs,
774                                            const data_in_code_entry &rhs) {
775       return lhs.offset < rhs.offset;
776     }));
777     // For each code subsection find 'data in code' entries residing in it.
778     // Compute the new offset values as
779     // <offset within subsection> + <subsection address> - <__TEXT address>.
780     for (const Section *section : objFile->sections) {
781       for (const Subsection &subsec : section->subsections) {
782         const InputSection *isec = subsec.isec;
783         if (!isCodeSection(isec))
784           continue;
785         if (cast<ConcatInputSection>(isec)->shouldOmitFromOutput())
786           continue;
787         const uint64_t beginAddr = section->addr + subsec.offset;
788         auto it = llvm::lower_bound(
789             entries, beginAddr,
790             [](const MachO::data_in_code_entry &entry, uint64_t addr) {
791               return entry.offset < addr;
792             });
793         const uint64_t endAddr = beginAddr + isec->getSize();
794         for (const auto end = entries.end();
795              it != end && it->offset + it->length <= endAddr; ++it)
796           dataInCodeEntries.push_back(
797               {static_cast<uint32_t>(isec->getVA(it->offset - beginAddr) -
798                                      in.header->addr),
799                it->length, it->kind});
800       }
801     }
802   }
803   return dataInCodeEntries;
804 }
805 
806 void DataInCodeSection::finalizeContents() {
807   entries = target->wordSize == 8 ? collectDataInCodeEntries<LP64>()
808                                   : collectDataInCodeEntries<ILP32>();
809 }
810 
811 void DataInCodeSection::writeTo(uint8_t *buf) const {
812   if (!entries.empty())
813     memcpy(buf, entries.data(), getRawSize());
814 }
815 
816 FunctionStartsSection::FunctionStartsSection()
817     : LinkEditSection(segment_names::linkEdit, section_names::functionStarts) {}
818 
819 void FunctionStartsSection::finalizeContents() {
820   raw_svector_ostream os{contents};
821   std::vector<uint64_t> addrs;
822   for (const InputFile *file : inputFiles) {
823     if (auto *objFile = dyn_cast<ObjFile>(file)) {
824       for (const Symbol *sym : objFile->symbols) {
825         if (const auto *defined = dyn_cast_or_null<Defined>(sym)) {
826           if (!defined->isec || !isCodeSection(defined->isec) ||
827               !defined->isLive())
828             continue;
829           // TODO: Add support for thumbs, in that case
830           // the lowest bit of nextAddr needs to be set to 1.
831           addrs.push_back(defined->getVA());
832         }
833       }
834     }
835   }
836   llvm::sort(addrs);
837   uint64_t addr = in.header->addr;
838   for (uint64_t nextAddr : addrs) {
839     uint64_t delta = nextAddr - addr;
840     if (delta == 0)
841       continue;
842     encodeULEB128(delta, os);
843     addr = nextAddr;
844   }
845   os << '\0';
846 }
847 
848 void FunctionStartsSection::writeTo(uint8_t *buf) const {
849   memcpy(buf, contents.data(), contents.size());
850 }
851 
852 SymtabSection::SymtabSection(StringTableSection &stringTableSection)
853     : LinkEditSection(segment_names::linkEdit, section_names::symbolTable),
854       stringTableSection(stringTableSection) {}
855 
856 void SymtabSection::emitBeginSourceStab(StringRef sourceFile) {
857   StabsEntry stab(N_SO);
858   stab.strx = stringTableSection.addString(saver().save(sourceFile));
859   stabs.emplace_back(std::move(stab));
860 }
861 
862 void SymtabSection::emitEndSourceStab() {
863   StabsEntry stab(N_SO);
864   stab.sect = 1;
865   stabs.emplace_back(std::move(stab));
866 }
867 
868 void SymtabSection::emitObjectFileStab(ObjFile *file) {
869   StabsEntry stab(N_OSO);
870   stab.sect = target->cpuSubtype;
871   SmallString<261> path(!file->archiveName.empty() ? file->archiveName
872                                                    : file->getName());
873   std::error_code ec = sys::fs::make_absolute(path);
874   if (ec)
875     fatal("failed to get absolute path for " + path);
876 
877   if (!file->archiveName.empty())
878     path.append({"(", file->getName(), ")"});
879 
880   StringRef adjustedPath = saver().save(path.str());
881   adjustedPath.consume_front(config->osoPrefix);
882 
883   stab.strx = stringTableSection.addString(adjustedPath);
884   stab.desc = 1;
885   stab.value = file->modTime;
886   stabs.emplace_back(std::move(stab));
887 }
888 
889 void SymtabSection::emitEndFunStab(Defined *defined) {
890   StabsEntry stab(N_FUN);
891   stab.value = defined->size;
892   stabs.emplace_back(std::move(stab));
893 }
894 
895 void SymtabSection::emitStabs() {
896   if (config->omitDebugInfo)
897     return;
898 
899   for (const std::string &s : config->astPaths) {
900     StabsEntry astStab(N_AST);
901     astStab.strx = stringTableSection.addString(s);
902     stabs.emplace_back(std::move(astStab));
903   }
904 
905   // Cache the file ID for each symbol in an std::pair for faster sorting.
906   using SortingPair = std::pair<Defined *, int>;
907   std::vector<SortingPair> symbolsNeedingStabs;
908   for (const SymtabEntry &entry :
909        concat<SymtabEntry>(localSymbols, externalSymbols)) {
910     Symbol *sym = entry.sym;
911     assert(sym->isLive() &&
912            "dead symbols should not be in localSymbols, externalSymbols");
913     if (auto *defined = dyn_cast<Defined>(sym)) {
914       // Excluded symbols should have been filtered out in finalizeContents().
915       assert(defined->includeInSymtab);
916 
917       if (defined->isAbsolute())
918         continue;
919 
920       // Constant-folded symbols go in the executable's symbol table, but don't
921       // get a stabs entry.
922       if (defined->wasIdenticalCodeFolded)
923         continue;
924 
925       InputSection *isec = defined->isec;
926       ObjFile *file = dyn_cast_or_null<ObjFile>(isec->getFile());
927       if (!file || !file->compileUnit)
928         continue;
929 
930       symbolsNeedingStabs.emplace_back(defined, defined->isec->getFile()->id);
931     }
932   }
933 
934   llvm::stable_sort(symbolsNeedingStabs,
935                     [&](const SortingPair &a, const SortingPair &b) {
936                       return a.second < b.second;
937                     });
938 
939   // Emit STABS symbols so that dsymutil and/or the debugger can map address
940   // regions in the final binary to the source and object files from which they
941   // originated.
942   InputFile *lastFile = nullptr;
943   for (SortingPair &pair : symbolsNeedingStabs) {
944     Defined *defined = pair.first;
945     InputSection *isec = defined->isec;
946     ObjFile *file = cast<ObjFile>(isec->getFile());
947 
948     if (lastFile == nullptr || lastFile != file) {
949       if (lastFile != nullptr)
950         emitEndSourceStab();
951       lastFile = file;
952 
953       emitBeginSourceStab(file->sourceFile());
954       emitObjectFileStab(file);
955     }
956 
957     StabsEntry symStab;
958     symStab.sect = defined->isec->parent->index;
959     symStab.strx = stringTableSection.addString(defined->getName());
960     symStab.value = defined->getVA();
961 
962     if (isCodeSection(isec)) {
963       symStab.type = N_FUN;
964       stabs.emplace_back(std::move(symStab));
965       emitEndFunStab(defined);
966     } else {
967       symStab.type = defined->isExternal() ? N_GSYM : N_STSYM;
968       stabs.emplace_back(std::move(symStab));
969     }
970   }
971 
972   if (!stabs.empty())
973     emitEndSourceStab();
974 }
975 
976 void SymtabSection::finalizeContents() {
977   auto addSymbol = [&](std::vector<SymtabEntry> &symbols, Symbol *sym) {
978     uint32_t strx = stringTableSection.addString(sym->getName());
979     symbols.push_back({sym, strx});
980   };
981 
982   std::function<void(Symbol *)> localSymbolsHandler;
983   switch (config->localSymbolsPresence) {
984   case SymtabPresence::All:
985     localSymbolsHandler = [&](Symbol *sym) { addSymbol(localSymbols, sym); };
986     break;
987   case SymtabPresence::None:
988     localSymbolsHandler = [&](Symbol *) { /* Do nothing*/ };
989     break;
990   case SymtabPresence::SelectivelyIncluded:
991     localSymbolsHandler = [&](Symbol *sym) {
992       if (config->localSymbolPatterns.match(sym->getName()))
993         addSymbol(localSymbols, sym);
994     };
995     break;
996   case SymtabPresence::SelectivelyExcluded:
997     localSymbolsHandler = [&](Symbol *sym) {
998       if (!config->localSymbolPatterns.match(sym->getName()))
999         addSymbol(localSymbols, sym);
1000     };
1001     break;
1002   }
1003 
1004   // Local symbols aren't in the SymbolTable, so we walk the list of object
1005   // files to gather them.
1006   // But if `-x` is set, then we don't need to. localSymbolsHandler() will do
1007   // the right thing regardless, but this check is a perf optimization because
1008   // iterating through all the input files and their symbols is expensive.
1009   if (config->localSymbolsPresence != SymtabPresence::None) {
1010     for (const InputFile *file : inputFiles) {
1011       if (auto *objFile = dyn_cast<ObjFile>(file)) {
1012         for (Symbol *sym : objFile->symbols) {
1013           if (auto *defined = dyn_cast_or_null<Defined>(sym)) {
1014             if (defined->isExternal() || !defined->isLive() ||
1015                 !defined->includeInSymtab)
1016               continue;
1017             localSymbolsHandler(sym);
1018           }
1019         }
1020       }
1021     }
1022   }
1023 
1024   // __dyld_private is a local symbol too. It's linker-created and doesn't
1025   // exist in any object file.
1026   if (Defined *dyldPrivate = in.stubHelper->dyldPrivate)
1027     localSymbolsHandler(dyldPrivate);
1028 
1029   for (Symbol *sym : symtab->getSymbols()) {
1030     if (!sym->isLive())
1031       continue;
1032     if (auto *defined = dyn_cast<Defined>(sym)) {
1033       if (!defined->includeInSymtab)
1034         continue;
1035       assert(defined->isExternal());
1036       if (defined->privateExtern)
1037         localSymbolsHandler(defined);
1038       else
1039         addSymbol(externalSymbols, defined);
1040     } else if (auto *dysym = dyn_cast<DylibSymbol>(sym)) {
1041       if (dysym->isReferenced())
1042         addSymbol(undefinedSymbols, sym);
1043     }
1044   }
1045 
1046   emitStabs();
1047   uint32_t symtabIndex = stabs.size();
1048   for (const SymtabEntry &entry :
1049        concat<SymtabEntry>(localSymbols, externalSymbols, undefinedSymbols)) {
1050     entry.sym->symtabIndex = symtabIndex++;
1051   }
1052 }
1053 
1054 uint32_t SymtabSection::getNumSymbols() const {
1055   return stabs.size() + localSymbols.size() + externalSymbols.size() +
1056          undefinedSymbols.size();
1057 }
1058 
1059 // This serves to hide (type-erase) the template parameter from SymtabSection.
1060 template <class LP> class SymtabSectionImpl final : public SymtabSection {
1061 public:
1062   SymtabSectionImpl(StringTableSection &stringTableSection)
1063       : SymtabSection(stringTableSection) {}
1064   uint64_t getRawSize() const override;
1065   void writeTo(uint8_t *buf) const override;
1066 };
1067 
1068 template <class LP> uint64_t SymtabSectionImpl<LP>::getRawSize() const {
1069   return getNumSymbols() * sizeof(typename LP::nlist);
1070 }
1071 
1072 template <class LP> void SymtabSectionImpl<LP>::writeTo(uint8_t *buf) const {
1073   auto *nList = reinterpret_cast<typename LP::nlist *>(buf);
1074   // Emit the stabs entries before the "real" symbols. We cannot emit them
1075   // after as that would render Symbol::symtabIndex inaccurate.
1076   for (const StabsEntry &entry : stabs) {
1077     nList->n_strx = entry.strx;
1078     nList->n_type = entry.type;
1079     nList->n_sect = entry.sect;
1080     nList->n_desc = entry.desc;
1081     nList->n_value = entry.value;
1082     ++nList;
1083   }
1084 
1085   for (const SymtabEntry &entry : concat<const SymtabEntry>(
1086            localSymbols, externalSymbols, undefinedSymbols)) {
1087     nList->n_strx = entry.strx;
1088     // TODO populate n_desc with more flags
1089     if (auto *defined = dyn_cast<Defined>(entry.sym)) {
1090       uint8_t scope = 0;
1091       if (defined->privateExtern) {
1092         // Private external -- dylib scoped symbol.
1093         // Promote to non-external at link time.
1094         scope = N_PEXT;
1095       } else if (defined->isExternal()) {
1096         // Normal global symbol.
1097         scope = N_EXT;
1098       } else {
1099         // TU-local symbol from localSymbols.
1100         scope = 0;
1101       }
1102 
1103       if (defined->isAbsolute()) {
1104         nList->n_type = scope | N_ABS;
1105         nList->n_sect = NO_SECT;
1106         nList->n_value = defined->value;
1107       } else {
1108         nList->n_type = scope | N_SECT;
1109         nList->n_sect = defined->isec->parent->index;
1110         // For the N_SECT symbol type, n_value is the address of the symbol
1111         nList->n_value = defined->getVA();
1112       }
1113       nList->n_desc |= defined->thumb ? N_ARM_THUMB_DEF : 0;
1114       nList->n_desc |= defined->isExternalWeakDef() ? N_WEAK_DEF : 0;
1115       nList->n_desc |=
1116           defined->referencedDynamically ? REFERENCED_DYNAMICALLY : 0;
1117     } else if (auto *dysym = dyn_cast<DylibSymbol>(entry.sym)) {
1118       uint16_t n_desc = nList->n_desc;
1119       int16_t ordinal = ordinalForDylibSymbol(*dysym);
1120       if (ordinal == BIND_SPECIAL_DYLIB_FLAT_LOOKUP)
1121         SET_LIBRARY_ORDINAL(n_desc, DYNAMIC_LOOKUP_ORDINAL);
1122       else if (ordinal == BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE)
1123         SET_LIBRARY_ORDINAL(n_desc, EXECUTABLE_ORDINAL);
1124       else {
1125         assert(ordinal > 0);
1126         SET_LIBRARY_ORDINAL(n_desc, static_cast<uint8_t>(ordinal));
1127       }
1128 
1129       nList->n_type = N_EXT;
1130       n_desc |= dysym->isWeakDef() ? N_WEAK_DEF : 0;
1131       n_desc |= dysym->isWeakRef() ? N_WEAK_REF : 0;
1132       nList->n_desc = n_desc;
1133     }
1134     ++nList;
1135   }
1136 }
1137 
1138 template <class LP>
1139 SymtabSection *
1140 macho::makeSymtabSection(StringTableSection &stringTableSection) {
1141   return make<SymtabSectionImpl<LP>>(stringTableSection);
1142 }
1143 
1144 IndirectSymtabSection::IndirectSymtabSection()
1145     : LinkEditSection(segment_names::linkEdit,
1146                       section_names::indirectSymbolTable) {}
1147 
1148 uint32_t IndirectSymtabSection::getNumSymbols() const {
1149   return in.got->getEntries().size() + in.tlvPointers->getEntries().size() +
1150          2 * in.stubs->getEntries().size();
1151 }
1152 
1153 bool IndirectSymtabSection::isNeeded() const {
1154   return in.got->isNeeded() || in.tlvPointers->isNeeded() ||
1155          in.stubs->isNeeded();
1156 }
1157 
1158 void IndirectSymtabSection::finalizeContents() {
1159   uint32_t off = 0;
1160   in.got->reserved1 = off;
1161   off += in.got->getEntries().size();
1162   in.tlvPointers->reserved1 = off;
1163   off += in.tlvPointers->getEntries().size();
1164   in.stubs->reserved1 = off;
1165   off += in.stubs->getEntries().size();
1166   in.lazyPointers->reserved1 = off;
1167 }
1168 
1169 static uint32_t indirectValue(const Symbol *sym) {
1170   if (sym->symtabIndex == UINT32_MAX)
1171     return INDIRECT_SYMBOL_LOCAL;
1172   if (auto *defined = dyn_cast<Defined>(sym))
1173     if (defined->privateExtern)
1174       return INDIRECT_SYMBOL_LOCAL;
1175   return sym->symtabIndex;
1176 }
1177 
1178 void IndirectSymtabSection::writeTo(uint8_t *buf) const {
1179   uint32_t off = 0;
1180   for (const Symbol *sym : in.got->getEntries()) {
1181     write32le(buf + off * sizeof(uint32_t), indirectValue(sym));
1182     ++off;
1183   }
1184   for (const Symbol *sym : in.tlvPointers->getEntries()) {
1185     write32le(buf + off * sizeof(uint32_t), indirectValue(sym));
1186     ++off;
1187   }
1188   for (const Symbol *sym : in.stubs->getEntries()) {
1189     write32le(buf + off * sizeof(uint32_t), indirectValue(sym));
1190     ++off;
1191   }
1192   // There is a 1:1 correspondence between stubs and LazyPointerSection
1193   // entries. But giving __stubs and __la_symbol_ptr the same reserved1
1194   // (the offset into the indirect symbol table) so that they both refer
1195   // to the same range of offsets confuses `strip`, so write the stubs
1196   // symbol table offsets a second time.
1197   for (const Symbol *sym : in.stubs->getEntries()) {
1198     write32le(buf + off * sizeof(uint32_t), indirectValue(sym));
1199     ++off;
1200   }
1201 }
1202 
1203 StringTableSection::StringTableSection()
1204     : LinkEditSection(segment_names::linkEdit, section_names::stringTable) {}
1205 
1206 uint32_t StringTableSection::addString(StringRef str) {
1207   uint32_t strx = size;
1208   strings.push_back(str); // TODO: consider deduplicating strings
1209   size += str.size() + 1; // account for null terminator
1210   return strx;
1211 }
1212 
1213 void StringTableSection::writeTo(uint8_t *buf) const {
1214   uint32_t off = 0;
1215   for (StringRef str : strings) {
1216     memcpy(buf + off, str.data(), str.size());
1217     off += str.size() + 1; // account for null terminator
1218   }
1219 }
1220 
1221 static_assert((CodeSignatureSection::blobHeadersSize % 8) == 0, "");
1222 static_assert((CodeSignatureSection::fixedHeadersSize % 8) == 0, "");
1223 
1224 CodeSignatureSection::CodeSignatureSection()
1225     : LinkEditSection(segment_names::linkEdit, section_names::codeSignature) {
1226   align = 16; // required by libstuff
1227   // FIXME: Consider using finalOutput instead of outputFile.
1228   fileName = config->outputFile;
1229   size_t slashIndex = fileName.rfind("/");
1230   if (slashIndex != std::string::npos)
1231     fileName = fileName.drop_front(slashIndex + 1);
1232 
1233   // NOTE: Any changes to these calculations should be repeated
1234   // in llvm-objcopy's MachOLayoutBuilder::layoutTail.
1235   allHeadersSize = alignTo<16>(fixedHeadersSize + fileName.size() + 1);
1236   fileNamePad = allHeadersSize - fixedHeadersSize - fileName.size();
1237 }
1238 
1239 uint32_t CodeSignatureSection::getBlockCount() const {
1240   return (fileOff + blockSize - 1) / blockSize;
1241 }
1242 
1243 uint64_t CodeSignatureSection::getRawSize() const {
1244   return allHeadersSize + getBlockCount() * hashSize;
1245 }
1246 
1247 void CodeSignatureSection::writeHashes(uint8_t *buf) const {
1248   // NOTE: Changes to this functionality should be repeated in llvm-objcopy's
1249   // MachOWriter::writeSignatureData.
1250   uint8_t *hashes = buf + fileOff + allHeadersSize;
1251   parallelFor(0, getBlockCount(), [&](size_t i) {
1252     sha256(buf + i * blockSize,
1253            std::min(static_cast<size_t>(fileOff - i * blockSize),
1254                     static_cast<size_t>(blockSize)),
1255            hashes + i * hashSize);
1256   });
1257 #if defined(__APPLE__)
1258   // This is macOS-specific work-around and makes no sense for any
1259   // other host OS. See https://openradar.appspot.com/FB8914231
1260   //
1261   // The macOS kernel maintains a signature-verification cache to
1262   // quickly validate applications at time of execve(2).  The trouble
1263   // is that for the kernel creates the cache entry at the time of the
1264   // mmap(2) call, before we have a chance to write either the code to
1265   // sign or the signature header+hashes.  The fix is to invalidate
1266   // all cached data associated with the output file, thus discarding
1267   // the bogus prematurely-cached signature.
1268   msync(buf, fileOff + getSize(), MS_INVALIDATE);
1269 #endif
1270 }
1271 
1272 void CodeSignatureSection::writeTo(uint8_t *buf) const {
1273   // NOTE: Changes to this functionality should be repeated in llvm-objcopy's
1274   // MachOWriter::writeSignatureData.
1275   uint32_t signatureSize = static_cast<uint32_t>(getSize());
1276   auto *superBlob = reinterpret_cast<CS_SuperBlob *>(buf);
1277   write32be(&superBlob->magic, CSMAGIC_EMBEDDED_SIGNATURE);
1278   write32be(&superBlob->length, signatureSize);
1279   write32be(&superBlob->count, 1);
1280   auto *blobIndex = reinterpret_cast<CS_BlobIndex *>(&superBlob[1]);
1281   write32be(&blobIndex->type, CSSLOT_CODEDIRECTORY);
1282   write32be(&blobIndex->offset, blobHeadersSize);
1283   auto *codeDirectory =
1284       reinterpret_cast<CS_CodeDirectory *>(buf + blobHeadersSize);
1285   write32be(&codeDirectory->magic, CSMAGIC_CODEDIRECTORY);
1286   write32be(&codeDirectory->length, signatureSize - blobHeadersSize);
1287   write32be(&codeDirectory->version, CS_SUPPORTSEXECSEG);
1288   write32be(&codeDirectory->flags, CS_ADHOC | CS_LINKER_SIGNED);
1289   write32be(&codeDirectory->hashOffset,
1290             sizeof(CS_CodeDirectory) + fileName.size() + fileNamePad);
1291   write32be(&codeDirectory->identOffset, sizeof(CS_CodeDirectory));
1292   codeDirectory->nSpecialSlots = 0;
1293   write32be(&codeDirectory->nCodeSlots, getBlockCount());
1294   write32be(&codeDirectory->codeLimit, fileOff);
1295   codeDirectory->hashSize = static_cast<uint8_t>(hashSize);
1296   codeDirectory->hashType = kSecCodeSignatureHashSHA256;
1297   codeDirectory->platform = 0;
1298   codeDirectory->pageSize = blockSizeShift;
1299   codeDirectory->spare2 = 0;
1300   codeDirectory->scatterOffset = 0;
1301   codeDirectory->teamOffset = 0;
1302   codeDirectory->spare3 = 0;
1303   codeDirectory->codeLimit64 = 0;
1304   OutputSegment *textSeg = getOrCreateOutputSegment(segment_names::text);
1305   write64be(&codeDirectory->execSegBase, textSeg->fileOff);
1306   write64be(&codeDirectory->execSegLimit, textSeg->fileSize);
1307   write64be(&codeDirectory->execSegFlags,
1308             config->outputType == MH_EXECUTE ? CS_EXECSEG_MAIN_BINARY : 0);
1309   auto *id = reinterpret_cast<char *>(&codeDirectory[1]);
1310   memcpy(id, fileName.begin(), fileName.size());
1311   memset(id + fileName.size(), 0, fileNamePad);
1312 }
1313 
1314 BitcodeBundleSection::BitcodeBundleSection()
1315     : SyntheticSection(segment_names::llvm, section_names::bitcodeBundle) {}
1316 
1317 class ErrorCodeWrapper {
1318 public:
1319   explicit ErrorCodeWrapper(std::error_code ec) : errorCode(ec.value()) {}
1320   explicit ErrorCodeWrapper(int ec) : errorCode(ec) {}
1321   operator int() const { return errorCode; }
1322 
1323 private:
1324   int errorCode;
1325 };
1326 
1327 #define CHECK_EC(exp)                                                          \
1328   do {                                                                         \
1329     ErrorCodeWrapper ec(exp);                                                  \
1330     if (ec)                                                                    \
1331       fatal(Twine("operation failed with error code ") + Twine(ec) + ": " +    \
1332             #exp);                                                             \
1333   } while (0);
1334 
1335 void BitcodeBundleSection::finalize() {
1336 #ifdef LLVM_HAVE_LIBXAR
1337   using namespace llvm::sys::fs;
1338   CHECK_EC(createTemporaryFile("bitcode-bundle", "xar", xarPath));
1339 
1340 #pragma clang diagnostic push
1341 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1342   xar_t xar(xar_open(xarPath.data(), O_RDWR));
1343 #pragma clang diagnostic pop
1344   if (!xar)
1345     fatal("failed to open XAR temporary file at " + xarPath);
1346   CHECK_EC(xar_opt_set(xar, XAR_OPT_COMPRESSION, XAR_OPT_VAL_NONE));
1347   // FIXME: add more data to XAR
1348   CHECK_EC(xar_close(xar));
1349 
1350   file_size(xarPath, xarSize);
1351 #endif // defined(LLVM_HAVE_LIBXAR)
1352 }
1353 
1354 void BitcodeBundleSection::writeTo(uint8_t *buf) const {
1355   using namespace llvm::sys::fs;
1356   file_t handle =
1357       CHECK(openNativeFile(xarPath, CD_OpenExisting, FA_Read, OF_None),
1358             "failed to open XAR file");
1359   std::error_code ec;
1360   mapped_file_region xarMap(handle, mapped_file_region::mapmode::readonly,
1361                             xarSize, 0, ec);
1362   if (ec)
1363     fatal("failed to map XAR file");
1364   memcpy(buf, xarMap.const_data(), xarSize);
1365 
1366   closeFile(handle);
1367   remove(xarPath);
1368 }
1369 
1370 CStringSection::CStringSection()
1371     : SyntheticSection(segment_names::text, section_names::cString) {
1372   flags = S_CSTRING_LITERALS;
1373 }
1374 
1375 void CStringSection::addInput(CStringInputSection *isec) {
1376   isec->parent = this;
1377   inputs.push_back(isec);
1378   if (isec->align > align)
1379     align = isec->align;
1380 }
1381 
1382 void CStringSection::writeTo(uint8_t *buf) const {
1383   for (const CStringInputSection *isec : inputs) {
1384     for (size_t i = 0, e = isec->pieces.size(); i != e; ++i) {
1385       if (!isec->pieces[i].live)
1386         continue;
1387       StringRef string = isec->getStringRef(i);
1388       memcpy(buf + isec->pieces[i].outSecOff, string.data(), string.size());
1389     }
1390   }
1391 }
1392 
1393 void CStringSection::finalizeContents() {
1394   uint64_t offset = 0;
1395   for (CStringInputSection *isec : inputs) {
1396     for (size_t i = 0, e = isec->pieces.size(); i != e; ++i) {
1397       if (!isec->pieces[i].live)
1398         continue;
1399       // See comment above DeduplicatedCStringSection for how alignment is
1400       // handled.
1401       uint32_t pieceAlign =
1402           1 << countTrailingZeros(isec->align | isec->pieces[i].inSecOff);
1403       offset = alignTo(offset, pieceAlign);
1404       isec->pieces[i].outSecOff = offset;
1405       isec->isFinal = true;
1406       StringRef string = isec->getStringRef(i);
1407       offset += string.size();
1408     }
1409   }
1410   size = offset;
1411 }
1412 
1413 // Mergeable cstring literals are found under the __TEXT,__cstring section. In
1414 // contrast to ELF, which puts strings that need different alignments into
1415 // different sections, clang's Mach-O backend puts them all in one section.
1416 // Strings that need to be aligned have the .p2align directive emitted before
1417 // them, which simply translates into zero padding in the object file. In other
1418 // words, we have to infer the desired alignment of these cstrings from their
1419 // addresses.
1420 //
1421 // We differ slightly from ld64 in how we've chosen to align these cstrings.
1422 // Both LLD and ld64 preserve the number of trailing zeros in each cstring's
1423 // address in the input object files. When deduplicating identical cstrings,
1424 // both linkers pick the cstring whose address has more trailing zeros, and
1425 // preserve the alignment of that address in the final binary. However, ld64
1426 // goes a step further and also preserves the offset of the cstring from the
1427 // last section-aligned address.  I.e. if a cstring is at offset 18 in the
1428 // input, with a section alignment of 16, then both LLD and ld64 will ensure the
1429 // final address is 2-byte aligned (since 18 == 16 + 2). But ld64 will also
1430 // ensure that the final address is of the form 16 * k + 2 for some k.
1431 //
1432 // Note that ld64's heuristic means that a dedup'ed cstring's final address is
1433 // dependent on the order of the input object files. E.g. if in addition to the
1434 // cstring at offset 18 above, we have a duplicate one in another file with a
1435 // `.cstring` section alignment of 2 and an offset of zero, then ld64 will pick
1436 // the cstring from the object file earlier on the command line (since both have
1437 // the same number of trailing zeros in their address). So the final cstring may
1438 // either be at some address `16 * k + 2` or at some address `2 * k`.
1439 //
1440 // I've opted not to follow this behavior primarily for implementation
1441 // simplicity, and secondarily to save a few more bytes. It's not clear to me
1442 // that preserving the section alignment + offset is ever necessary, and there
1443 // are many cases that are clearly redundant. In particular, if an x86_64 object
1444 // file contains some strings that are accessed via SIMD instructions, then the
1445 // .cstring section in the object file will be 16-byte-aligned (since SIMD
1446 // requires its operand addresses to be 16-byte aligned). However, there will
1447 // typically also be other cstrings in the same file that aren't used via SIMD
1448 // and don't need this alignment. They will be emitted at some arbitrary address
1449 // `A`, but ld64 will treat them as being 16-byte aligned with an offset of `16
1450 // % A`.
1451 void DeduplicatedCStringSection::finalizeContents() {
1452   // Find the largest alignment required for each string.
1453   for (const CStringInputSection *isec : inputs) {
1454     for (size_t i = 0, e = isec->pieces.size(); i != e; ++i) {
1455       const StringPiece &piece = isec->pieces[i];
1456       if (!piece.live)
1457         continue;
1458       auto s = isec->getCachedHashStringRef(i);
1459       assert(isec->align != 0);
1460       uint8_t trailingZeros = countTrailingZeros(isec->align | piece.inSecOff);
1461       auto it = stringOffsetMap.insert(
1462           std::make_pair(s, StringOffset(trailingZeros)));
1463       if (!it.second && it.first->second.trailingZeros < trailingZeros)
1464         it.first->second.trailingZeros = trailingZeros;
1465     }
1466   }
1467 
1468   // Assign an offset for each string and save it to the corresponding
1469   // StringPieces for easy access.
1470   for (CStringInputSection *isec : inputs) {
1471     for (size_t i = 0, e = isec->pieces.size(); i != e; ++i) {
1472       if (!isec->pieces[i].live)
1473         continue;
1474       auto s = isec->getCachedHashStringRef(i);
1475       auto it = stringOffsetMap.find(s);
1476       assert(it != stringOffsetMap.end());
1477       StringOffset &offsetInfo = it->second;
1478       if (offsetInfo.outSecOff == UINT64_MAX) {
1479         offsetInfo.outSecOff = alignTo(size, 1ULL << offsetInfo.trailingZeros);
1480         size = offsetInfo.outSecOff + s.size();
1481       }
1482       isec->pieces[i].outSecOff = offsetInfo.outSecOff;
1483     }
1484     isec->isFinal = true;
1485   }
1486 }
1487 
1488 void DeduplicatedCStringSection::writeTo(uint8_t *buf) const {
1489   for (const auto &p : stringOffsetMap) {
1490     StringRef data = p.first.val();
1491     uint64_t off = p.second.outSecOff;
1492     if (!data.empty())
1493       memcpy(buf + off, data.data(), data.size());
1494   }
1495 }
1496 
1497 // This section is actually emitted as __TEXT,__const by ld64, but clang may
1498 // emit input sections of that name, and LLD doesn't currently support mixing
1499 // synthetic and concat-type OutputSections. To work around this, I've given
1500 // our merged-literals section a different name.
1501 WordLiteralSection::WordLiteralSection()
1502     : SyntheticSection(segment_names::text, section_names::literals) {
1503   align = 16;
1504 }
1505 
1506 void WordLiteralSection::addInput(WordLiteralInputSection *isec) {
1507   isec->parent = this;
1508   inputs.push_back(isec);
1509 }
1510 
1511 void WordLiteralSection::finalizeContents() {
1512   for (WordLiteralInputSection *isec : inputs) {
1513     // We do all processing of the InputSection here, so it will be effectively
1514     // finalized.
1515     isec->isFinal = true;
1516     const uint8_t *buf = isec->data.data();
1517     switch (sectionType(isec->getFlags())) {
1518     case S_4BYTE_LITERALS: {
1519       for (size_t off = 0, e = isec->data.size(); off < e; off += 4) {
1520         if (!isec->isLive(off))
1521           continue;
1522         uint32_t value = *reinterpret_cast<const uint32_t *>(buf + off);
1523         literal4Map.emplace(value, literal4Map.size());
1524       }
1525       break;
1526     }
1527     case S_8BYTE_LITERALS: {
1528       for (size_t off = 0, e = isec->data.size(); off < e; off += 8) {
1529         if (!isec->isLive(off))
1530           continue;
1531         uint64_t value = *reinterpret_cast<const uint64_t *>(buf + off);
1532         literal8Map.emplace(value, literal8Map.size());
1533       }
1534       break;
1535     }
1536     case S_16BYTE_LITERALS: {
1537       for (size_t off = 0, e = isec->data.size(); off < e; off += 16) {
1538         if (!isec->isLive(off))
1539           continue;
1540         UInt128 value = *reinterpret_cast<const UInt128 *>(buf + off);
1541         literal16Map.emplace(value, literal16Map.size());
1542       }
1543       break;
1544     }
1545     default:
1546       llvm_unreachable("invalid literal section type");
1547     }
1548   }
1549 }
1550 
1551 void WordLiteralSection::writeTo(uint8_t *buf) const {
1552   // Note that we don't attempt to do any endianness conversion in addInput(),
1553   // so we don't do it here either -- just write out the original value,
1554   // byte-for-byte.
1555   for (const auto &p : literal16Map)
1556     memcpy(buf + p.second * 16, &p.first, 16);
1557   buf += literal16Map.size() * 16;
1558 
1559   for (const auto &p : literal8Map)
1560     memcpy(buf + p.second * 8, &p.first, 8);
1561   buf += literal8Map.size() * 8;
1562 
1563   for (const auto &p : literal4Map)
1564     memcpy(buf + p.second * 4, &p.first, 4);
1565 }
1566 
1567 void macho::createSyntheticSymbols() {
1568   auto addHeaderSymbol = [](const char *name) {
1569     symtab->addSynthetic(name, in.header->isec, /*value=*/0,
1570                          /*isPrivateExtern=*/true, /*includeInSymtab=*/false,
1571                          /*referencedDynamically=*/false);
1572   };
1573 
1574   switch (config->outputType) {
1575     // FIXME: Assign the right address value for these symbols
1576     // (rather than 0). But we need to do that after assignAddresses().
1577   case MH_EXECUTE:
1578     // If linking PIE, __mh_execute_header is a defined symbol in
1579     //  __TEXT, __text)
1580     // Otherwise, it's an absolute symbol.
1581     if (config->isPic)
1582       symtab->addSynthetic("__mh_execute_header", in.header->isec, /*value=*/0,
1583                            /*isPrivateExtern=*/false, /*includeInSymtab=*/true,
1584                            /*referencedDynamically=*/true);
1585     else
1586       symtab->addSynthetic("__mh_execute_header", /*isec=*/nullptr, /*value=*/0,
1587                            /*isPrivateExtern=*/false, /*includeInSymtab=*/true,
1588                            /*referencedDynamically=*/true);
1589     break;
1590 
1591     // The following symbols are N_SECT symbols, even though the header is not
1592     // part of any section and that they are private to the bundle/dylib/object
1593     // they are part of.
1594   case MH_BUNDLE:
1595     addHeaderSymbol("__mh_bundle_header");
1596     break;
1597   case MH_DYLIB:
1598     addHeaderSymbol("__mh_dylib_header");
1599     break;
1600   case MH_DYLINKER:
1601     addHeaderSymbol("__mh_dylinker_header");
1602     break;
1603   case MH_OBJECT:
1604     addHeaderSymbol("__mh_object_header");
1605     break;
1606   default:
1607     llvm_unreachable("unexpected outputType");
1608     break;
1609   }
1610 
1611   // The Itanium C++ ABI requires dylibs to pass a pointer to __cxa_atexit
1612   // which does e.g. cleanup of static global variables. The ABI document
1613   // says that the pointer can point to any address in one of the dylib's
1614   // segments, but in practice ld64 seems to set it to point to the header,
1615   // so that's what's implemented here.
1616   addHeaderSymbol("___dso_handle");
1617 }
1618 
1619 template SymtabSection *macho::makeSymtabSection<LP64>(StringTableSection &);
1620 template SymtabSection *macho::makeSymtabSection<ILP32>(StringTableSection &);
1621