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