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