[LLVM] Fix Maintainers.md formatting (NFC)
[llvm-project.git] / lld / MachO / SyntheticSections.cpp
blobeee87b3a6cb4de623cfda38e79de021f1062f3cd
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 //===----------------------------------------------------------------------===//
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 "ObjC.h"
16 #include "OutputSegment.h"
17 #include "SymbolTable.h"
18 #include "Symbols.h"
20 #include "lld/Common/CommonLinkerContext.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/Parallel.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/xxhash.h"
30 #if defined(__APPLE__)
31 #include <sys/mman.h>
33 #define COMMON_DIGEST_FOR_OPENSSL
34 #include <CommonCrypto/CommonDigest.h>
35 #else
36 #include "llvm/Support/SHA256.h"
37 #endif
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;
46 // Reads `len` bytes at data and writes the 32-byte SHA256 checksum to `output`.
47 static void sha256(const uint8_t *data, size_t len, uint8_t *output) {
48 #if defined(__APPLE__)
49 // FIXME: Make LLVM's SHA256 faster and use it unconditionally. See PR56121
50 // for some notes on this.
51 CC_SHA256(data, len, output);
52 #else
53 ArrayRef<uint8_t> block(data, len);
54 std::array<uint8_t, 32> hash = SHA256::hash(block);
55 static_assert(hash.size() == CodeSignatureSection::hashSize);
56 memcpy(output, hash.data(), hash.size());
57 #endif
60 InStruct macho::in;
61 std::vector<SyntheticSection *> macho::syntheticSections;
63 SyntheticSection::SyntheticSection(const char *segname, const char *name)
64 : OutputSection(SyntheticKind, name) {
65 std::tie(this->segname, this->name) = maybeRenameSection({segname, name});
66 isec = makeSyntheticInputSection(segname, name);
67 isec->parent = this;
68 syntheticSections.push_back(this);
71 // dyld3's MachOLoaded::getSlide() assumes that the __TEXT segment starts
72 // from the beginning of the file (i.e. the header).
73 MachHeaderSection::MachHeaderSection()
74 : SyntheticSection(segment_names::text, section_names::header) {
75 // XXX: This is a hack. (See D97007)
76 // Setting the index to 1 to pretend that this section is the text
77 // section.
78 index = 1;
79 isec->isFinal = true;
82 void MachHeaderSection::addLoadCommand(LoadCommand *lc) {
83 loadCommands.push_back(lc);
84 sizeOfCmds += lc->getSize();
87 uint64_t MachHeaderSection::getSize() const {
88 uint64_t size = target->headerSize + sizeOfCmds + config->headerPad;
89 // If we are emitting an encryptable binary, our load commands must have a
90 // separate (non-encrypted) page to themselves.
91 if (config->emitEncryptionInfo)
92 size = alignToPowerOf2(size, target->getPageSize());
93 return size;
96 static uint32_t cpuSubtype() {
97 uint32_t subtype = target->cpuSubtype;
99 if (config->outputType == MH_EXECUTE && !config->staticLink &&
100 target->cpuSubtype == CPU_SUBTYPE_X86_64_ALL &&
101 config->platform() == PLATFORM_MACOS &&
102 config->platformInfo.target.MinDeployment >= VersionTuple(10, 5))
103 subtype |= CPU_SUBTYPE_LIB64;
105 return subtype;
108 static bool hasWeakBinding() {
109 return config->emitChainedFixups ? in.chainedFixups->hasWeakBinding()
110 : in.weakBinding->hasEntry();
113 static bool hasNonWeakDefinition() {
114 return config->emitChainedFixups ? in.chainedFixups->hasNonWeakDefinition()
115 : in.weakBinding->hasNonWeakDefinition();
118 void MachHeaderSection::writeTo(uint8_t *buf) const {
119 auto *hdr = reinterpret_cast<mach_header *>(buf);
120 hdr->magic = target->magic;
121 hdr->cputype = target->cpuType;
122 hdr->cpusubtype = cpuSubtype();
123 hdr->filetype = config->outputType;
124 hdr->ncmds = loadCommands.size();
125 hdr->sizeofcmds = sizeOfCmds;
126 hdr->flags = MH_DYLDLINK;
128 if (config->namespaceKind == NamespaceKind::twolevel)
129 hdr->flags |= MH_NOUNDEFS | MH_TWOLEVEL;
131 if (config->outputType == MH_DYLIB && !config->hasReexports)
132 hdr->flags |= MH_NO_REEXPORTED_DYLIBS;
134 if (config->markDeadStrippableDylib)
135 hdr->flags |= MH_DEAD_STRIPPABLE_DYLIB;
137 if (config->outputType == MH_EXECUTE && config->isPic)
138 hdr->flags |= MH_PIE;
140 if (config->outputType == MH_DYLIB && config->applicationExtension)
141 hdr->flags |= MH_APP_EXTENSION_SAFE;
143 if (in.exports->hasWeakSymbol || hasNonWeakDefinition())
144 hdr->flags |= MH_WEAK_DEFINES;
146 if (in.exports->hasWeakSymbol || hasWeakBinding())
147 hdr->flags |= MH_BINDS_TO_WEAK;
149 for (const OutputSegment *seg : outputSegments) {
150 for (const OutputSection *osec : seg->getSections()) {
151 if (isThreadLocalVariables(osec->flags)) {
152 hdr->flags |= MH_HAS_TLV_DESCRIPTORS;
153 break;
158 uint8_t *p = reinterpret_cast<uint8_t *>(hdr) + target->headerSize;
159 for (const LoadCommand *lc : loadCommands) {
160 lc->writeTo(p);
161 p += lc->getSize();
165 PageZeroSection::PageZeroSection()
166 : SyntheticSection(segment_names::pageZero, section_names::pageZero) {}
168 RebaseSection::RebaseSection()
169 : LinkEditSection(segment_names::linkEdit, section_names::rebase) {}
171 namespace {
172 struct RebaseState {
173 uint64_t sequenceLength;
174 uint64_t skipLength;
176 } // namespace
178 static void emitIncrement(uint64_t incr, raw_svector_ostream &os) {
179 assert(incr != 0);
181 if ((incr >> target->p2WordSize) <= REBASE_IMMEDIATE_MASK &&
182 (incr % target->wordSize) == 0) {
183 os << static_cast<uint8_t>(REBASE_OPCODE_ADD_ADDR_IMM_SCALED |
184 (incr >> target->p2WordSize));
185 } else {
186 os << static_cast<uint8_t>(REBASE_OPCODE_ADD_ADDR_ULEB);
187 encodeULEB128(incr, os);
191 static void flushRebase(const RebaseState &state, raw_svector_ostream &os) {
192 assert(state.sequenceLength > 0);
194 if (state.skipLength == target->wordSize) {
195 if (state.sequenceLength <= REBASE_IMMEDIATE_MASK) {
196 os << static_cast<uint8_t>(REBASE_OPCODE_DO_REBASE_IMM_TIMES |
197 state.sequenceLength);
198 } else {
199 os << static_cast<uint8_t>(REBASE_OPCODE_DO_REBASE_ULEB_TIMES);
200 encodeULEB128(state.sequenceLength, os);
202 } else if (state.sequenceLength == 1) {
203 os << static_cast<uint8_t>(REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB);
204 encodeULEB128(state.skipLength - target->wordSize, os);
205 } else {
206 os << static_cast<uint8_t>(
207 REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB);
208 encodeULEB128(state.sequenceLength, os);
209 encodeULEB128(state.skipLength - target->wordSize, os);
213 // Rebases are communicated to dyld using a bytecode, whose opcodes cause the
214 // memory location at a specific address to be rebased and/or the address to be
215 // incremented.
217 // Opcode REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB is the most generic
218 // one, encoding a series of evenly spaced addresses. This algorithm works by
219 // splitting up the sorted list of addresses into such chunks. If the locations
220 // are consecutive or the sequence consists of a single location, flushRebase
221 // will use a smaller, more specialized encoding.
222 static void encodeRebases(const OutputSegment *seg,
223 MutableArrayRef<Location> locations,
224 raw_svector_ostream &os) {
225 // dyld operates on segments. Translate section offsets into segment offsets.
226 for (Location &loc : locations)
227 loc.offset =
228 loc.isec->parent->getSegmentOffset() + loc.isec->getOffset(loc.offset);
229 // The algorithm assumes that locations are unique.
230 Location *end =
231 llvm::unique(locations, [](const Location &a, const Location &b) {
232 return a.offset == b.offset;
234 size_t count = end - locations.begin();
236 os << static_cast<uint8_t>(REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB |
237 seg->index);
238 assert(!locations.empty());
239 uint64_t offset = locations[0].offset;
240 encodeULEB128(offset, os);
242 RebaseState state{1, target->wordSize};
244 for (size_t i = 1; i < count; ++i) {
245 offset = locations[i].offset;
247 uint64_t skip = offset - locations[i - 1].offset;
248 assert(skip != 0 && "duplicate locations should have been weeded out");
250 if (skip == state.skipLength) {
251 ++state.sequenceLength;
252 } else if (state.sequenceLength == 1) {
253 ++state.sequenceLength;
254 state.skipLength = skip;
255 } else if (skip < state.skipLength) {
256 // The address is lower than what the rebase pointer would be if the last
257 // location would be part of a sequence. We start a new sequence from the
258 // previous location.
259 --state.sequenceLength;
260 flushRebase(state, os);
262 state.sequenceLength = 2;
263 state.skipLength = skip;
264 } else {
265 // The address is at some positive offset from the rebase pointer. We
266 // start a new sequence which begins with the current location.
267 flushRebase(state, os);
268 emitIncrement(skip - state.skipLength, os);
269 state.sequenceLength = 1;
270 state.skipLength = target->wordSize;
273 flushRebase(state, os);
276 void RebaseSection::finalizeContents() {
277 if (locations.empty())
278 return;
280 raw_svector_ostream os{contents};
281 os << static_cast<uint8_t>(REBASE_OPCODE_SET_TYPE_IMM | REBASE_TYPE_POINTER);
283 llvm::sort(locations, [](const Location &a, const Location &b) {
284 return a.isec->getVA(a.offset) < b.isec->getVA(b.offset);
287 for (size_t i = 0, count = locations.size(); i < count;) {
288 const OutputSegment *seg = locations[i].isec->parent->parent;
289 size_t j = i + 1;
290 while (j < count && locations[j].isec->parent->parent == seg)
291 ++j;
292 encodeRebases(seg, {locations.data() + i, locations.data() + j}, os);
293 i = j;
295 os << static_cast<uint8_t>(REBASE_OPCODE_DONE);
298 void RebaseSection::writeTo(uint8_t *buf) const {
299 memcpy(buf, contents.data(), contents.size());
302 NonLazyPointerSectionBase::NonLazyPointerSectionBase(const char *segname,
303 const char *name)
304 : SyntheticSection(segname, name) {
305 align = target->wordSize;
308 void macho::addNonLazyBindingEntries(const Symbol *sym,
309 const InputSection *isec, uint64_t offset,
310 int64_t addend) {
311 if (config->emitChainedFixups) {
312 if (needsBinding(sym))
313 in.chainedFixups->addBinding(sym, isec, offset, addend);
314 else if (isa<Defined>(sym))
315 in.chainedFixups->addRebase(isec, offset);
316 else
317 llvm_unreachable("cannot bind to an undefined symbol");
318 return;
321 if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) {
322 in.binding->addEntry(dysym, isec, offset, addend);
323 if (dysym->isWeakDef())
324 in.weakBinding->addEntry(sym, isec, offset, addend);
325 } else if (const auto *defined = dyn_cast<Defined>(sym)) {
326 in.rebase->addEntry(isec, offset);
327 if (defined->isExternalWeakDef())
328 in.weakBinding->addEntry(sym, isec, offset, addend);
329 else if (defined->interposable)
330 in.binding->addEntry(sym, isec, offset, addend);
331 } else {
332 // Undefined symbols are filtered out in scanRelocations(); we should never
333 // get here
334 llvm_unreachable("cannot bind to an undefined symbol");
338 void NonLazyPointerSectionBase::addEntry(Symbol *sym) {
339 if (entries.insert(sym)) {
340 assert(!sym->isInGot());
341 sym->gotIndex = entries.size() - 1;
343 addNonLazyBindingEntries(sym, isec, sym->gotIndex * target->wordSize);
347 void macho::writeChainedRebase(uint8_t *buf, uint64_t targetVA) {
348 assert(config->emitChainedFixups);
349 assert(target->wordSize == 8 && "Only 64-bit platforms are supported");
350 auto *rebase = reinterpret_cast<dyld_chained_ptr_64_rebase *>(buf);
351 rebase->target = targetVA & 0xf'ffff'ffff;
352 rebase->high8 = (targetVA >> 56);
353 rebase->reserved = 0;
354 rebase->next = 0;
355 rebase->bind = 0;
357 // The fixup format places a 64 GiB limit on the output's size.
358 // Should we handle this gracefully?
359 uint64_t encodedVA = rebase->target | ((uint64_t)rebase->high8 << 56);
360 if (encodedVA != targetVA)
361 error("rebase target address 0x" + Twine::utohexstr(targetVA) +
362 " does not fit into chained fixup. Re-link with -no_fixup_chains");
365 static void writeChainedBind(uint8_t *buf, const Symbol *sym, int64_t addend) {
366 assert(config->emitChainedFixups);
367 assert(target->wordSize == 8 && "Only 64-bit platforms are supported");
368 auto *bind = reinterpret_cast<dyld_chained_ptr_64_bind *>(buf);
369 auto [ordinal, inlineAddend] = in.chainedFixups->getBinding(sym, addend);
370 bind->ordinal = ordinal;
371 bind->addend = inlineAddend;
372 bind->reserved = 0;
373 bind->next = 0;
374 bind->bind = 1;
377 void macho::writeChainedFixup(uint8_t *buf, const Symbol *sym, int64_t addend) {
378 if (needsBinding(sym))
379 writeChainedBind(buf, sym, addend);
380 else
381 writeChainedRebase(buf, sym->getVA() + addend);
384 void NonLazyPointerSectionBase::writeTo(uint8_t *buf) const {
385 if (config->emitChainedFixups) {
386 for (const auto &[i, entry] : llvm::enumerate(entries))
387 writeChainedFixup(&buf[i * target->wordSize], entry, 0);
388 } else {
389 for (const auto &[i, entry] : llvm::enumerate(entries))
390 if (auto *defined = dyn_cast<Defined>(entry))
391 write64le(&buf[i * target->wordSize], defined->getVA());
395 GotSection::GotSection()
396 : NonLazyPointerSectionBase(segment_names::data, section_names::got) {
397 flags = S_NON_LAZY_SYMBOL_POINTERS;
400 TlvPointerSection::TlvPointerSection()
401 : NonLazyPointerSectionBase(segment_names::data,
402 section_names::threadPtrs) {
403 flags = S_THREAD_LOCAL_VARIABLE_POINTERS;
406 BindingSection::BindingSection()
407 : LinkEditSection(segment_names::linkEdit, section_names::binding) {}
409 namespace {
410 struct Binding {
411 OutputSegment *segment = nullptr;
412 uint64_t offset = 0;
413 int64_t addend = 0;
415 struct BindIR {
416 // Default value of 0xF0 is not valid opcode and should make the program
417 // scream instead of accidentally writing "valid" values.
418 uint8_t opcode = 0xF0;
419 uint64_t data = 0;
420 uint64_t consecutiveCount = 0;
422 } // namespace
424 // Encode a sequence of opcodes that tell dyld to write the address of symbol +
425 // addend at osec->addr + outSecOff.
427 // The bind opcode "interpreter" remembers the values of each binding field, so
428 // we only need to encode the differences between bindings. Hence the use of
429 // lastBinding.
430 static void encodeBinding(const OutputSection *osec, uint64_t outSecOff,
431 int64_t addend, Binding &lastBinding,
432 std::vector<BindIR> &opcodes) {
433 OutputSegment *seg = osec->parent;
434 uint64_t offset = osec->getSegmentOffset() + outSecOff;
435 if (lastBinding.segment != seg) {
436 opcodes.push_back(
437 {static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB |
438 seg->index),
439 offset});
440 lastBinding.segment = seg;
441 lastBinding.offset = offset;
442 } else if (lastBinding.offset != offset) {
443 opcodes.push_back({BIND_OPCODE_ADD_ADDR_ULEB, offset - lastBinding.offset});
444 lastBinding.offset = offset;
447 if (lastBinding.addend != addend) {
448 opcodes.push_back(
449 {BIND_OPCODE_SET_ADDEND_SLEB, static_cast<uint64_t>(addend)});
450 lastBinding.addend = addend;
453 opcodes.push_back({BIND_OPCODE_DO_BIND, 0});
454 // DO_BIND causes dyld to both perform the binding and increment the offset
455 lastBinding.offset += target->wordSize;
458 static void optimizeOpcodes(std::vector<BindIR> &opcodes) {
459 // Pass 1: Combine bind/add pairs
460 size_t i;
461 int pWrite = 0;
462 for (i = 1; i < opcodes.size(); ++i, ++pWrite) {
463 if ((opcodes[i].opcode == BIND_OPCODE_ADD_ADDR_ULEB) &&
464 (opcodes[i - 1].opcode == BIND_OPCODE_DO_BIND)) {
465 opcodes[pWrite].opcode = BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB;
466 opcodes[pWrite].data = opcodes[i].data;
467 ++i;
468 } else {
469 opcodes[pWrite] = opcodes[i - 1];
472 if (i == opcodes.size())
473 opcodes[pWrite] = opcodes[i - 1];
474 opcodes.resize(pWrite + 1);
476 // Pass 2: Compress two or more bind_add opcodes
477 pWrite = 0;
478 for (i = 1; i < opcodes.size(); ++i, ++pWrite) {
479 if ((opcodes[i].opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) &&
480 (opcodes[i - 1].opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) &&
481 (opcodes[i].data == opcodes[i - 1].data)) {
482 opcodes[pWrite].opcode = BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB;
483 opcodes[pWrite].consecutiveCount = 2;
484 opcodes[pWrite].data = opcodes[i].data;
485 ++i;
486 while (i < opcodes.size() &&
487 (opcodes[i].opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) &&
488 (opcodes[i].data == opcodes[i - 1].data)) {
489 opcodes[pWrite].consecutiveCount++;
490 ++i;
492 } else {
493 opcodes[pWrite] = opcodes[i - 1];
496 if (i == opcodes.size())
497 opcodes[pWrite] = opcodes[i - 1];
498 opcodes.resize(pWrite + 1);
500 // Pass 3: Use immediate encodings
501 // Every binding is the size of one pointer. If the next binding is a
502 // multiple of wordSize away that is within BIND_IMMEDIATE_MASK, the
503 // opcode can be scaled by wordSize into a single byte and dyld will
504 // expand it to the correct address.
505 for (auto &p : opcodes) {
506 // It's unclear why the check needs to be less than BIND_IMMEDIATE_MASK,
507 // but ld64 currently does this. This could be a potential bug, but
508 // for now, perform the same behavior to prevent mysterious bugs.
509 if ((p.opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) &&
510 ((p.data / target->wordSize) < BIND_IMMEDIATE_MASK) &&
511 ((p.data % target->wordSize) == 0)) {
512 p.opcode = BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED;
513 p.data /= target->wordSize;
518 static void flushOpcodes(const BindIR &op, raw_svector_ostream &os) {
519 uint8_t opcode = op.opcode & BIND_OPCODE_MASK;
520 switch (opcode) {
521 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
522 case BIND_OPCODE_ADD_ADDR_ULEB:
523 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
524 os << op.opcode;
525 encodeULEB128(op.data, os);
526 break;
527 case BIND_OPCODE_SET_ADDEND_SLEB:
528 os << op.opcode;
529 encodeSLEB128(static_cast<int64_t>(op.data), os);
530 break;
531 case BIND_OPCODE_DO_BIND:
532 os << op.opcode;
533 break;
534 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
535 os << op.opcode;
536 encodeULEB128(op.consecutiveCount, os);
537 encodeULEB128(op.data, os);
538 break;
539 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
540 os << static_cast<uint8_t>(op.opcode | op.data);
541 break;
542 default:
543 llvm_unreachable("cannot bind to an unrecognized symbol");
547 static bool needsWeakBind(const Symbol &sym) {
548 if (auto *dysym = dyn_cast<DylibSymbol>(&sym))
549 return dysym->isWeakDef();
550 if (auto *defined = dyn_cast<Defined>(&sym))
551 return defined->isExternalWeakDef();
552 return false;
555 // Non-weak bindings need to have their dylib ordinal encoded as well.
556 static int16_t ordinalForDylibSymbol(const DylibSymbol &dysym) {
557 if (config->namespaceKind == NamespaceKind::flat || dysym.isDynamicLookup())
558 return static_cast<int16_t>(BIND_SPECIAL_DYLIB_FLAT_LOOKUP);
559 assert(dysym.getFile()->isReferenced());
560 return dysym.getFile()->ordinal;
563 static int16_t ordinalForSymbol(const Symbol &sym) {
564 if (config->emitChainedFixups && needsWeakBind(sym))
565 return BIND_SPECIAL_DYLIB_WEAK_LOOKUP;
566 if (const auto *dysym = dyn_cast<DylibSymbol>(&sym))
567 return ordinalForDylibSymbol(*dysym);
568 assert(cast<Defined>(&sym)->interposable);
569 return BIND_SPECIAL_DYLIB_FLAT_LOOKUP;
572 static void encodeDylibOrdinal(int16_t ordinal, raw_svector_ostream &os) {
573 if (ordinal <= 0) {
574 os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM |
575 (ordinal & BIND_IMMEDIATE_MASK));
576 } else if (ordinal <= BIND_IMMEDIATE_MASK) {
577 os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | ordinal);
578 } else {
579 os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB);
580 encodeULEB128(ordinal, os);
584 static void encodeWeakOverride(const Defined *defined,
585 raw_svector_ostream &os) {
586 os << static_cast<uint8_t>(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM |
587 BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
588 << defined->getName() << '\0';
591 // Organize the bindings so we can encoded them with fewer opcodes.
593 // First, all bindings for a given symbol should be grouped together.
594 // BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM is the largest opcode (since it
595 // has an associated symbol string), so we only want to emit it once per symbol.
597 // Within each group, we sort the bindings by address. Since bindings are
598 // delta-encoded, sorting them allows for a more compact result. Note that
599 // sorting by address alone ensures that bindings for the same segment / section
600 // are located together, minimizing the number of times we have to emit
601 // BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB.
603 // Finally, we sort the symbols by the address of their first binding, again
604 // to facilitate the delta-encoding process.
605 template <class Sym>
606 std::vector<std::pair<const Sym *, std::vector<BindingEntry>>>
607 sortBindings(const BindingsMap<const Sym *> &bindingsMap) {
608 std::vector<std::pair<const Sym *, std::vector<BindingEntry>>> bindingsVec(
609 bindingsMap.begin(), bindingsMap.end());
610 for (auto &p : bindingsVec) {
611 std::vector<BindingEntry> &bindings = p.second;
612 llvm::sort(bindings, [](const BindingEntry &a, const BindingEntry &b) {
613 return a.target.getVA() < b.target.getVA();
616 llvm::sort(bindingsVec, [](const auto &a, const auto &b) {
617 return a.second[0].target.getVA() < b.second[0].target.getVA();
619 return bindingsVec;
622 // Emit bind opcodes, which are a stream of byte-sized opcodes that dyld
623 // interprets to update a record with the following fields:
624 // * segment index (of the segment to write the symbol addresses to, typically
625 // the __DATA_CONST segment which contains the GOT)
626 // * offset within the segment, indicating the next location to write a binding
627 // * symbol type
628 // * symbol library ordinal (the index of its library's LC_LOAD_DYLIB command)
629 // * symbol name
630 // * addend
631 // When dyld sees BIND_OPCODE_DO_BIND, it uses the current record state to bind
632 // a symbol in the GOT, and increments the segment offset to point to the next
633 // entry. It does *not* clear the record state after doing the bind, so
634 // subsequent opcodes only need to encode the differences between bindings.
635 void BindingSection::finalizeContents() {
636 raw_svector_ostream os{contents};
637 Binding lastBinding;
638 int16_t lastOrdinal = 0;
640 for (auto &p : sortBindings(bindingsMap)) {
641 const Symbol *sym = p.first;
642 std::vector<BindingEntry> &bindings = p.second;
643 uint8_t flags = BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM;
644 if (sym->isWeakRef())
645 flags |= BIND_SYMBOL_FLAGS_WEAK_IMPORT;
646 os << flags << sym->getName() << '\0'
647 << static_cast<uint8_t>(BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER);
648 int16_t ordinal = ordinalForSymbol(*sym);
649 if (ordinal != lastOrdinal) {
650 encodeDylibOrdinal(ordinal, os);
651 lastOrdinal = ordinal;
653 std::vector<BindIR> opcodes;
654 for (const BindingEntry &b : bindings)
655 encodeBinding(b.target.isec->parent,
656 b.target.isec->getOffset(b.target.offset), b.addend,
657 lastBinding, opcodes);
658 if (config->optimize > 1)
659 optimizeOpcodes(opcodes);
660 for (const auto &op : opcodes)
661 flushOpcodes(op, os);
663 if (!bindingsMap.empty())
664 os << static_cast<uint8_t>(BIND_OPCODE_DONE);
667 void BindingSection::writeTo(uint8_t *buf) const {
668 memcpy(buf, contents.data(), contents.size());
671 WeakBindingSection::WeakBindingSection()
672 : LinkEditSection(segment_names::linkEdit, section_names::weakBinding) {}
674 void WeakBindingSection::finalizeContents() {
675 raw_svector_ostream os{contents};
676 Binding lastBinding;
678 for (const Defined *defined : definitions)
679 encodeWeakOverride(defined, os);
681 for (auto &p : sortBindings(bindingsMap)) {
682 const Symbol *sym = p.first;
683 std::vector<BindingEntry> &bindings = p.second;
684 os << static_cast<uint8_t>(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM)
685 << sym->getName() << '\0'
686 << static_cast<uint8_t>(BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER);
687 std::vector<BindIR> opcodes;
688 for (const BindingEntry &b : bindings)
689 encodeBinding(b.target.isec->parent,
690 b.target.isec->getOffset(b.target.offset), b.addend,
691 lastBinding, opcodes);
692 if (config->optimize > 1)
693 optimizeOpcodes(opcodes);
694 for (const auto &op : opcodes)
695 flushOpcodes(op, os);
697 if (!bindingsMap.empty() || !definitions.empty())
698 os << static_cast<uint8_t>(BIND_OPCODE_DONE);
701 void WeakBindingSection::writeTo(uint8_t *buf) const {
702 memcpy(buf, contents.data(), contents.size());
705 StubsSection::StubsSection()
706 : SyntheticSection(segment_names::text, section_names::stubs) {
707 flags = S_SYMBOL_STUBS | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
708 // The stubs section comprises machine instructions, which are aligned to
709 // 4 bytes on the archs we care about.
710 align = 4;
711 reserved2 = target->stubSize;
714 uint64_t StubsSection::getSize() const {
715 return entries.size() * target->stubSize;
718 void StubsSection::writeTo(uint8_t *buf) const {
719 size_t off = 0;
720 for (const Symbol *sym : entries) {
721 uint64_t pointerVA =
722 config->emitChainedFixups ? sym->getGotVA() : sym->getLazyPtrVA();
723 target->writeStub(buf + off, *sym, pointerVA);
724 off += target->stubSize;
728 void StubsSection::finalize() { isFinal = true; }
730 static void addBindingsForStub(Symbol *sym) {
731 assert(!config->emitChainedFixups);
732 if (auto *dysym = dyn_cast<DylibSymbol>(sym)) {
733 if (sym->isWeakDef()) {
734 in.binding->addEntry(dysym, in.lazyPointers->isec,
735 sym->stubsIndex * target->wordSize);
736 in.weakBinding->addEntry(sym, in.lazyPointers->isec,
737 sym->stubsIndex * target->wordSize);
738 } else {
739 in.lazyBinding->addEntry(dysym);
741 } else if (auto *defined = dyn_cast<Defined>(sym)) {
742 if (defined->isExternalWeakDef()) {
743 in.rebase->addEntry(in.lazyPointers->isec,
744 sym->stubsIndex * target->wordSize);
745 in.weakBinding->addEntry(sym, in.lazyPointers->isec,
746 sym->stubsIndex * target->wordSize);
747 } else if (defined->interposable) {
748 in.lazyBinding->addEntry(sym);
749 } else {
750 llvm_unreachable("invalid stub target");
752 } else {
753 llvm_unreachable("invalid stub target symbol type");
757 void StubsSection::addEntry(Symbol *sym) {
758 bool inserted = entries.insert(sym);
759 if (inserted) {
760 sym->stubsIndex = entries.size() - 1;
762 if (config->emitChainedFixups)
763 in.got->addEntry(sym);
764 else
765 addBindingsForStub(sym);
769 StubHelperSection::StubHelperSection()
770 : SyntheticSection(segment_names::text, section_names::stubHelper) {
771 flags = S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
772 align = 4; // This section comprises machine instructions
775 uint64_t StubHelperSection::getSize() const {
776 return target->stubHelperHeaderSize +
777 in.lazyBinding->getEntries().size() * target->stubHelperEntrySize;
780 bool StubHelperSection::isNeeded() const { return in.lazyBinding->isNeeded(); }
782 void StubHelperSection::writeTo(uint8_t *buf) const {
783 target->writeStubHelperHeader(buf);
784 size_t off = target->stubHelperHeaderSize;
785 for (const Symbol *sym : in.lazyBinding->getEntries()) {
786 target->writeStubHelperEntry(buf + off, *sym, addr + off);
787 off += target->stubHelperEntrySize;
791 void StubHelperSection::setUp() {
792 Symbol *binder = symtab->addUndefined("dyld_stub_binder", /*file=*/nullptr,
793 /*isWeakRef=*/false);
794 if (auto *undefined = dyn_cast<Undefined>(binder))
795 treatUndefinedSymbol(*undefined,
796 "lazy binding (normally in libSystem.dylib)");
798 // treatUndefinedSymbol() can replace binder with a DylibSymbol; re-check.
799 stubBinder = dyn_cast_or_null<DylibSymbol>(binder);
800 if (stubBinder == nullptr)
801 return;
803 in.got->addEntry(stubBinder);
805 in.imageLoaderCache->parent =
806 ConcatOutputSection::getOrCreateForInput(in.imageLoaderCache);
807 addInputSection(in.imageLoaderCache);
808 // Since this isn't in the symbol table or in any input file, the noDeadStrip
809 // argument doesn't matter.
810 dyldPrivate =
811 make<Defined>("__dyld_private", nullptr, in.imageLoaderCache, 0, 0,
812 /*isWeakDef=*/false,
813 /*isExternal=*/false, /*isPrivateExtern=*/false,
814 /*includeInSymtab=*/true,
815 /*isReferencedDynamically=*/false,
816 /*noDeadStrip=*/false);
817 dyldPrivate->used = true;
820 llvm::DenseMap<llvm::CachedHashStringRef, ConcatInputSection *>
821 ObjCSelRefsHelper::methnameToSelref;
822 void ObjCSelRefsHelper::initialize() {
823 // Do not fold selrefs without ICF.
824 if (config->icfLevel == ICFLevel::none)
825 return;
827 // Search methnames already referenced in __objc_selrefs
828 // Map the name to the corresponding selref entry
829 // which we will reuse when creating objc stubs.
830 for (ConcatInputSection *isec : inputSections) {
831 if (isec->shouldOmitFromOutput())
832 continue;
833 if (isec->getName() != section_names::objcSelrefs)
834 continue;
835 // We expect a single relocation per selref entry to __objc_methname that
836 // might be aggregated.
837 assert(isec->relocs.size() == 1);
838 auto Reloc = isec->relocs[0];
839 if (const auto *sym = Reloc.referent.dyn_cast<Symbol *>()) {
840 if (const auto *d = dyn_cast<Defined>(sym)) {
841 auto *cisec = cast<CStringInputSection>(d->isec());
842 auto methname = cisec->getStringRefAtOffset(d->value);
843 methnameToSelref[CachedHashStringRef(methname)] = isec;
849 void ObjCSelRefsHelper::cleanup() { methnameToSelref.clear(); }
851 ConcatInputSection *ObjCSelRefsHelper::makeSelRef(StringRef methname) {
852 auto methnameOffset =
853 in.objcMethnameSection->getStringOffset(methname).outSecOff;
855 size_t wordSize = target->wordSize;
856 uint8_t *selrefData = bAlloc().Allocate<uint8_t>(wordSize);
857 write64le(selrefData, methnameOffset);
858 ConcatInputSection *objcSelref =
859 makeSyntheticInputSection(segment_names::data, section_names::objcSelrefs,
860 S_LITERAL_POINTERS | S_ATTR_NO_DEAD_STRIP,
861 ArrayRef<uint8_t>{selrefData, wordSize},
862 /*align=*/wordSize);
863 assert(objcSelref->live);
864 objcSelref->relocs.push_back({/*type=*/target->unsignedRelocType,
865 /*pcrel=*/false, /*length=*/3,
866 /*offset=*/0,
867 /*addend=*/static_cast<int64_t>(methnameOffset),
868 /*referent=*/in.objcMethnameSection->isec});
869 objcSelref->parent = ConcatOutputSection::getOrCreateForInput(objcSelref);
870 addInputSection(objcSelref);
871 objcSelref->isFinal = true;
872 methnameToSelref[CachedHashStringRef(methname)] = objcSelref;
873 return objcSelref;
876 ConcatInputSection *ObjCSelRefsHelper::getSelRef(StringRef methname) {
877 auto it = methnameToSelref.find(CachedHashStringRef(methname));
878 if (it == methnameToSelref.end())
879 return nullptr;
880 return it->second;
883 ObjCStubsSection::ObjCStubsSection()
884 : SyntheticSection(segment_names::text, section_names::objcStubs) {
885 flags = S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS;
886 align = config->objcStubsMode == ObjCStubsMode::fast
887 ? target->objcStubsFastAlignment
888 : target->objcStubsSmallAlignment;
891 bool ObjCStubsSection::isObjCStubSymbol(Symbol *sym) {
892 return sym->getName().starts_with(symbolPrefix);
895 StringRef ObjCStubsSection::getMethname(Symbol *sym) {
896 assert(isObjCStubSymbol(sym) && "not an objc stub");
897 auto name = sym->getName();
898 StringRef methname = name.drop_front(symbolPrefix.size());
899 return methname;
902 void ObjCStubsSection::addEntry(Symbol *sym) {
903 StringRef methname = getMethname(sym);
904 // We create a selref entry for each unique methname.
905 if (!ObjCSelRefsHelper::getSelRef(methname))
906 ObjCSelRefsHelper::makeSelRef(methname);
908 auto stubSize = config->objcStubsMode == ObjCStubsMode::fast
909 ? target->objcStubsFastSize
910 : target->objcStubsSmallSize;
911 Defined *newSym = replaceSymbol<Defined>(
912 sym, sym->getName(), nullptr, isec,
913 /*value=*/symbols.size() * stubSize,
914 /*size=*/stubSize,
915 /*isWeakDef=*/false, /*isExternal=*/true, /*isPrivateExtern=*/true,
916 /*includeInSymtab=*/true, /*isReferencedDynamically=*/false,
917 /*noDeadStrip=*/false);
918 symbols.push_back(newSym);
921 void ObjCStubsSection::setUp() {
922 objcMsgSend = symtab->addUndefined("_objc_msgSend", /*file=*/nullptr,
923 /*isWeakRef=*/false);
924 if (auto *undefined = dyn_cast<Undefined>(objcMsgSend))
925 treatUndefinedSymbol(*undefined,
926 "lazy binding (normally in libobjc.dylib)");
927 objcMsgSend->used = true;
928 if (config->objcStubsMode == ObjCStubsMode::fast) {
929 in.got->addEntry(objcMsgSend);
930 assert(objcMsgSend->isInGot());
931 } else {
932 assert(config->objcStubsMode == ObjCStubsMode::small);
933 // In line with ld64's behavior, when objc_msgSend is a direct symbol,
934 // we directly reference it.
935 // In other cases, typically when binding in libobjc.dylib,
936 // we generate a stub to invoke objc_msgSend.
937 if (!isa<Defined>(objcMsgSend))
938 in.stubs->addEntry(objcMsgSend);
942 uint64_t ObjCStubsSection::getSize() const {
943 auto stubSize = config->objcStubsMode == ObjCStubsMode::fast
944 ? target->objcStubsFastSize
945 : target->objcStubsSmallSize;
946 return stubSize * symbols.size();
949 void ObjCStubsSection::writeTo(uint8_t *buf) const {
950 uint64_t stubOffset = 0;
951 for (size_t i = 0, n = symbols.size(); i < n; ++i) {
952 Defined *sym = symbols[i];
954 auto methname = getMethname(sym);
955 InputSection *selRef = ObjCSelRefsHelper::getSelRef(methname);
956 assert(selRef != nullptr && "no selref for methname");
957 auto selrefAddr = selRef->getVA(0);
958 target->writeObjCMsgSendStub(buf + stubOffset, sym, in.objcStubs->addr,
959 stubOffset, selrefAddr, objcMsgSend);
963 LazyPointerSection::LazyPointerSection()
964 : SyntheticSection(segment_names::data, section_names::lazySymbolPtr) {
965 align = target->wordSize;
966 flags = S_LAZY_SYMBOL_POINTERS;
969 uint64_t LazyPointerSection::getSize() const {
970 return in.stubs->getEntries().size() * target->wordSize;
973 bool LazyPointerSection::isNeeded() const {
974 return !in.stubs->getEntries().empty();
977 void LazyPointerSection::writeTo(uint8_t *buf) const {
978 size_t off = 0;
979 for (const Symbol *sym : in.stubs->getEntries()) {
980 if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) {
981 if (dysym->hasStubsHelper()) {
982 uint64_t stubHelperOffset =
983 target->stubHelperHeaderSize +
984 dysym->stubsHelperIndex * target->stubHelperEntrySize;
985 write64le(buf + off, in.stubHelper->addr + stubHelperOffset);
987 } else {
988 write64le(buf + off, sym->getVA());
990 off += target->wordSize;
994 LazyBindingSection::LazyBindingSection()
995 : LinkEditSection(segment_names::linkEdit, section_names::lazyBinding) {}
997 void LazyBindingSection::finalizeContents() {
998 // TODO: Just precompute output size here instead of writing to a temporary
999 // buffer
1000 for (Symbol *sym : entries)
1001 sym->lazyBindOffset = encode(*sym);
1004 void LazyBindingSection::writeTo(uint8_t *buf) const {
1005 memcpy(buf, contents.data(), contents.size());
1008 void LazyBindingSection::addEntry(Symbol *sym) {
1009 assert(!config->emitChainedFixups && "Chained fixups always bind eagerly");
1010 if (entries.insert(sym)) {
1011 sym->stubsHelperIndex = entries.size() - 1;
1012 in.rebase->addEntry(in.lazyPointers->isec,
1013 sym->stubsIndex * target->wordSize);
1017 // Unlike the non-lazy binding section, the bind opcodes in this section aren't
1018 // interpreted all at once. Rather, dyld will start interpreting opcodes at a
1019 // given offset, typically only binding a single symbol before it finds a
1020 // BIND_OPCODE_DONE terminator. As such, unlike in the non-lazy-binding case,
1021 // we cannot encode just the differences between symbols; we have to emit the
1022 // complete bind information for each symbol.
1023 uint32_t LazyBindingSection::encode(const Symbol &sym) {
1024 uint32_t opstreamOffset = contents.size();
1025 OutputSegment *dataSeg = in.lazyPointers->parent;
1026 os << static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB |
1027 dataSeg->index);
1028 uint64_t offset =
1029 in.lazyPointers->addr - dataSeg->addr + sym.stubsIndex * target->wordSize;
1030 encodeULEB128(offset, os);
1031 encodeDylibOrdinal(ordinalForSymbol(sym), os);
1033 uint8_t flags = BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM;
1034 if (sym.isWeakRef())
1035 flags |= BIND_SYMBOL_FLAGS_WEAK_IMPORT;
1037 os << flags << sym.getName() << '\0'
1038 << static_cast<uint8_t>(BIND_OPCODE_DO_BIND)
1039 << static_cast<uint8_t>(BIND_OPCODE_DONE);
1040 return opstreamOffset;
1043 ExportSection::ExportSection()
1044 : LinkEditSection(segment_names::linkEdit, section_names::export_) {}
1046 void ExportSection::finalizeContents() {
1047 trieBuilder.setImageBase(in.header->addr);
1048 for (const Symbol *sym : symtab->getSymbols()) {
1049 if (const auto *defined = dyn_cast<Defined>(sym)) {
1050 if (defined->privateExtern || !defined->isLive())
1051 continue;
1052 trieBuilder.addSymbol(*defined);
1053 hasWeakSymbol = hasWeakSymbol || sym->isWeakDef();
1054 } else if (auto *dysym = dyn_cast<DylibSymbol>(sym)) {
1055 if (dysym->shouldReexport)
1056 trieBuilder.addSymbol(*dysym);
1059 size = trieBuilder.build();
1062 void ExportSection::writeTo(uint8_t *buf) const { trieBuilder.writeTo(buf); }
1064 DataInCodeSection::DataInCodeSection()
1065 : LinkEditSection(segment_names::linkEdit, section_names::dataInCode) {}
1067 template <class LP>
1068 static std::vector<MachO::data_in_code_entry> collectDataInCodeEntries() {
1069 std::vector<MachO::data_in_code_entry> dataInCodeEntries;
1070 for (const InputFile *inputFile : inputFiles) {
1071 if (!isa<ObjFile>(inputFile))
1072 continue;
1073 const ObjFile *objFile = cast<ObjFile>(inputFile);
1074 ArrayRef<MachO::data_in_code_entry> entries = objFile->getDataInCode();
1075 if (entries.empty())
1076 continue;
1078 std::vector<MachO::data_in_code_entry> sortedEntries;
1079 sortedEntries.assign(entries.begin(), entries.end());
1080 llvm::sort(sortedEntries, [](const data_in_code_entry &lhs,
1081 const data_in_code_entry &rhs) {
1082 return lhs.offset < rhs.offset;
1085 // For each code subsection find 'data in code' entries residing in it.
1086 // Compute the new offset values as
1087 // <offset within subsection> + <subsection address> - <__TEXT address>.
1088 for (const Section *section : objFile->sections) {
1089 for (const Subsection &subsec : section->subsections) {
1090 const InputSection *isec = subsec.isec;
1091 if (!isCodeSection(isec))
1092 continue;
1093 if (cast<ConcatInputSection>(isec)->shouldOmitFromOutput())
1094 continue;
1095 const uint64_t beginAddr = section->addr + subsec.offset;
1096 auto it = llvm::lower_bound(
1097 sortedEntries, beginAddr,
1098 [](const MachO::data_in_code_entry &entry, uint64_t addr) {
1099 return entry.offset < addr;
1101 const uint64_t endAddr = beginAddr + isec->getSize();
1102 for (const auto end = sortedEntries.end();
1103 it != end && it->offset + it->length <= endAddr; ++it)
1104 dataInCodeEntries.push_back(
1105 {static_cast<uint32_t>(isec->getVA(it->offset - beginAddr) -
1106 in.header->addr),
1107 it->length, it->kind});
1112 // ld64 emits the table in sorted order too.
1113 llvm::sort(dataInCodeEntries,
1114 [](const data_in_code_entry &lhs, const data_in_code_entry &rhs) {
1115 return lhs.offset < rhs.offset;
1117 return dataInCodeEntries;
1120 void DataInCodeSection::finalizeContents() {
1121 entries = target->wordSize == 8 ? collectDataInCodeEntries<LP64>()
1122 : collectDataInCodeEntries<ILP32>();
1125 void DataInCodeSection::writeTo(uint8_t *buf) const {
1126 if (!entries.empty())
1127 memcpy(buf, entries.data(), getRawSize());
1130 FunctionStartsSection::FunctionStartsSection()
1131 : LinkEditSection(segment_names::linkEdit, section_names::functionStarts) {}
1133 void FunctionStartsSection::finalizeContents() {
1134 raw_svector_ostream os{contents};
1135 std::vector<uint64_t> addrs;
1136 for (const InputFile *file : inputFiles) {
1137 if (auto *objFile = dyn_cast<ObjFile>(file)) {
1138 for (const Symbol *sym : objFile->symbols) {
1139 if (const auto *defined = dyn_cast_or_null<Defined>(sym)) {
1140 if (!defined->isec() || !isCodeSection(defined->isec()) ||
1141 !defined->isLive())
1142 continue;
1143 addrs.push_back(defined->getVA());
1148 llvm::sort(addrs);
1149 uint64_t addr = in.header->addr;
1150 for (uint64_t nextAddr : addrs) {
1151 uint64_t delta = nextAddr - addr;
1152 if (delta == 0)
1153 continue;
1154 encodeULEB128(delta, os);
1155 addr = nextAddr;
1157 os << '\0';
1160 void FunctionStartsSection::writeTo(uint8_t *buf) const {
1161 memcpy(buf, contents.data(), contents.size());
1164 SymtabSection::SymtabSection(StringTableSection &stringTableSection)
1165 : LinkEditSection(segment_names::linkEdit, section_names::symbolTable),
1166 stringTableSection(stringTableSection) {}
1168 void SymtabSection::emitBeginSourceStab(StringRef sourceFile) {
1169 StabsEntry stab(N_SO);
1170 stab.strx = stringTableSection.addString(saver().save(sourceFile));
1171 stabs.emplace_back(std::move(stab));
1174 void SymtabSection::emitEndSourceStab() {
1175 StabsEntry stab(N_SO);
1176 stab.sect = 1;
1177 stabs.emplace_back(std::move(stab));
1180 void SymtabSection::emitObjectFileStab(ObjFile *file) {
1181 StabsEntry stab(N_OSO);
1182 stab.sect = target->cpuSubtype;
1183 SmallString<261> path(!file->archiveName.empty() ? file->archiveName
1184 : file->getName());
1185 std::error_code ec = sys::fs::make_absolute(path);
1186 if (ec)
1187 fatal("failed to get absolute path for " + path);
1189 if (!file->archiveName.empty())
1190 path.append({"(", file->getName(), ")"});
1192 StringRef adjustedPath = saver().save(path.str());
1193 adjustedPath.consume_front(config->osoPrefix);
1195 stab.strx = stringTableSection.addString(adjustedPath);
1196 stab.desc = 1;
1197 stab.value = file->modTime;
1198 stabs.emplace_back(std::move(stab));
1201 void SymtabSection::emitEndFunStab(Defined *defined) {
1202 StabsEntry stab(N_FUN);
1203 stab.value = defined->size;
1204 stabs.emplace_back(std::move(stab));
1207 void SymtabSection::emitStabs() {
1208 if (config->omitDebugInfo)
1209 return;
1211 for (const std::string &s : config->astPaths) {
1212 StabsEntry astStab(N_AST);
1213 astStab.strx = stringTableSection.addString(s);
1214 stabs.emplace_back(std::move(astStab));
1217 // Cache the file ID for each symbol in an std::pair for faster sorting.
1218 using SortingPair = std::pair<Defined *, int>;
1219 std::vector<SortingPair> symbolsNeedingStabs;
1220 for (const SymtabEntry &entry :
1221 concat<SymtabEntry>(localSymbols, externalSymbols)) {
1222 Symbol *sym = entry.sym;
1223 assert(sym->isLive() &&
1224 "dead symbols should not be in localSymbols, externalSymbols");
1225 if (auto *defined = dyn_cast<Defined>(sym)) {
1226 // Excluded symbols should have been filtered out in finalizeContents().
1227 assert(defined->includeInSymtab);
1229 if (defined->isAbsolute())
1230 continue;
1232 // Never generate a STABS entry for a symbol that has been ICF'ed using a
1233 // thunk, just as we do for fully ICF'ed functions. Otherwise, we end up
1234 // generating invalid DWARF as dsymutil will assume the entire function
1235 // body is at that location, when, in reality, only the thunk is
1236 // present. This will end up causing overlapping DWARF entries.
1237 // TODO: Find an implementation that works in combination with
1238 // `--keep-icf-stabs`.
1239 if (defined->identicalCodeFoldingKind == Symbol::ICFFoldKind::Thunk)
1240 continue;
1242 // Constant-folded symbols go in the executable's symbol table, but don't
1243 // get a stabs entry unless --keep-icf-stabs flag is specified
1244 if (!config->keepICFStabs &&
1245 defined->identicalCodeFoldingKind == Symbol::ICFFoldKind::Body)
1246 continue;
1248 ObjFile *file = defined->getObjectFile();
1249 if (!file || !file->compileUnit)
1250 continue;
1252 // We use 'originalIsec' to get the file id of the symbol since 'isec()'
1253 // might point to the merged ICF symbol's file
1254 symbolsNeedingStabs.emplace_back(defined,
1255 defined->originalIsec->getFile()->id);
1259 llvm::stable_sort(symbolsNeedingStabs,
1260 [&](const SortingPair &a, const SortingPair &b) {
1261 return a.second < b.second;
1264 // Emit STABS symbols so that dsymutil and/or the debugger can map address
1265 // regions in the final binary to the source and object files from which they
1266 // originated.
1267 InputFile *lastFile = nullptr;
1268 for (SortingPair &pair : symbolsNeedingStabs) {
1269 Defined *defined = pair.first;
1270 // We use 'originalIsec' of the symbol since we care about the actual origin
1271 // of the symbol, not the canonical location returned by `isec()`.
1272 InputSection *isec = defined->originalIsec;
1273 ObjFile *file = cast<ObjFile>(isec->getFile());
1275 if (lastFile == nullptr || lastFile != file) {
1276 if (lastFile != nullptr)
1277 emitEndSourceStab();
1278 lastFile = file;
1280 emitBeginSourceStab(file->sourceFile());
1281 emitObjectFileStab(file);
1284 StabsEntry symStab;
1285 symStab.sect = isec->parent->index;
1286 symStab.strx = stringTableSection.addString(defined->getName());
1287 symStab.value = defined->getVA();
1289 if (isCodeSection(isec)) {
1290 symStab.type = N_FUN;
1291 stabs.emplace_back(std::move(symStab));
1292 emitEndFunStab(defined);
1293 } else {
1294 symStab.type = defined->isExternal() ? N_GSYM : N_STSYM;
1295 stabs.emplace_back(std::move(symStab));
1299 if (!stabs.empty())
1300 emitEndSourceStab();
1303 void SymtabSection::finalizeContents() {
1304 auto addSymbol = [&](std::vector<SymtabEntry> &symbols, Symbol *sym) {
1305 uint32_t strx = stringTableSection.addString(sym->getName());
1306 symbols.push_back({sym, strx});
1309 std::function<void(Symbol *)> localSymbolsHandler;
1310 switch (config->localSymbolsPresence) {
1311 case SymtabPresence::All:
1312 localSymbolsHandler = [&](Symbol *sym) { addSymbol(localSymbols, sym); };
1313 break;
1314 case SymtabPresence::None:
1315 localSymbolsHandler = [&](Symbol *) { /* Do nothing*/ };
1316 break;
1317 case SymtabPresence::SelectivelyIncluded:
1318 localSymbolsHandler = [&](Symbol *sym) {
1319 if (config->localSymbolPatterns.match(sym->getName()))
1320 addSymbol(localSymbols, sym);
1322 break;
1323 case SymtabPresence::SelectivelyExcluded:
1324 localSymbolsHandler = [&](Symbol *sym) {
1325 if (!config->localSymbolPatterns.match(sym->getName()))
1326 addSymbol(localSymbols, sym);
1328 break;
1331 // Local symbols aren't in the SymbolTable, so we walk the list of object
1332 // files to gather them.
1333 // But if `-x` is set, then we don't need to. localSymbolsHandler() will do
1334 // the right thing regardless, but this check is a perf optimization because
1335 // iterating through all the input files and their symbols is expensive.
1336 if (config->localSymbolsPresence != SymtabPresence::None) {
1337 for (const InputFile *file : inputFiles) {
1338 if (auto *objFile = dyn_cast<ObjFile>(file)) {
1339 for (Symbol *sym : objFile->symbols) {
1340 if (auto *defined = dyn_cast_or_null<Defined>(sym)) {
1341 if (defined->isExternal() || !defined->isLive() ||
1342 !defined->includeInSymtab)
1343 continue;
1344 localSymbolsHandler(sym);
1351 // __dyld_private is a local symbol too. It's linker-created and doesn't
1352 // exist in any object file.
1353 if (in.stubHelper && in.stubHelper->dyldPrivate)
1354 localSymbolsHandler(in.stubHelper->dyldPrivate);
1356 for (Symbol *sym : symtab->getSymbols()) {
1357 if (!sym->isLive())
1358 continue;
1359 if (auto *defined = dyn_cast<Defined>(sym)) {
1360 if (!defined->includeInSymtab)
1361 continue;
1362 assert(defined->isExternal());
1363 if (defined->privateExtern)
1364 localSymbolsHandler(defined);
1365 else
1366 addSymbol(externalSymbols, defined);
1367 } else if (auto *dysym = dyn_cast<DylibSymbol>(sym)) {
1368 if (dysym->isReferenced())
1369 addSymbol(undefinedSymbols, sym);
1373 emitStabs();
1374 uint32_t symtabIndex = stabs.size();
1375 for (const SymtabEntry &entry :
1376 concat<SymtabEntry>(localSymbols, externalSymbols, undefinedSymbols)) {
1377 entry.sym->symtabIndex = symtabIndex++;
1381 uint32_t SymtabSection::getNumSymbols() const {
1382 return stabs.size() + localSymbols.size() + externalSymbols.size() +
1383 undefinedSymbols.size();
1386 // This serves to hide (type-erase) the template parameter from SymtabSection.
1387 template <class LP> class SymtabSectionImpl final : public SymtabSection {
1388 public:
1389 SymtabSectionImpl(StringTableSection &stringTableSection)
1390 : SymtabSection(stringTableSection) {}
1391 uint64_t getRawSize() const override;
1392 void writeTo(uint8_t *buf) const override;
1395 template <class LP> uint64_t SymtabSectionImpl<LP>::getRawSize() const {
1396 return getNumSymbols() * sizeof(typename LP::nlist);
1399 template <class LP> void SymtabSectionImpl<LP>::writeTo(uint8_t *buf) const {
1400 auto *nList = reinterpret_cast<typename LP::nlist *>(buf);
1401 // Emit the stabs entries before the "real" symbols. We cannot emit them
1402 // after as that would render Symbol::symtabIndex inaccurate.
1403 for (const StabsEntry &entry : stabs) {
1404 nList->n_strx = entry.strx;
1405 nList->n_type = entry.type;
1406 nList->n_sect = entry.sect;
1407 nList->n_desc = entry.desc;
1408 nList->n_value = entry.value;
1409 ++nList;
1412 for (const SymtabEntry &entry : concat<const SymtabEntry>(
1413 localSymbols, externalSymbols, undefinedSymbols)) {
1414 nList->n_strx = entry.strx;
1415 // TODO populate n_desc with more flags
1416 if (auto *defined = dyn_cast<Defined>(entry.sym)) {
1417 uint8_t scope = 0;
1418 if (defined->privateExtern) {
1419 // Private external -- dylib scoped symbol.
1420 // Promote to non-external at link time.
1421 scope = N_PEXT;
1422 } else if (defined->isExternal()) {
1423 // Normal global symbol.
1424 scope = N_EXT;
1425 } else {
1426 // TU-local symbol from localSymbols.
1427 scope = 0;
1430 if (defined->isAbsolute()) {
1431 nList->n_type = scope | N_ABS;
1432 nList->n_sect = NO_SECT;
1433 nList->n_value = defined->value;
1434 } else {
1435 nList->n_type = scope | N_SECT;
1436 nList->n_sect = defined->isec()->parent->index;
1437 // For the N_SECT symbol type, n_value is the address of the symbol
1438 nList->n_value = defined->getVA();
1440 nList->n_desc |= defined->isExternalWeakDef() ? N_WEAK_DEF : 0;
1441 nList->n_desc |=
1442 defined->referencedDynamically ? REFERENCED_DYNAMICALLY : 0;
1443 } else if (auto *dysym = dyn_cast<DylibSymbol>(entry.sym)) {
1444 uint16_t n_desc = nList->n_desc;
1445 int16_t ordinal = ordinalForDylibSymbol(*dysym);
1446 if (ordinal == BIND_SPECIAL_DYLIB_FLAT_LOOKUP)
1447 SET_LIBRARY_ORDINAL(n_desc, DYNAMIC_LOOKUP_ORDINAL);
1448 else if (ordinal == BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE)
1449 SET_LIBRARY_ORDINAL(n_desc, EXECUTABLE_ORDINAL);
1450 else {
1451 assert(ordinal > 0);
1452 SET_LIBRARY_ORDINAL(n_desc, static_cast<uint8_t>(ordinal));
1455 nList->n_type = N_EXT;
1456 n_desc |= dysym->isWeakDef() ? N_WEAK_DEF : 0;
1457 n_desc |= dysym->isWeakRef() ? N_WEAK_REF : 0;
1458 nList->n_desc = n_desc;
1460 ++nList;
1464 template <class LP>
1465 SymtabSection *
1466 macho::makeSymtabSection(StringTableSection &stringTableSection) {
1467 return make<SymtabSectionImpl<LP>>(stringTableSection);
1470 IndirectSymtabSection::IndirectSymtabSection()
1471 : LinkEditSection(segment_names::linkEdit,
1472 section_names::indirectSymbolTable) {}
1474 uint32_t IndirectSymtabSection::getNumSymbols() const {
1475 uint32_t size = in.got->getEntries().size() +
1476 in.tlvPointers->getEntries().size() +
1477 in.stubs->getEntries().size();
1478 if (!config->emitChainedFixups)
1479 size += in.stubs->getEntries().size();
1480 return size;
1483 bool IndirectSymtabSection::isNeeded() const {
1484 return in.got->isNeeded() || in.tlvPointers->isNeeded() ||
1485 in.stubs->isNeeded();
1488 void IndirectSymtabSection::finalizeContents() {
1489 uint32_t off = 0;
1490 in.got->reserved1 = off;
1491 off += in.got->getEntries().size();
1492 in.tlvPointers->reserved1 = off;
1493 off += in.tlvPointers->getEntries().size();
1494 in.stubs->reserved1 = off;
1495 if (in.lazyPointers) {
1496 off += in.stubs->getEntries().size();
1497 in.lazyPointers->reserved1 = off;
1501 static uint32_t indirectValue(const Symbol *sym) {
1502 if (sym->symtabIndex == UINT32_MAX || !needsBinding(sym))
1503 return INDIRECT_SYMBOL_LOCAL;
1504 return sym->symtabIndex;
1507 void IndirectSymtabSection::writeTo(uint8_t *buf) const {
1508 uint32_t off = 0;
1509 for (const Symbol *sym : in.got->getEntries()) {
1510 write32le(buf + off * sizeof(uint32_t), indirectValue(sym));
1511 ++off;
1513 for (const Symbol *sym : in.tlvPointers->getEntries()) {
1514 write32le(buf + off * sizeof(uint32_t), indirectValue(sym));
1515 ++off;
1517 for (const Symbol *sym : in.stubs->getEntries()) {
1518 write32le(buf + off * sizeof(uint32_t), indirectValue(sym));
1519 ++off;
1522 if (in.lazyPointers) {
1523 // There is a 1:1 correspondence between stubs and LazyPointerSection
1524 // entries. But giving __stubs and __la_symbol_ptr the same reserved1
1525 // (the offset into the indirect symbol table) so that they both refer
1526 // to the same range of offsets confuses `strip`, so write the stubs
1527 // symbol table offsets a second time.
1528 for (const Symbol *sym : in.stubs->getEntries()) {
1529 write32le(buf + off * sizeof(uint32_t), indirectValue(sym));
1530 ++off;
1535 StringTableSection::StringTableSection()
1536 : LinkEditSection(segment_names::linkEdit, section_names::stringTable) {}
1538 uint32_t StringTableSection::addString(StringRef str) {
1539 uint32_t strx = size;
1540 strings.push_back(str); // TODO: consider deduplicating strings
1541 size += str.size() + 1; // account for null terminator
1542 return strx;
1545 void StringTableSection::writeTo(uint8_t *buf) const {
1546 uint32_t off = 0;
1547 for (StringRef str : strings) {
1548 memcpy(buf + off, str.data(), str.size());
1549 off += str.size() + 1; // account for null terminator
1553 static_assert((CodeSignatureSection::blobHeadersSize % 8) == 0);
1554 static_assert((CodeSignatureSection::fixedHeadersSize % 8) == 0);
1556 CodeSignatureSection::CodeSignatureSection()
1557 : LinkEditSection(segment_names::linkEdit, section_names::codeSignature) {
1558 align = 16; // required by libstuff
1560 // XXX: This mimics LD64, where it uses the install-name as codesign
1561 // identifier, if available.
1562 if (!config->installName.empty())
1563 fileName = config->installName;
1564 else
1565 // FIXME: Consider using finalOutput instead of outputFile.
1566 fileName = config->outputFile;
1568 size_t slashIndex = fileName.rfind("/");
1569 if (slashIndex != std::string::npos)
1570 fileName = fileName.drop_front(slashIndex + 1);
1572 // NOTE: Any changes to these calculations should be repeated
1573 // in llvm-objcopy's MachOLayoutBuilder::layoutTail.
1574 allHeadersSize = alignTo<16>(fixedHeadersSize + fileName.size() + 1);
1575 fileNamePad = allHeadersSize - fixedHeadersSize - fileName.size();
1578 uint32_t CodeSignatureSection::getBlockCount() const {
1579 return (fileOff + blockSize - 1) / blockSize;
1582 uint64_t CodeSignatureSection::getRawSize() const {
1583 return allHeadersSize + getBlockCount() * hashSize;
1586 void CodeSignatureSection::writeHashes(uint8_t *buf) const {
1587 // NOTE: Changes to this functionality should be repeated in llvm-objcopy's
1588 // MachOWriter::writeSignatureData.
1589 uint8_t *hashes = buf + fileOff + allHeadersSize;
1590 parallelFor(0, getBlockCount(), [&](size_t i) {
1591 sha256(buf + i * blockSize,
1592 std::min(static_cast<size_t>(fileOff - i * blockSize), blockSize),
1593 hashes + i * hashSize);
1595 #if defined(__APPLE__)
1596 // This is macOS-specific work-around and makes no sense for any
1597 // other host OS. See https://openradar.appspot.com/FB8914231
1599 // The macOS kernel maintains a signature-verification cache to
1600 // quickly validate applications at time of execve(2). The trouble
1601 // is that for the kernel creates the cache entry at the time of the
1602 // mmap(2) call, before we have a chance to write either the code to
1603 // sign or the signature header+hashes. The fix is to invalidate
1604 // all cached data associated with the output file, thus discarding
1605 // the bogus prematurely-cached signature.
1606 msync(buf, fileOff + getSize(), MS_INVALIDATE);
1607 #endif
1610 void CodeSignatureSection::writeTo(uint8_t *buf) const {
1611 // NOTE: Changes to this functionality should be repeated in llvm-objcopy's
1612 // MachOWriter::writeSignatureData.
1613 uint32_t signatureSize = static_cast<uint32_t>(getSize());
1614 auto *superBlob = reinterpret_cast<CS_SuperBlob *>(buf);
1615 write32be(&superBlob->magic, CSMAGIC_EMBEDDED_SIGNATURE);
1616 write32be(&superBlob->length, signatureSize);
1617 write32be(&superBlob->count, 1);
1618 auto *blobIndex = reinterpret_cast<CS_BlobIndex *>(&superBlob[1]);
1619 write32be(&blobIndex->type, CSSLOT_CODEDIRECTORY);
1620 write32be(&blobIndex->offset, blobHeadersSize);
1621 auto *codeDirectory =
1622 reinterpret_cast<CS_CodeDirectory *>(buf + blobHeadersSize);
1623 write32be(&codeDirectory->magic, CSMAGIC_CODEDIRECTORY);
1624 write32be(&codeDirectory->length, signatureSize - blobHeadersSize);
1625 write32be(&codeDirectory->version, CS_SUPPORTSEXECSEG);
1626 write32be(&codeDirectory->flags, CS_ADHOC | CS_LINKER_SIGNED);
1627 write32be(&codeDirectory->hashOffset,
1628 sizeof(CS_CodeDirectory) + fileName.size() + fileNamePad);
1629 write32be(&codeDirectory->identOffset, sizeof(CS_CodeDirectory));
1630 codeDirectory->nSpecialSlots = 0;
1631 write32be(&codeDirectory->nCodeSlots, getBlockCount());
1632 write32be(&codeDirectory->codeLimit, fileOff);
1633 codeDirectory->hashSize = static_cast<uint8_t>(hashSize);
1634 codeDirectory->hashType = kSecCodeSignatureHashSHA256;
1635 codeDirectory->platform = 0;
1636 codeDirectory->pageSize = blockSizeShift;
1637 codeDirectory->spare2 = 0;
1638 codeDirectory->scatterOffset = 0;
1639 codeDirectory->teamOffset = 0;
1640 codeDirectory->spare3 = 0;
1641 codeDirectory->codeLimit64 = 0;
1642 OutputSegment *textSeg = getOrCreateOutputSegment(segment_names::text);
1643 write64be(&codeDirectory->execSegBase, textSeg->fileOff);
1644 write64be(&codeDirectory->execSegLimit, textSeg->fileSize);
1645 write64be(&codeDirectory->execSegFlags,
1646 config->outputType == MH_EXECUTE ? CS_EXECSEG_MAIN_BINARY : 0);
1647 auto *id = reinterpret_cast<char *>(&codeDirectory[1]);
1648 memcpy(id, fileName.begin(), fileName.size());
1649 memset(id + fileName.size(), 0, fileNamePad);
1652 CStringSection::CStringSection(const char *name)
1653 : SyntheticSection(segment_names::text, name) {
1654 flags = S_CSTRING_LITERALS;
1657 void CStringSection::addInput(CStringInputSection *isec) {
1658 isec->parent = this;
1659 inputs.push_back(isec);
1660 if (isec->align > align)
1661 align = isec->align;
1664 void CStringSection::writeTo(uint8_t *buf) const {
1665 for (const CStringInputSection *isec : inputs) {
1666 for (const auto &[i, piece] : llvm::enumerate(isec->pieces)) {
1667 if (!piece.live)
1668 continue;
1669 StringRef string = isec->getStringRef(i);
1670 memcpy(buf + piece.outSecOff, string.data(), string.size());
1675 void CStringSection::finalizeContents() {
1676 uint64_t offset = 0;
1677 for (CStringInputSection *isec : inputs) {
1678 for (const auto &[i, piece] : llvm::enumerate(isec->pieces)) {
1679 if (!piece.live)
1680 continue;
1681 // See comment above DeduplicatedCStringSection for how alignment is
1682 // handled.
1683 uint32_t pieceAlign = 1
1684 << llvm::countr_zero(isec->align | piece.inSecOff);
1685 offset = alignToPowerOf2(offset, pieceAlign);
1686 piece.outSecOff = offset;
1687 isec->isFinal = true;
1688 StringRef string = isec->getStringRef(i);
1689 offset += string.size() + 1; // account for null terminator
1692 size = offset;
1695 // Mergeable cstring literals are found under the __TEXT,__cstring section. In
1696 // contrast to ELF, which puts strings that need different alignments into
1697 // different sections, clang's Mach-O backend puts them all in one section.
1698 // Strings that need to be aligned have the .p2align directive emitted before
1699 // them, which simply translates into zero padding in the object file. In other
1700 // words, we have to infer the desired alignment of these cstrings from their
1701 // addresses.
1703 // We differ slightly from ld64 in how we've chosen to align these cstrings.
1704 // Both LLD and ld64 preserve the number of trailing zeros in each cstring's
1705 // address in the input object files. When deduplicating identical cstrings,
1706 // both linkers pick the cstring whose address has more trailing zeros, and
1707 // preserve the alignment of that address in the final binary. However, ld64
1708 // goes a step further and also preserves the offset of the cstring from the
1709 // last section-aligned address. I.e. if a cstring is at offset 18 in the
1710 // input, with a section alignment of 16, then both LLD and ld64 will ensure the
1711 // final address is 2-byte aligned (since 18 == 16 + 2). But ld64 will also
1712 // ensure that the final address is of the form 16 * k + 2 for some k.
1714 // Note that ld64's heuristic means that a dedup'ed cstring's final address is
1715 // dependent on the order of the input object files. E.g. if in addition to the
1716 // cstring at offset 18 above, we have a duplicate one in another file with a
1717 // `.cstring` section alignment of 2 and an offset of zero, then ld64 will pick
1718 // the cstring from the object file earlier on the command line (since both have
1719 // the same number of trailing zeros in their address). So the final cstring may
1720 // either be at some address `16 * k + 2` or at some address `2 * k`.
1722 // I've opted not to follow this behavior primarily for implementation
1723 // simplicity, and secondarily to save a few more bytes. It's not clear to me
1724 // that preserving the section alignment + offset is ever necessary, and there
1725 // are many cases that are clearly redundant. In particular, if an x86_64 object
1726 // file contains some strings that are accessed via SIMD instructions, then the
1727 // .cstring section in the object file will be 16-byte-aligned (since SIMD
1728 // requires its operand addresses to be 16-byte aligned). However, there will
1729 // typically also be other cstrings in the same file that aren't used via SIMD
1730 // and don't need this alignment. They will be emitted at some arbitrary address
1731 // `A`, but ld64 will treat them as being 16-byte aligned with an offset of `16
1732 // % A`.
1733 void DeduplicatedCStringSection::finalizeContents() {
1734 // Find the largest alignment required for each string.
1735 for (const CStringInputSection *isec : inputs) {
1736 for (const auto &[i, piece] : llvm::enumerate(isec->pieces)) {
1737 if (!piece.live)
1738 continue;
1739 auto s = isec->getCachedHashStringRef(i);
1740 assert(isec->align != 0);
1741 uint8_t trailingZeros = llvm::countr_zero(isec->align | piece.inSecOff);
1742 auto it = stringOffsetMap.insert(
1743 std::make_pair(s, StringOffset(trailingZeros)));
1744 if (!it.second && it.first->second.trailingZeros < trailingZeros)
1745 it.first->second.trailingZeros = trailingZeros;
1749 // Assign an offset for each string and save it to the corresponding
1750 // StringPieces for easy access.
1751 for (CStringInputSection *isec : inputs) {
1752 for (const auto &[i, piece] : llvm::enumerate(isec->pieces)) {
1753 if (!piece.live)
1754 continue;
1755 auto s = isec->getCachedHashStringRef(i);
1756 auto it = stringOffsetMap.find(s);
1757 assert(it != stringOffsetMap.end());
1758 StringOffset &offsetInfo = it->second;
1759 if (offsetInfo.outSecOff == UINT64_MAX) {
1760 offsetInfo.outSecOff =
1761 alignToPowerOf2(size, 1ULL << offsetInfo.trailingZeros);
1762 size =
1763 offsetInfo.outSecOff + s.size() + 1; // account for null terminator
1765 piece.outSecOff = offsetInfo.outSecOff;
1767 isec->isFinal = true;
1771 void DeduplicatedCStringSection::writeTo(uint8_t *buf) const {
1772 for (const auto &p : stringOffsetMap) {
1773 StringRef data = p.first.val();
1774 uint64_t off = p.second.outSecOff;
1775 if (!data.empty())
1776 memcpy(buf + off, data.data(), data.size());
1780 DeduplicatedCStringSection::StringOffset
1781 DeduplicatedCStringSection::getStringOffset(StringRef str) const {
1782 // StringPiece uses 31 bits to store the hashes, so we replicate that
1783 uint32_t hash = xxh3_64bits(str) & 0x7fffffff;
1784 auto offset = stringOffsetMap.find(CachedHashStringRef(str, hash));
1785 assert(offset != stringOffsetMap.end() &&
1786 "Looked-up strings should always exist in section");
1787 return offset->second;
1790 // This section is actually emitted as __TEXT,__const by ld64, but clang may
1791 // emit input sections of that name, and LLD doesn't currently support mixing
1792 // synthetic and concat-type OutputSections. To work around this, I've given
1793 // our merged-literals section a different name.
1794 WordLiteralSection::WordLiteralSection()
1795 : SyntheticSection(segment_names::text, section_names::literals) {
1796 align = 16;
1799 void WordLiteralSection::addInput(WordLiteralInputSection *isec) {
1800 isec->parent = this;
1801 inputs.push_back(isec);
1804 void WordLiteralSection::finalizeContents() {
1805 for (WordLiteralInputSection *isec : inputs) {
1806 // We do all processing of the InputSection here, so it will be effectively
1807 // finalized.
1808 isec->isFinal = true;
1809 const uint8_t *buf = isec->data.data();
1810 switch (sectionType(isec->getFlags())) {
1811 case S_4BYTE_LITERALS: {
1812 for (size_t off = 0, e = isec->data.size(); off < e; off += 4) {
1813 if (!isec->isLive(off))
1814 continue;
1815 uint32_t value = *reinterpret_cast<const uint32_t *>(buf + off);
1816 literal4Map.emplace(value, literal4Map.size());
1818 break;
1820 case S_8BYTE_LITERALS: {
1821 for (size_t off = 0, e = isec->data.size(); off < e; off += 8) {
1822 if (!isec->isLive(off))
1823 continue;
1824 uint64_t value = *reinterpret_cast<const uint64_t *>(buf + off);
1825 literal8Map.emplace(value, literal8Map.size());
1827 break;
1829 case S_16BYTE_LITERALS: {
1830 for (size_t off = 0, e = isec->data.size(); off < e; off += 16) {
1831 if (!isec->isLive(off))
1832 continue;
1833 UInt128 value = *reinterpret_cast<const UInt128 *>(buf + off);
1834 literal16Map.emplace(value, literal16Map.size());
1836 break;
1838 default:
1839 llvm_unreachable("invalid literal section type");
1844 void WordLiteralSection::writeTo(uint8_t *buf) const {
1845 // Note that we don't attempt to do any endianness conversion in addInput(),
1846 // so we don't do it here either -- just write out the original value,
1847 // byte-for-byte.
1848 for (const auto &p : literal16Map)
1849 memcpy(buf + p.second * 16, &p.first, 16);
1850 buf += literal16Map.size() * 16;
1852 for (const auto &p : literal8Map)
1853 memcpy(buf + p.second * 8, &p.first, 8);
1854 buf += literal8Map.size() * 8;
1856 for (const auto &p : literal4Map)
1857 memcpy(buf + p.second * 4, &p.first, 4);
1860 ObjCImageInfoSection::ObjCImageInfoSection()
1861 : SyntheticSection(segment_names::data, section_names::objCImageInfo) {}
1863 ObjCImageInfoSection::ImageInfo
1864 ObjCImageInfoSection::parseImageInfo(const InputFile *file) {
1865 ImageInfo info;
1866 ArrayRef<uint8_t> data = file->objCImageInfo;
1867 // The image info struct has the following layout:
1868 // struct {
1869 // uint32_t version;
1870 // uint32_t flags;
1871 // };
1872 if (data.size() < 8) {
1873 warn(toString(file) + ": invalid __objc_imageinfo size");
1874 return info;
1877 auto *buf = reinterpret_cast<const uint32_t *>(data.data());
1878 if (read32le(buf) != 0) {
1879 warn(toString(file) + ": invalid __objc_imageinfo version");
1880 return info;
1883 uint32_t flags = read32le(buf + 1);
1884 info.swiftVersion = (flags >> 8) & 0xff;
1885 info.hasCategoryClassProperties = flags & 0x40;
1886 return info;
1889 static std::string swiftVersionString(uint8_t version) {
1890 switch (version) {
1891 case 1:
1892 return "1.0";
1893 case 2:
1894 return "1.1";
1895 case 3:
1896 return "2.0";
1897 case 4:
1898 return "3.0";
1899 case 5:
1900 return "4.0";
1901 default:
1902 return ("0x" + Twine::utohexstr(version)).str();
1906 // Validate each object file's __objc_imageinfo and use them to generate the
1907 // image info for the output binary. Only two pieces of info are relevant:
1908 // 1. The Swift version (should be identical across inputs)
1909 // 2. `bool hasCategoryClassProperties` (true only if true for all inputs)
1910 void ObjCImageInfoSection::finalizeContents() {
1911 assert(files.size() != 0); // should have already been checked via isNeeded()
1913 info.hasCategoryClassProperties = true;
1914 const InputFile *firstFile;
1915 for (const InputFile *file : files) {
1916 ImageInfo inputInfo = parseImageInfo(file);
1917 info.hasCategoryClassProperties &= inputInfo.hasCategoryClassProperties;
1919 // swiftVersion 0 means no Swift is present, so no version checking required
1920 if (inputInfo.swiftVersion == 0)
1921 continue;
1923 if (info.swiftVersion != 0 && info.swiftVersion != inputInfo.swiftVersion) {
1924 error("Swift version mismatch: " + toString(firstFile) + " has version " +
1925 swiftVersionString(info.swiftVersion) + " but " + toString(file) +
1926 " has version " + swiftVersionString(inputInfo.swiftVersion));
1927 } else {
1928 info.swiftVersion = inputInfo.swiftVersion;
1929 firstFile = file;
1934 void ObjCImageInfoSection::writeTo(uint8_t *buf) const {
1935 uint32_t flags = info.hasCategoryClassProperties ? 0x40 : 0x0;
1936 flags |= info.swiftVersion << 8;
1937 write32le(buf + 4, flags);
1940 InitOffsetsSection::InitOffsetsSection()
1941 : SyntheticSection(segment_names::text, section_names::initOffsets) {
1942 flags = S_INIT_FUNC_OFFSETS;
1943 align = 4; // This section contains 32-bit integers.
1946 uint64_t InitOffsetsSection::getSize() const {
1947 size_t count = 0;
1948 for (const ConcatInputSection *isec : sections)
1949 count += isec->relocs.size();
1950 return count * sizeof(uint32_t);
1953 void InitOffsetsSection::writeTo(uint8_t *buf) const {
1954 // FIXME: Add function specified by -init when that argument is implemented.
1955 for (ConcatInputSection *isec : sections) {
1956 for (const Reloc &rel : isec->relocs) {
1957 const Symbol *referent = rel.referent.dyn_cast<Symbol *>();
1958 assert(referent && "section relocation should have been rejected");
1959 uint64_t offset = referent->getVA() - in.header->addr;
1960 // FIXME: Can we handle this gracefully?
1961 if (offset > UINT32_MAX)
1962 fatal(isec->getLocation(rel.offset) + ": offset to initializer " +
1963 referent->getName() + " (" + utohexstr(offset) +
1964 ") does not fit in 32 bits");
1966 // Entries need to be added in the order they appear in the section, but
1967 // relocations aren't guaranteed to be sorted.
1968 size_t index = rel.offset >> target->p2WordSize;
1969 write32le(&buf[index * sizeof(uint32_t)], offset);
1971 buf += isec->relocs.size() * sizeof(uint32_t);
1975 // The inputs are __mod_init_func sections, which contain pointers to
1976 // initializer functions, therefore all relocations should be of the UNSIGNED
1977 // type. InitOffsetsSection stores offsets, so if the initializer's address is
1978 // not known at link time, stub-indirection has to be used.
1979 void InitOffsetsSection::setUp() {
1980 for (const ConcatInputSection *isec : sections) {
1981 for (const Reloc &rel : isec->relocs) {
1982 RelocAttrs attrs = target->getRelocAttrs(rel.type);
1983 if (!attrs.hasAttr(RelocAttrBits::UNSIGNED))
1984 error(isec->getLocation(rel.offset) +
1985 ": unsupported relocation type: " + attrs.name);
1986 if (rel.addend != 0)
1987 error(isec->getLocation(rel.offset) +
1988 ": relocation addend is not representable in __init_offsets");
1989 if (rel.referent.is<InputSection *>())
1990 error(isec->getLocation(rel.offset) +
1991 ": unexpected section relocation");
1993 Symbol *sym = rel.referent.dyn_cast<Symbol *>();
1994 if (auto *undefined = dyn_cast<Undefined>(sym))
1995 treatUndefinedSymbol(*undefined, isec, rel.offset);
1996 if (needsBinding(sym))
1997 in.stubs->addEntry(sym);
2002 ObjCMethListSection::ObjCMethListSection()
2003 : SyntheticSection(segment_names::text, section_names::objcMethList) {
2004 flags = S_ATTR_NO_DEAD_STRIP;
2005 align = relativeOffsetSize;
2008 // Go through all input method lists and ensure that we have selrefs for all
2009 // their method names. The selrefs will be needed later by ::writeTo. We need to
2010 // create them early on here to ensure they are processed correctly by the lld
2011 // pipeline.
2012 void ObjCMethListSection::setUp() {
2013 for (const ConcatInputSection *isec : inputs) {
2014 uint32_t structSizeAndFlags = 0, structCount = 0;
2015 readMethodListHeader(isec->data.data(), structSizeAndFlags, structCount);
2016 uint32_t originalStructSize = structSizeAndFlags & structSizeMask;
2017 // Method name is immediately after header
2018 uint32_t methodNameOff = methodListHeaderSize;
2020 // Loop through all methods, and ensure a selref for each of them exists.
2021 while (methodNameOff < isec->data.size()) {
2022 const Reloc *reloc = isec->getRelocAt(methodNameOff);
2023 assert(reloc && "Relocation expected at method list name slot");
2025 StringRef methname = reloc->getReferentString();
2026 if (!ObjCSelRefsHelper::getSelRef(methname))
2027 ObjCSelRefsHelper::makeSelRef(methname);
2029 // Jump to method name offset in next struct
2030 methodNameOff += originalStructSize;
2035 // Calculate section size and final offsets for where InputSection's need to be
2036 // written.
2037 void ObjCMethListSection::finalize() {
2038 // sectionSize will be the total size of the __objc_methlist section
2039 sectionSize = 0;
2040 for (ConcatInputSection *isec : inputs) {
2041 // We can also use sectionSize as write offset for isec
2042 assert(sectionSize == alignToPowerOf2(sectionSize, relativeOffsetSize) &&
2043 "expected __objc_methlist to be aligned by default with the "
2044 "required section alignment");
2045 isec->outSecOff = sectionSize;
2047 isec->isFinal = true;
2048 uint32_t relativeListSize =
2049 computeRelativeMethodListSize(isec->data.size());
2050 sectionSize += relativeListSize;
2052 // If encoding the method list in relative offset format shrinks the size,
2053 // then we also need to adjust symbol sizes to match the new size. Note that
2054 // on 32bit platforms the size of the method list will remain the same when
2055 // encoded in relative offset format.
2056 if (relativeListSize != isec->data.size()) {
2057 for (Symbol *sym : isec->symbols) {
2058 assert(isa<Defined>(sym) &&
2059 "Unexpected undefined symbol in ObjC method list");
2060 auto *def = cast<Defined>(sym);
2061 // There can be 0-size symbols, check if this is the case and ignore
2062 // them.
2063 if (def->size) {
2064 assert(
2065 def->size == isec->data.size() &&
2066 "Invalid ObjC method list symbol size: expected symbol size to "
2067 "match isec size");
2068 def->size = relativeListSize;
2075 void ObjCMethListSection::writeTo(uint8_t *bufStart) const {
2076 uint8_t *buf = bufStart;
2077 for (const ConcatInputSection *isec : inputs) {
2078 assert(buf - bufStart == long(isec->outSecOff) &&
2079 "Writing at unexpected offset");
2080 uint32_t writtenSize = writeRelativeMethodList(isec, buf);
2081 buf += writtenSize;
2083 assert(buf - bufStart == sectionSize &&
2084 "Written size does not match expected section size");
2087 // Check if an InputSection is a method list. To do this we scan the
2088 // InputSection for any symbols who's names match the patterns we expect clang
2089 // to generate for method lists.
2090 bool ObjCMethListSection::isMethodList(const ConcatInputSection *isec) {
2091 const char *symPrefixes[] = {objc::symbol_names::classMethods,
2092 objc::symbol_names::instanceMethods,
2093 objc::symbol_names::categoryInstanceMethods,
2094 objc::symbol_names::categoryClassMethods};
2095 if (!isec)
2096 return false;
2097 for (const Symbol *sym : isec->symbols) {
2098 auto *def = dyn_cast_or_null<Defined>(sym);
2099 if (!def)
2100 continue;
2101 for (const char *prefix : symPrefixes) {
2102 if (def->getName().starts_with(prefix)) {
2103 assert(def->size == isec->data.size() &&
2104 "Invalid ObjC method list symbol size: expected symbol size to "
2105 "match isec size");
2106 assert(def->value == 0 &&
2107 "Offset of ObjC method list symbol must be 0");
2108 return true;
2113 return false;
2116 // Encode a single relative offset value. The input is the data/symbol at
2117 // (&isec->data[inSecOff]). The output is written to (&buf[outSecOff]).
2118 // 'createSelRef' indicates that we should not directly use the specified
2119 // symbol, but instead get the selRef for the symbol and use that instead.
2120 void ObjCMethListSection::writeRelativeOffsetForIsec(
2121 const ConcatInputSection *isec, uint8_t *buf, uint32_t &inSecOff,
2122 uint32_t &outSecOff, bool useSelRef) const {
2123 const Reloc *reloc = isec->getRelocAt(inSecOff);
2124 assert(reloc && "Relocation expected at __objc_methlist Offset");
2126 uint32_t symVA = 0;
2127 if (useSelRef) {
2128 StringRef methname = reloc->getReferentString();
2129 ConcatInputSection *selRef = ObjCSelRefsHelper::getSelRef(methname);
2130 assert(selRef && "Expected all selector names to already be already be "
2131 "present in __objc_selrefs");
2132 symVA = selRef->getVA();
2133 assert(selRef->data.size() == target->wordSize &&
2134 "Expected one selref per ConcatInputSection");
2135 } else if (reloc->referent.is<Symbol *>()) {
2136 auto *def = dyn_cast_or_null<Defined>(reloc->referent.get<Symbol *>());
2137 assert(def && "Expected all syms in __objc_methlist to be defined");
2138 symVA = def->getVA();
2139 } else {
2140 auto *isec = reloc->referent.get<InputSection *>();
2141 symVA = isec->getVA(reloc->addend);
2144 uint32_t currentVA = isec->getVA() + outSecOff;
2145 uint32_t delta = symVA - currentVA;
2146 write32le(buf + outSecOff, delta);
2148 // Move one pointer forward in the absolute method list
2149 inSecOff += target->wordSize;
2150 // Move one relative offset forward in the relative method list (32 bits)
2151 outSecOff += relativeOffsetSize;
2154 // Write a relative method list to buf, return the size of the written
2155 // information
2156 uint32_t
2157 ObjCMethListSection::writeRelativeMethodList(const ConcatInputSection *isec,
2158 uint8_t *buf) const {
2159 // Copy over the header, and add the "this is a relative method list" magic
2160 // value flag
2161 uint32_t structSizeAndFlags = 0, structCount = 0;
2162 readMethodListHeader(isec->data.data(), structSizeAndFlags, structCount);
2163 // Set the struct size for the relative method list
2164 uint32_t relativeStructSizeAndFlags =
2165 (relativeOffsetSize * pointersPerStruct) & structSizeMask;
2166 // Carry over the old flags from the input struct
2167 relativeStructSizeAndFlags |= structSizeAndFlags & structFlagsMask;
2168 // Set the relative method list flag
2169 relativeStructSizeAndFlags |= relMethodHeaderFlag;
2171 writeMethodListHeader(buf, relativeStructSizeAndFlags, structCount);
2173 assert(methodListHeaderSize +
2174 (structCount * pointersPerStruct * target->wordSize) ==
2175 isec->data.size() &&
2176 "Invalid computed ObjC method list size");
2178 uint32_t inSecOff = methodListHeaderSize;
2179 uint32_t outSecOff = methodListHeaderSize;
2181 // Go through the method list and encode input absolute pointers as relative
2182 // offsets. writeRelativeOffsetForIsec will be incrementing inSecOff and
2183 // outSecOff
2184 for (uint32_t i = 0; i < structCount; i++) {
2185 // Write the name of the method
2186 writeRelativeOffsetForIsec(isec, buf, inSecOff, outSecOff, true);
2187 // Write the type of the method
2188 writeRelativeOffsetForIsec(isec, buf, inSecOff, outSecOff, false);
2189 // Write reference to the selector of the method
2190 writeRelativeOffsetForIsec(isec, buf, inSecOff, outSecOff, false);
2193 // Expecting to have read all the data in the isec
2194 assert(inSecOff == isec->data.size() &&
2195 "Invalid actual ObjC method list size");
2196 assert(
2197 outSecOff == computeRelativeMethodListSize(inSecOff) &&
2198 "Mismatch between input & output size when writing relative method list");
2199 return outSecOff;
2202 // Given the size of an ObjC method list InputSection, return the size of the
2203 // method list when encoded in relative offsets format. We can do this without
2204 // decoding the actual data, as it can be directly inferred from the size of the
2205 // isec.
2206 uint32_t ObjCMethListSection::computeRelativeMethodListSize(
2207 uint32_t absoluteMethodListSize) const {
2208 uint32_t oldPointersSize = absoluteMethodListSize - methodListHeaderSize;
2209 uint32_t pointerCount = oldPointersSize / target->wordSize;
2210 assert(((pointerCount % pointersPerStruct) == 0) &&
2211 "__objc_methlist expects method lists to have multiple-of-3 pointers");
2213 uint32_t newPointersSize = pointerCount * relativeOffsetSize;
2214 uint32_t newTotalSize = methodListHeaderSize + newPointersSize;
2216 assert((newTotalSize <= absoluteMethodListSize) &&
2217 "Expected relative method list size to be smaller or equal than "
2218 "original size");
2219 return newTotalSize;
2222 // Read a method list header from buf
2223 void ObjCMethListSection::readMethodListHeader(const uint8_t *buf,
2224 uint32_t &structSizeAndFlags,
2225 uint32_t &structCount) const {
2226 structSizeAndFlags = read32le(buf);
2227 structCount = read32le(buf + sizeof(uint32_t));
2230 // Write a method list header to buf
2231 void ObjCMethListSection::writeMethodListHeader(uint8_t *buf,
2232 uint32_t structSizeAndFlags,
2233 uint32_t structCount) const {
2234 write32le(buf, structSizeAndFlags);
2235 write32le(buf + sizeof(structSizeAndFlags), structCount);
2238 void macho::createSyntheticSymbols() {
2239 auto addHeaderSymbol = [](const char *name) {
2240 symtab->addSynthetic(name, in.header->isec, /*value=*/0,
2241 /*isPrivateExtern=*/true, /*includeInSymtab=*/false,
2242 /*referencedDynamically=*/false);
2245 switch (config->outputType) {
2246 // FIXME: Assign the right address value for these symbols
2247 // (rather than 0). But we need to do that after assignAddresses().
2248 case MH_EXECUTE:
2249 // If linking PIE, __mh_execute_header is a defined symbol in
2250 // __TEXT, __text)
2251 // Otherwise, it's an absolute symbol.
2252 if (config->isPic)
2253 symtab->addSynthetic("__mh_execute_header", in.header->isec, /*value=*/0,
2254 /*isPrivateExtern=*/false, /*includeInSymtab=*/true,
2255 /*referencedDynamically=*/true);
2256 else
2257 symtab->addSynthetic("__mh_execute_header", /*isec=*/nullptr, /*value=*/0,
2258 /*isPrivateExtern=*/false, /*includeInSymtab=*/true,
2259 /*referencedDynamically=*/true);
2260 break;
2262 // The following symbols are N_SECT symbols, even though the header is not
2263 // part of any section and that they are private to the bundle/dylib/object
2264 // they are part of.
2265 case MH_BUNDLE:
2266 addHeaderSymbol("__mh_bundle_header");
2267 break;
2268 case MH_DYLIB:
2269 addHeaderSymbol("__mh_dylib_header");
2270 break;
2271 case MH_DYLINKER:
2272 addHeaderSymbol("__mh_dylinker_header");
2273 break;
2274 case MH_OBJECT:
2275 addHeaderSymbol("__mh_object_header");
2276 break;
2277 default:
2278 llvm_unreachable("unexpected outputType");
2279 break;
2282 // The Itanium C++ ABI requires dylibs to pass a pointer to __cxa_atexit
2283 // which does e.g. cleanup of static global variables. The ABI document
2284 // says that the pointer can point to any address in one of the dylib's
2285 // segments, but in practice ld64 seems to set it to point to the header,
2286 // so that's what's implemented here.
2287 addHeaderSymbol("___dso_handle");
2290 ChainedFixupsSection::ChainedFixupsSection()
2291 : LinkEditSection(segment_names::linkEdit, section_names::chainFixups) {}
2293 bool ChainedFixupsSection::isNeeded() const {
2294 assert(config->emitChainedFixups);
2295 // dyld always expects LC_DYLD_CHAINED_FIXUPS to point to a valid
2296 // dyld_chained_fixups_header, so we create this section even if there aren't
2297 // any fixups.
2298 return true;
2301 void ChainedFixupsSection::addBinding(const Symbol *sym,
2302 const InputSection *isec, uint64_t offset,
2303 int64_t addend) {
2304 locations.emplace_back(isec, offset);
2305 int64_t outlineAddend = (addend < 0 || addend > 0xFF) ? addend : 0;
2306 auto [it, inserted] = bindings.insert(
2307 {{sym, outlineAddend}, static_cast<uint32_t>(bindings.size())});
2309 if (inserted) {
2310 symtabSize += sym->getName().size() + 1;
2311 hasWeakBind = hasWeakBind || needsWeakBind(*sym);
2312 if (!isInt<23>(outlineAddend))
2313 needsLargeAddend = true;
2314 else if (outlineAddend != 0)
2315 needsAddend = true;
2319 std::pair<uint32_t, uint8_t>
2320 ChainedFixupsSection::getBinding(const Symbol *sym, int64_t addend) const {
2321 int64_t outlineAddend = (addend < 0 || addend > 0xFF) ? addend : 0;
2322 auto it = bindings.find({sym, outlineAddend});
2323 assert(it != bindings.end() && "binding not found in the imports table");
2324 if (outlineAddend == 0)
2325 return {it->second, addend};
2326 return {it->second, 0};
2329 static size_t writeImport(uint8_t *buf, int format, int16_t libOrdinal,
2330 bool weakRef, uint32_t nameOffset, int64_t addend) {
2331 switch (format) {
2332 case DYLD_CHAINED_IMPORT: {
2333 auto *import = reinterpret_cast<dyld_chained_import *>(buf);
2334 import->lib_ordinal = libOrdinal;
2335 import->weak_import = weakRef;
2336 import->name_offset = nameOffset;
2337 return sizeof(dyld_chained_import);
2339 case DYLD_CHAINED_IMPORT_ADDEND: {
2340 auto *import = reinterpret_cast<dyld_chained_import_addend *>(buf);
2341 import->lib_ordinal = libOrdinal;
2342 import->weak_import = weakRef;
2343 import->name_offset = nameOffset;
2344 import->addend = addend;
2345 return sizeof(dyld_chained_import_addend);
2347 case DYLD_CHAINED_IMPORT_ADDEND64: {
2348 auto *import = reinterpret_cast<dyld_chained_import_addend64 *>(buf);
2349 import->lib_ordinal = libOrdinal;
2350 import->weak_import = weakRef;
2351 import->name_offset = nameOffset;
2352 import->addend = addend;
2353 return sizeof(dyld_chained_import_addend64);
2355 default:
2356 llvm_unreachable("Unknown import format");
2360 size_t ChainedFixupsSection::SegmentInfo::getSize() const {
2361 assert(pageStarts.size() > 0 && "SegmentInfo for segment with no fixups?");
2362 return alignTo<8>(sizeof(dyld_chained_starts_in_segment) +
2363 pageStarts.back().first * sizeof(uint16_t));
2366 size_t ChainedFixupsSection::SegmentInfo::writeTo(uint8_t *buf) const {
2367 auto *segInfo = reinterpret_cast<dyld_chained_starts_in_segment *>(buf);
2368 segInfo->size = getSize();
2369 segInfo->page_size = target->getPageSize();
2370 // FIXME: Use DYLD_CHAINED_PTR_64_OFFSET on newer OS versions.
2371 segInfo->pointer_format = DYLD_CHAINED_PTR_64;
2372 segInfo->segment_offset = oseg->addr - in.header->addr;
2373 segInfo->max_valid_pointer = 0; // not used on 64-bit
2374 segInfo->page_count = pageStarts.back().first + 1;
2376 uint16_t *starts = segInfo->page_start;
2377 for (size_t i = 0; i < segInfo->page_count; ++i)
2378 starts[i] = DYLD_CHAINED_PTR_START_NONE;
2380 for (auto [pageIdx, startAddr] : pageStarts)
2381 starts[pageIdx] = startAddr;
2382 return segInfo->size;
2385 static size_t importEntrySize(int format) {
2386 switch (format) {
2387 case DYLD_CHAINED_IMPORT:
2388 return sizeof(dyld_chained_import);
2389 case DYLD_CHAINED_IMPORT_ADDEND:
2390 return sizeof(dyld_chained_import_addend);
2391 case DYLD_CHAINED_IMPORT_ADDEND64:
2392 return sizeof(dyld_chained_import_addend64);
2393 default:
2394 llvm_unreachable("Unknown import format");
2398 // This is step 3 of the algorithm described in the class comment of
2399 // ChainedFixupsSection.
2401 // LC_DYLD_CHAINED_FIXUPS data consists of (in this order):
2402 // * A dyld_chained_fixups_header
2403 // * A dyld_chained_starts_in_image
2404 // * One dyld_chained_starts_in_segment per segment
2405 // * List of all imports (dyld_chained_import, dyld_chained_import_addend, or
2406 // dyld_chained_import_addend64)
2407 // * Names of imported symbols
2408 void ChainedFixupsSection::writeTo(uint8_t *buf) const {
2409 auto *header = reinterpret_cast<dyld_chained_fixups_header *>(buf);
2410 header->fixups_version = 0;
2411 header->imports_count = bindings.size();
2412 header->imports_format = importFormat;
2413 header->symbols_format = 0;
2415 buf += alignTo<8>(sizeof(*header));
2417 auto curOffset = [&buf, &header]() -> uint32_t {
2418 return buf - reinterpret_cast<uint8_t *>(header);
2421 header->starts_offset = curOffset();
2423 auto *imageInfo = reinterpret_cast<dyld_chained_starts_in_image *>(buf);
2424 imageInfo->seg_count = outputSegments.size();
2425 uint32_t *segStarts = imageInfo->seg_info_offset;
2427 // dyld_chained_starts_in_image ends in a flexible array member containing an
2428 // uint32_t for each segment. Leave room for it, and fill it via segStarts.
2429 buf += alignTo<8>(offsetof(dyld_chained_starts_in_image, seg_info_offset) +
2430 outputSegments.size() * sizeof(uint32_t));
2432 // Initialize all offsets to 0, which indicates that the segment does not have
2433 // fixups. Those that do have them will be filled in below.
2434 for (size_t i = 0; i < outputSegments.size(); ++i)
2435 segStarts[i] = 0;
2437 for (const SegmentInfo &seg : fixupSegments) {
2438 segStarts[seg.oseg->index] = curOffset() - header->starts_offset;
2439 buf += seg.writeTo(buf);
2442 // Write imports table.
2443 header->imports_offset = curOffset();
2444 uint64_t nameOffset = 0;
2445 for (auto [import, idx] : bindings) {
2446 const Symbol &sym = *import.first;
2447 buf += writeImport(buf, importFormat, ordinalForSymbol(sym),
2448 sym.isWeakRef(), nameOffset, import.second);
2449 nameOffset += sym.getName().size() + 1;
2452 // Write imported symbol names.
2453 header->symbols_offset = curOffset();
2454 for (auto [import, idx] : bindings) {
2455 StringRef name = import.first->getName();
2456 memcpy(buf, name.data(), name.size());
2457 buf += name.size() + 1; // account for null terminator
2460 assert(curOffset() == getRawSize());
2463 // This is step 2 of the algorithm described in the class comment of
2464 // ChainedFixupsSection.
2465 void ChainedFixupsSection::finalizeContents() {
2466 assert(target->wordSize == 8 && "Only 64-bit platforms are supported");
2467 assert(config->emitChainedFixups);
2469 if (!isUInt<32>(symtabSize))
2470 error("cannot encode chained fixups: imported symbols table size " +
2471 Twine(symtabSize) + " exceeds 4 GiB");
2473 bool needsLargeOrdinal = any_of(bindings, [](const auto &p) {
2474 // 0xF1 - 0xFF are reserved for special ordinals in the 8-bit encoding.
2475 return ordinalForSymbol(*p.first.first) > 0xF0;
2478 if (needsLargeAddend || !isUInt<23>(symtabSize) || needsLargeOrdinal)
2479 importFormat = DYLD_CHAINED_IMPORT_ADDEND64;
2480 else if (needsAddend)
2481 importFormat = DYLD_CHAINED_IMPORT_ADDEND;
2482 else
2483 importFormat = DYLD_CHAINED_IMPORT;
2485 for (Location &loc : locations)
2486 loc.offset =
2487 loc.isec->parent->getSegmentOffset() + loc.isec->getOffset(loc.offset);
2489 llvm::sort(locations, [](const Location &a, const Location &b) {
2490 const OutputSegment *segA = a.isec->parent->parent;
2491 const OutputSegment *segB = b.isec->parent->parent;
2492 if (segA == segB)
2493 return a.offset < b.offset;
2494 return segA->addr < segB->addr;
2497 auto sameSegment = [](const Location &a, const Location &b) {
2498 return a.isec->parent->parent == b.isec->parent->parent;
2501 const uint64_t pageSize = target->getPageSize();
2502 for (size_t i = 0, count = locations.size(); i < count;) {
2503 const Location &firstLoc = locations[i];
2504 fixupSegments.emplace_back(firstLoc.isec->parent->parent);
2505 while (i < count && sameSegment(locations[i], firstLoc)) {
2506 uint32_t pageIdx = locations[i].offset / pageSize;
2507 fixupSegments.back().pageStarts.emplace_back(
2508 pageIdx, locations[i].offset % pageSize);
2509 ++i;
2510 while (i < count && sameSegment(locations[i], firstLoc) &&
2511 locations[i].offset / pageSize == pageIdx)
2512 ++i;
2516 // Compute expected encoded size.
2517 size = alignTo<8>(sizeof(dyld_chained_fixups_header));
2518 size += alignTo<8>(offsetof(dyld_chained_starts_in_image, seg_info_offset) +
2519 outputSegments.size() * sizeof(uint32_t));
2520 for (const SegmentInfo &seg : fixupSegments)
2521 size += seg.getSize();
2522 size += importEntrySize(importFormat) * bindings.size();
2523 size += symtabSize;
2526 template SymtabSection *macho::makeSymtabSection<LP64>(StringTableSection &);
2527 template SymtabSection *macho::makeSymtabSection<ILP32>(StringTableSection &);