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