1 //===- Writer.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 "Writer.h"
10 #include "ConcatOutputSection.h"
11 #include "Config.h"
12 #include "InputFiles.h"
13 #include "InputSection.h"
14 #include "MapFile.h"
15 #include "OutputSection.h"
16 #include "OutputSegment.h"
17 #include "SymbolTable.h"
18 #include "Symbols.h"
19 #include "SyntheticSections.h"
20 #include "Target.h"
21 #include "UnwindInfoSection.h"
22
23 #include "lld/Common/Arrays.h"
24 #include "lld/Common/ErrorHandler.h"
25 #include "lld/Common/Memory.h"
26 #include "llvm/BinaryFormat/MachO.h"
27 #include "llvm/Config/llvm-config.h"
28 #include "llvm/Support/LEB128.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/Parallel.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/TimeProfiler.h"
33 #include "llvm/Support/xxhash.h"
34
35 #include <algorithm>
36
37 using namespace llvm;
38 using namespace llvm::MachO;
39 using namespace llvm::sys;
40 using namespace lld;
41 using namespace lld::macho;
42
43 namespace {
44 class LCUuid;
45
46 class Writer {
47 public:
Writer()48 Writer() : buffer(errorHandler().outputBuffer) {}
49
50 void treatSpecialUndefineds();
51 void scanRelocations();
52 void scanSymbols();
53 template <class LP> void createOutputSections();
54 template <class LP> void createLoadCommands();
55 void finalizeAddresses();
56 void finalizeLinkEditSegment();
57 void assignAddresses(OutputSegment *);
58
59 void openFile();
60 void writeSections();
61 void writeUuid();
62 void writeCodeSignature();
63 void writeOutputFile();
64
65 template <class LP> void run();
66
67 std::unique_ptr<FileOutputBuffer> &buffer;
68 uint64_t addr = 0;
69 uint64_t fileOff = 0;
70 MachHeaderSection *header = nullptr;
71 StringTableSection *stringTableSection = nullptr;
72 SymtabSection *symtabSection = nullptr;
73 IndirectSymtabSection *indirectSymtabSection = nullptr;
74 CodeSignatureSection *codeSignatureSection = nullptr;
75 DataInCodeSection *dataInCodeSection = nullptr;
76 FunctionStartsSection *functionStartsSection = nullptr;
77
78 LCUuid *uuidCommand = nullptr;
79 OutputSegment *linkEditSegment = nullptr;
80 };
81
82 // LC_DYLD_INFO_ONLY stores the offsets of symbol import/export information.
83 class LCDyldInfo final : public LoadCommand {
84 public:
LCDyldInfo(RebaseSection * rebaseSection,BindingSection * bindingSection,WeakBindingSection * weakBindingSection,LazyBindingSection * lazyBindingSection,ExportSection * exportSection)85 LCDyldInfo(RebaseSection *rebaseSection, BindingSection *bindingSection,
86 WeakBindingSection *weakBindingSection,
87 LazyBindingSection *lazyBindingSection,
88 ExportSection *exportSection)
89 : rebaseSection(rebaseSection), bindingSection(bindingSection),
90 weakBindingSection(weakBindingSection),
91 lazyBindingSection(lazyBindingSection), exportSection(exportSection) {}
92
getSize() const93 uint32_t getSize() const override { return sizeof(dyld_info_command); }
94
writeTo(uint8_t * buf) const95 void writeTo(uint8_t *buf) const override {
96 auto *c = reinterpret_cast<dyld_info_command *>(buf);
97 c->cmd = LC_DYLD_INFO_ONLY;
98 c->cmdsize = getSize();
99 if (rebaseSection->isNeeded()) {
100 c->rebase_off = rebaseSection->fileOff;
101 c->rebase_size = rebaseSection->getFileSize();
102 }
103 if (bindingSection->isNeeded()) {
104 c->bind_off = bindingSection->fileOff;
105 c->bind_size = bindingSection->getFileSize();
106 }
107 if (weakBindingSection->isNeeded()) {
108 c->weak_bind_off = weakBindingSection->fileOff;
109 c->weak_bind_size = weakBindingSection->getFileSize();
110 }
111 if (lazyBindingSection->isNeeded()) {
112 c->lazy_bind_off = lazyBindingSection->fileOff;
113 c->lazy_bind_size = lazyBindingSection->getFileSize();
114 }
115 if (exportSection->isNeeded()) {
116 c->export_off = exportSection->fileOff;
117 c->export_size = exportSection->getFileSize();
118 }
119 }
120
121 RebaseSection *rebaseSection;
122 BindingSection *bindingSection;
123 WeakBindingSection *weakBindingSection;
124 LazyBindingSection *lazyBindingSection;
125 ExportSection *exportSection;
126 };
127
128 class LCSubFramework final : public LoadCommand {
129 public:
LCSubFramework(StringRef umbrella)130 LCSubFramework(StringRef umbrella) : umbrella(umbrella) {}
131
getSize() const132 uint32_t getSize() const override {
133 return alignTo(sizeof(sub_framework_command) + umbrella.size() + 1,
134 target->wordSize);
135 }
136
writeTo(uint8_t * buf) const137 void writeTo(uint8_t *buf) const override {
138 auto *c = reinterpret_cast<sub_framework_command *>(buf);
139 buf += sizeof(sub_framework_command);
140
141 c->cmd = LC_SUB_FRAMEWORK;
142 c->cmdsize = getSize();
143 c->umbrella = sizeof(sub_framework_command);
144
145 memcpy(buf, umbrella.data(), umbrella.size());
146 buf[umbrella.size()] = '\0';
147 }
148
149 private:
150 const StringRef umbrella;
151 };
152
153 class LCFunctionStarts final : public LoadCommand {
154 public:
LCFunctionStarts(FunctionStartsSection * functionStartsSection)155 explicit LCFunctionStarts(FunctionStartsSection *functionStartsSection)
156 : functionStartsSection(functionStartsSection) {}
157
getSize() const158 uint32_t getSize() const override { return sizeof(linkedit_data_command); }
159
writeTo(uint8_t * buf) const160 void writeTo(uint8_t *buf) const override {
161 auto *c = reinterpret_cast<linkedit_data_command *>(buf);
162 c->cmd = LC_FUNCTION_STARTS;
163 c->cmdsize = getSize();
164 c->dataoff = functionStartsSection->fileOff;
165 c->datasize = functionStartsSection->getFileSize();
166 }
167
168 private:
169 FunctionStartsSection *functionStartsSection;
170 };
171
172 class LCDataInCode final : public LoadCommand {
173 public:
LCDataInCode(DataInCodeSection * dataInCodeSection)174 explicit LCDataInCode(DataInCodeSection *dataInCodeSection)
175 : dataInCodeSection(dataInCodeSection) {}
176
getSize() const177 uint32_t getSize() const override { return sizeof(linkedit_data_command); }
178
writeTo(uint8_t * buf) const179 void writeTo(uint8_t *buf) const override {
180 auto *c = reinterpret_cast<linkedit_data_command *>(buf);
181 c->cmd = LC_DATA_IN_CODE;
182 c->cmdsize = getSize();
183 c->dataoff = dataInCodeSection->fileOff;
184 c->datasize = dataInCodeSection->getFileSize();
185 }
186
187 private:
188 DataInCodeSection *dataInCodeSection;
189 };
190
191 class LCDysymtab final : public LoadCommand {
192 public:
LCDysymtab(SymtabSection * symtabSection,IndirectSymtabSection * indirectSymtabSection)193 LCDysymtab(SymtabSection *symtabSection,
194 IndirectSymtabSection *indirectSymtabSection)
195 : symtabSection(symtabSection),
196 indirectSymtabSection(indirectSymtabSection) {}
197
getSize() const198 uint32_t getSize() const override { return sizeof(dysymtab_command); }
199
writeTo(uint8_t * buf) const200 void writeTo(uint8_t *buf) const override {
201 auto *c = reinterpret_cast<dysymtab_command *>(buf);
202 c->cmd = LC_DYSYMTAB;
203 c->cmdsize = getSize();
204
205 c->ilocalsym = 0;
206 c->iextdefsym = c->nlocalsym = symtabSection->getNumLocalSymbols();
207 c->nextdefsym = symtabSection->getNumExternalSymbols();
208 c->iundefsym = c->iextdefsym + c->nextdefsym;
209 c->nundefsym = symtabSection->getNumUndefinedSymbols();
210
211 c->indirectsymoff = indirectSymtabSection->fileOff;
212 c->nindirectsyms = indirectSymtabSection->getNumSymbols();
213 }
214
215 SymtabSection *symtabSection;
216 IndirectSymtabSection *indirectSymtabSection;
217 };
218
219 template <class LP> class LCSegment final : public LoadCommand {
220 public:
LCSegment(StringRef name,OutputSegment * seg)221 LCSegment(StringRef name, OutputSegment *seg) : name(name), seg(seg) {}
222
getSize() const223 uint32_t getSize() const override {
224 return sizeof(typename LP::segment_command) +
225 seg->numNonHiddenSections() * sizeof(typename LP::section);
226 }
227
writeTo(uint8_t * buf) const228 void writeTo(uint8_t *buf) const override {
229 using SegmentCommand = typename LP::segment_command;
230 using Section = typename LP::section;
231
232 auto *c = reinterpret_cast<SegmentCommand *>(buf);
233 buf += sizeof(SegmentCommand);
234
235 c->cmd = LP::segmentLCType;
236 c->cmdsize = getSize();
237 memcpy(c->segname, name.data(), name.size());
238 c->fileoff = seg->fileOff;
239 c->maxprot = seg->maxProt;
240 c->initprot = seg->initProt;
241
242 c->vmaddr = seg->addr;
243 c->vmsize = seg->vmSize;
244 c->filesize = seg->fileSize;
245 c->nsects = seg->numNonHiddenSections();
246
247 for (const OutputSection *osec : seg->getSections()) {
248 if (osec->isHidden())
249 continue;
250
251 auto *sectHdr = reinterpret_cast<Section *>(buf);
252 buf += sizeof(Section);
253
254 memcpy(sectHdr->sectname, osec->name.data(), osec->name.size());
255 memcpy(sectHdr->segname, name.data(), name.size());
256
257 sectHdr->addr = osec->addr;
258 sectHdr->offset = osec->fileOff;
259 sectHdr->align = Log2_32(osec->align);
260 sectHdr->flags = osec->flags;
261 sectHdr->size = osec->getSize();
262 sectHdr->reserved1 = osec->reserved1;
263 sectHdr->reserved2 = osec->reserved2;
264 }
265 }
266
267 private:
268 StringRef name;
269 OutputSegment *seg;
270 };
271
272 class LCMain final : public LoadCommand {
getSize() const273 uint32_t getSize() const override {
274 return sizeof(structs::entry_point_command);
275 }
276
writeTo(uint8_t * buf) const277 void writeTo(uint8_t *buf) const override {
278 auto *c = reinterpret_cast<structs::entry_point_command *>(buf);
279 c->cmd = LC_MAIN;
280 c->cmdsize = getSize();
281
282 if (config->entry->isInStubs())
283 c->entryoff =
284 in.stubs->fileOff + config->entry->stubsIndex * target->stubSize;
285 else
286 c->entryoff = config->entry->getVA() - in.header->addr;
287
288 c->stacksize = 0;
289 }
290 };
291
292 class LCSymtab final : public LoadCommand {
293 public:
LCSymtab(SymtabSection * symtabSection,StringTableSection * stringTableSection)294 LCSymtab(SymtabSection *symtabSection, StringTableSection *stringTableSection)
295 : symtabSection(symtabSection), stringTableSection(stringTableSection) {}
296
getSize() const297 uint32_t getSize() const override { return sizeof(symtab_command); }
298
writeTo(uint8_t * buf) const299 void writeTo(uint8_t *buf) const override {
300 auto *c = reinterpret_cast<symtab_command *>(buf);
301 c->cmd = LC_SYMTAB;
302 c->cmdsize = getSize();
303 c->symoff = symtabSection->fileOff;
304 c->nsyms = symtabSection->getNumSymbols();
305 c->stroff = stringTableSection->fileOff;
306 c->strsize = stringTableSection->getFileSize();
307 }
308
309 SymtabSection *symtabSection = nullptr;
310 StringTableSection *stringTableSection = nullptr;
311 };
312
313 // There are several dylib load commands that share the same structure:
314 // * LC_LOAD_DYLIB
315 // * LC_ID_DYLIB
316 // * LC_REEXPORT_DYLIB
317 class LCDylib final : public LoadCommand {
318 public:
LCDylib(LoadCommandType type,StringRef path,uint32_t compatibilityVersion=0,uint32_t currentVersion=0)319 LCDylib(LoadCommandType type, StringRef path,
320 uint32_t compatibilityVersion = 0, uint32_t currentVersion = 0)
321 : type(type), path(path), compatibilityVersion(compatibilityVersion),
322 currentVersion(currentVersion) {
323 instanceCount++;
324 }
325
getSize() const326 uint32_t getSize() const override {
327 return alignTo(sizeof(dylib_command) + path.size() + 1, 8);
328 }
329
writeTo(uint8_t * buf) const330 void writeTo(uint8_t *buf) const override {
331 auto *c = reinterpret_cast<dylib_command *>(buf);
332 buf += sizeof(dylib_command);
333
334 c->cmd = type;
335 c->cmdsize = getSize();
336 c->dylib.name = sizeof(dylib_command);
337 c->dylib.timestamp = 0;
338 c->dylib.compatibility_version = compatibilityVersion;
339 c->dylib.current_version = currentVersion;
340
341 memcpy(buf, path.data(), path.size());
342 buf[path.size()] = '\0';
343 }
344
getInstanceCount()345 static uint32_t getInstanceCount() { return instanceCount; }
346
347 private:
348 LoadCommandType type;
349 StringRef path;
350 uint32_t compatibilityVersion;
351 uint32_t currentVersion;
352 static uint32_t instanceCount;
353 };
354
355 uint32_t LCDylib::instanceCount = 0;
356
357 class LCLoadDylinker final : public LoadCommand {
358 public:
getSize() const359 uint32_t getSize() const override {
360 return alignTo(sizeof(dylinker_command) + path.size() + 1, 8);
361 }
362
writeTo(uint8_t * buf) const363 void writeTo(uint8_t *buf) const override {
364 auto *c = reinterpret_cast<dylinker_command *>(buf);
365 buf += sizeof(dylinker_command);
366
367 c->cmd = LC_LOAD_DYLINKER;
368 c->cmdsize = getSize();
369 c->name = sizeof(dylinker_command);
370
371 memcpy(buf, path.data(), path.size());
372 buf[path.size()] = '\0';
373 }
374
375 private:
376 // Recent versions of Darwin won't run any binary that has dyld at a
377 // different location.
378 const StringRef path = "/usr/lib/dyld";
379 };
380
381 class LCRPath final : public LoadCommand {
382 public:
LCRPath(StringRef path)383 explicit LCRPath(StringRef path) : path(path) {}
384
getSize() const385 uint32_t getSize() const override {
386 return alignTo(sizeof(rpath_command) + path.size() + 1, target->wordSize);
387 }
388
writeTo(uint8_t * buf) const389 void writeTo(uint8_t *buf) const override {
390 auto *c = reinterpret_cast<rpath_command *>(buf);
391 buf += sizeof(rpath_command);
392
393 c->cmd = LC_RPATH;
394 c->cmdsize = getSize();
395 c->path = sizeof(rpath_command);
396
397 memcpy(buf, path.data(), path.size());
398 buf[path.size()] = '\0';
399 }
400
401 private:
402 StringRef path;
403 };
404
405 class LCMinVersion final : public LoadCommand {
406 public:
LCMinVersion(const PlatformInfo & platformInfo)407 explicit LCMinVersion(const PlatformInfo &platformInfo)
408 : platformInfo(platformInfo) {}
409
getSize() const410 uint32_t getSize() const override { return sizeof(version_min_command); }
411
writeTo(uint8_t * buf) const412 void writeTo(uint8_t *buf) const override {
413 auto *c = reinterpret_cast<version_min_command *>(buf);
414 switch (platformInfo.target.Platform) {
415 case PlatformKind::macOS:
416 c->cmd = LC_VERSION_MIN_MACOSX;
417 break;
418 case PlatformKind::iOS:
419 case PlatformKind::iOSSimulator:
420 c->cmd = LC_VERSION_MIN_IPHONEOS;
421 break;
422 case PlatformKind::tvOS:
423 case PlatformKind::tvOSSimulator:
424 c->cmd = LC_VERSION_MIN_TVOS;
425 break;
426 case PlatformKind::watchOS:
427 case PlatformKind::watchOSSimulator:
428 c->cmd = LC_VERSION_MIN_WATCHOS;
429 break;
430 default:
431 llvm_unreachable("invalid platform");
432 break;
433 }
434 c->cmdsize = getSize();
435 c->version = encodeVersion(platformInfo.minimum);
436 c->sdk = encodeVersion(platformInfo.sdk);
437 }
438
439 private:
440 const PlatformInfo &platformInfo;
441 };
442
443 class LCBuildVersion final : public LoadCommand {
444 public:
LCBuildVersion(const PlatformInfo & platformInfo)445 explicit LCBuildVersion(const PlatformInfo &platformInfo)
446 : platformInfo(platformInfo) {}
447
448 const int ntools = 1;
449
getSize() const450 uint32_t getSize() const override {
451 return sizeof(build_version_command) + ntools * sizeof(build_tool_version);
452 }
453
writeTo(uint8_t * buf) const454 void writeTo(uint8_t *buf) const override {
455 auto *c = reinterpret_cast<build_version_command *>(buf);
456 c->cmd = LC_BUILD_VERSION;
457 c->cmdsize = getSize();
458 c->platform = static_cast<uint32_t>(platformInfo.target.Platform);
459 c->minos = encodeVersion(platformInfo.minimum);
460 c->sdk = encodeVersion(platformInfo.sdk);
461 c->ntools = ntools;
462 auto *t = reinterpret_cast<build_tool_version *>(&c[1]);
463 t->tool = TOOL_LD;
464 t->version = encodeVersion(VersionTuple(
465 LLVM_VERSION_MAJOR, LLVM_VERSION_MINOR, LLVM_VERSION_PATCH));
466 }
467
468 private:
469 const PlatformInfo &platformInfo;
470 };
471
472 // Stores a unique identifier for the output file based on an MD5 hash of its
473 // contents. In order to hash the contents, we must first write them, but
474 // LC_UUID itself must be part of the written contents in order for all the
475 // offsets to be calculated correctly. We resolve this circular paradox by
476 // first writing an LC_UUID with an all-zero UUID, then updating the UUID with
477 // its real value later.
478 class LCUuid final : public LoadCommand {
479 public:
getSize() const480 uint32_t getSize() const override { return sizeof(uuid_command); }
481
writeTo(uint8_t * buf) const482 void writeTo(uint8_t *buf) const override {
483 auto *c = reinterpret_cast<uuid_command *>(buf);
484 c->cmd = LC_UUID;
485 c->cmdsize = getSize();
486 uuidBuf = c->uuid;
487 }
488
writeUuid(uint64_t digest) const489 void writeUuid(uint64_t digest) const {
490 // xxhash only gives us 8 bytes, so put some fixed data in the other half.
491 static_assert(sizeof(uuid_command::uuid) == 16, "unexpected uuid size");
492 memcpy(uuidBuf, "LLD\xa1UU1D", 8);
493 memcpy(uuidBuf + 8, &digest, 8);
494
495 // RFC 4122 conformance. We need to fix 4 bits in byte 6 and 2 bits in
496 // byte 8. Byte 6 is already fine due to the fixed data we put in. We don't
497 // want to lose bits of the digest in byte 8, so swap that with a byte of
498 // fixed data that happens to have the right bits set.
499 std::swap(uuidBuf[3], uuidBuf[8]);
500
501 // Claim that this is an MD5-based hash. It isn't, but this signals that
502 // this is not a time-based and not a random hash. MD5 seems like the least
503 // bad lie we can put here.
504 assert((uuidBuf[6] & 0xf0) == 0x30 && "See RFC 4122 Sections 4.2.2, 4.1.3");
505 assert((uuidBuf[8] & 0xc0) == 0x80 && "See RFC 4122 Section 4.2.2");
506 }
507
508 mutable uint8_t *uuidBuf;
509 };
510
511 template <class LP> class LCEncryptionInfo final : public LoadCommand {
512 public:
getSize() const513 uint32_t getSize() const override {
514 return sizeof(typename LP::encryption_info_command);
515 }
516
writeTo(uint8_t * buf) const517 void writeTo(uint8_t *buf) const override {
518 using EncryptionInfo = typename LP::encryption_info_command;
519 auto *c = reinterpret_cast<EncryptionInfo *>(buf);
520 buf += sizeof(EncryptionInfo);
521 c->cmd = LP::encryptionInfoLCType;
522 c->cmdsize = getSize();
523 c->cryptoff = in.header->getSize();
524 auto it = find_if(outputSegments, [](const OutputSegment *seg) {
525 return seg->name == segment_names::text;
526 });
527 assert(it != outputSegments.end());
528 c->cryptsize = (*it)->fileSize - c->cryptoff;
529 }
530 };
531
532 class LCCodeSignature final : public LoadCommand {
533 public:
LCCodeSignature(CodeSignatureSection * section)534 LCCodeSignature(CodeSignatureSection *section) : section(section) {}
535
getSize() const536 uint32_t getSize() const override { return sizeof(linkedit_data_command); }
537
writeTo(uint8_t * buf) const538 void writeTo(uint8_t *buf) const override {
539 auto *c = reinterpret_cast<linkedit_data_command *>(buf);
540 c->cmd = LC_CODE_SIGNATURE;
541 c->cmdsize = getSize();
542 c->dataoff = static_cast<uint32_t>(section->fileOff);
543 c->datasize = section->getSize();
544 }
545
546 CodeSignatureSection *section;
547 };
548
549 } // namespace
550
treatSpecialUndefineds()551 void Writer::treatSpecialUndefineds() {
552 if (config->entry)
553 if (auto *undefined = dyn_cast<Undefined>(config->entry))
554 treatUndefinedSymbol(*undefined, "the entry point");
555
556 // FIXME: This prints symbols that are undefined both in input files and
557 // via -u flag twice.
558 for (const Symbol *sym : config->explicitUndefineds) {
559 if (const auto *undefined = dyn_cast<Undefined>(sym))
560 treatUndefinedSymbol(*undefined, "-u");
561 }
562 // Literal exported-symbol names must be defined, but glob
563 // patterns need not match.
564 for (const CachedHashStringRef &cachedName :
565 config->exportedSymbols.literals) {
566 if (const Symbol *sym = symtab->find(cachedName))
567 if (const auto *undefined = dyn_cast<Undefined>(sym))
568 treatUndefinedSymbol(*undefined, "-exported_symbol(s_list)");
569 }
570 }
571
572 // Add stubs and bindings where necessary (e.g. if the symbol is a
573 // DylibSymbol.)
prepareBranchTarget(Symbol * sym)574 static void prepareBranchTarget(Symbol *sym) {
575 if (auto *dysym = dyn_cast<DylibSymbol>(sym)) {
576 if (in.stubs->addEntry(dysym)) {
577 if (sym->isWeakDef()) {
578 in.binding->addEntry(dysym, in.lazyPointers->isec,
579 sym->stubsIndex * target->wordSize);
580 in.weakBinding->addEntry(sym, in.lazyPointers->isec,
581 sym->stubsIndex * target->wordSize);
582 } else {
583 in.lazyBinding->addEntry(dysym);
584 }
585 }
586 } else if (auto *defined = dyn_cast<Defined>(sym)) {
587 if (defined->isExternalWeakDef()) {
588 if (in.stubs->addEntry(sym)) {
589 in.rebase->addEntry(in.lazyPointers->isec,
590 sym->stubsIndex * target->wordSize);
591 in.weakBinding->addEntry(sym, in.lazyPointers->isec,
592 sym->stubsIndex * target->wordSize);
593 }
594 }
595 } else {
596 llvm_unreachable("invalid branch target symbol type");
597 }
598 }
599
600 // Can a symbol's address can only be resolved at runtime?
needsBinding(const Symbol * sym)601 static bool needsBinding(const Symbol *sym) {
602 if (isa<DylibSymbol>(sym))
603 return true;
604 if (const auto *defined = dyn_cast<Defined>(sym))
605 return defined->isExternalWeakDef();
606 return false;
607 }
608
prepareSymbolRelocation(Symbol * sym,const InputSection * isec,const Reloc & r)609 static void prepareSymbolRelocation(Symbol *sym, const InputSection *isec,
610 const Reloc &r) {
611 assert(sym->isLive());
612 const RelocAttrs &relocAttrs = target->getRelocAttrs(r.type);
613
614 if (relocAttrs.hasAttr(RelocAttrBits::BRANCH)) {
615 prepareBranchTarget(sym);
616 } else if (relocAttrs.hasAttr(RelocAttrBits::GOT)) {
617 if (relocAttrs.hasAttr(RelocAttrBits::POINTER) || needsBinding(sym))
618 in.got->addEntry(sym);
619 } else if (relocAttrs.hasAttr(RelocAttrBits::TLV)) {
620 if (needsBinding(sym))
621 in.tlvPointers->addEntry(sym);
622 } else if (relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) {
623 // References from thread-local variable sections are treated as offsets
624 // relative to the start of the referent section, and therefore have no
625 // need of rebase opcodes.
626 if (!(isThreadLocalVariables(isec->getFlags()) && isa<Defined>(sym)))
627 addNonLazyBindingEntries(sym, isec, r.offset, r.addend);
628 }
629 }
630
scanRelocations()631 void Writer::scanRelocations() {
632 TimeTraceScope timeScope("Scan relocations");
633
634 // This can't use a for-each loop: It calls treatUndefinedSymbol(), which can
635 // add to inputSections, which invalidates inputSections's iterators.
636 for (size_t i = 0; i < inputSections.size(); ++i) {
637 ConcatInputSection *isec = inputSections[i];
638
639 if (isec->shouldOmitFromOutput())
640 continue;
641
642 for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) {
643 Reloc &r = *it;
644 if (target->hasAttr(r.type, RelocAttrBits::SUBTRAHEND)) {
645 // Skip over the following UNSIGNED relocation -- it's just there as the
646 // minuend, and doesn't have the usual UNSIGNED semantics. We don't want
647 // to emit rebase opcodes for it.
648 it++;
649 continue;
650 }
651 if (auto *sym = r.referent.dyn_cast<Symbol *>()) {
652 if (auto *undefined = dyn_cast<Undefined>(sym))
653 treatUndefinedSymbol(*undefined);
654 // treatUndefinedSymbol() can replace sym with a DylibSymbol; re-check.
655 if (!isa<Undefined>(sym) && validateSymbolRelocation(sym, isec, r))
656 prepareSymbolRelocation(sym, isec, r);
657 } else {
658 // Canonicalize the referent so that later accesses in Writer won't
659 // have to worry about it. Perhaps we should do this for Defined::isec
660 // too...
661 auto *referentIsec = r.referent.get<InputSection *>();
662 r.referent = referentIsec->canonical();
663 if (!r.pcrel)
664 in.rebase->addEntry(isec, r.offset);
665 }
666 }
667 }
668
669 in.unwindInfo->prepareRelocations();
670 }
671
scanSymbols()672 void Writer::scanSymbols() {
673 TimeTraceScope timeScope("Scan symbols");
674 for (const Symbol *sym : symtab->getSymbols()) {
675 if (const auto *defined = dyn_cast<Defined>(sym)) {
676 if (defined->overridesWeakDef && defined->isLive())
677 in.weakBinding->addNonWeakDefinition(defined);
678 } else if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) {
679 // This branch intentionally doesn't check isLive().
680 if (dysym->isDynamicLookup())
681 continue;
682 dysym->getFile()->refState =
683 std::max(dysym->getFile()->refState, dysym->getRefState());
684 }
685 }
686 }
687
688 // TODO: ld64 enforces the old load commands in a few other cases.
useLCBuildVersion(const PlatformInfo & platformInfo)689 static bool useLCBuildVersion(const PlatformInfo &platformInfo) {
690 static const std::vector<std::pair<PlatformKind, VersionTuple>> minVersion = {
691 {PlatformKind::macOS, VersionTuple(10, 14)},
692 {PlatformKind::iOS, VersionTuple(12, 0)},
693 {PlatformKind::iOSSimulator, VersionTuple(13, 0)},
694 {PlatformKind::tvOS, VersionTuple(12, 0)},
695 {PlatformKind::tvOSSimulator, VersionTuple(13, 0)},
696 {PlatformKind::watchOS, VersionTuple(5, 0)},
697 {PlatformKind::watchOSSimulator, VersionTuple(6, 0)}};
698 auto it = llvm::find_if(minVersion, [&](const auto &p) {
699 return p.first == platformInfo.target.Platform;
700 });
701 return it == minVersion.end() ? true : platformInfo.minimum >= it->second;
702 }
703
createLoadCommands()704 template <class LP> void Writer::createLoadCommands() {
705 uint8_t segIndex = 0;
706 for (OutputSegment *seg : outputSegments) {
707 in.header->addLoadCommand(make<LCSegment<LP>>(seg->name, seg));
708 seg->index = segIndex++;
709 }
710
711 in.header->addLoadCommand(make<LCDyldInfo>(
712 in.rebase, in.binding, in.weakBinding, in.lazyBinding, in.exports));
713 in.header->addLoadCommand(make<LCSymtab>(symtabSection, stringTableSection));
714 in.header->addLoadCommand(
715 make<LCDysymtab>(symtabSection, indirectSymtabSection));
716 if (!config->umbrella.empty())
717 in.header->addLoadCommand(make<LCSubFramework>(config->umbrella));
718 if (config->emitEncryptionInfo)
719 in.header->addLoadCommand(make<LCEncryptionInfo<LP>>());
720 for (StringRef path : config->runtimePaths)
721 in.header->addLoadCommand(make<LCRPath>(path));
722
723 switch (config->outputType) {
724 case MH_EXECUTE:
725 in.header->addLoadCommand(make<LCLoadDylinker>());
726 break;
727 case MH_DYLIB:
728 in.header->addLoadCommand(make<LCDylib>(LC_ID_DYLIB, config->installName,
729 config->dylibCompatibilityVersion,
730 config->dylibCurrentVersion));
731 break;
732 case MH_BUNDLE:
733 break;
734 default:
735 llvm_unreachable("unhandled output file type");
736 }
737
738 uuidCommand = make<LCUuid>();
739 in.header->addLoadCommand(uuidCommand);
740
741 if (useLCBuildVersion(config->platformInfo))
742 in.header->addLoadCommand(make<LCBuildVersion>(config->platformInfo));
743 else
744 in.header->addLoadCommand(make<LCMinVersion>(config->platformInfo));
745
746 // This is down here to match ld64's load command order.
747 if (config->outputType == MH_EXECUTE)
748 in.header->addLoadCommand(make<LCMain>());
749
750 int64_t dylibOrdinal = 1;
751 DenseMap<StringRef, int64_t> ordinalForInstallName;
752 for (InputFile *file : inputFiles) {
753 if (auto *dylibFile = dyn_cast<DylibFile>(file)) {
754 if (dylibFile->isBundleLoader) {
755 dylibFile->ordinal = BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE;
756 // Shortcut since bundle-loader does not re-export the symbols.
757
758 dylibFile->reexport = false;
759 continue;
760 }
761
762 // Don't emit load commands for a dylib that is not referenced if:
763 // - it was added implicitly (via a reexport, an LC_LOAD_DYLINKER --
764 // if it's on the linker command line, it's explicit)
765 // - or it's marked MH_DEAD_STRIPPABLE_DYLIB
766 // - or the flag -dead_strip_dylibs is used
767 // FIXME: `isReferenced()` is currently computed before dead code
768 // stripping, so references from dead code keep a dylib alive. This
769 // matches ld64, but it's something we should do better.
770 if (!dylibFile->isReferenced() && !dylibFile->forceNeeded &&
771 (!dylibFile->explicitlyLinked || dylibFile->deadStrippable ||
772 config->deadStripDylibs))
773 continue;
774
775 // Several DylibFiles can have the same installName. Only emit a single
776 // load command for that installName and give all these DylibFiles the
777 // same ordinal.
778 // This can happen in several cases:
779 // - a new framework could change its installName to an older
780 // framework name via an $ld$ symbol depending on platform_version
781 // - symlinks (for example, libpthread.tbd is a symlink to libSystem.tbd;
782 // Foo.framework/Foo.tbd is usually a symlink to
783 // Foo.framework/Versions/Current/Foo.tbd, where
784 // Foo.framework/Versions/Current is usually a symlink to
785 // Foo.framework/Versions/A)
786 // - a framework can be linked both explicitly on the linker
787 // command line and implicitly as a reexport from a different
788 // framework. The re-export will usually point to the tbd file
789 // in Foo.framework/Versions/A/Foo.tbd, while the explicit link will
790 // usually find Foo.framework/Foo.tbd. These are usually symlinks,
791 // but in a --reproduce archive they will be identical but distinct
792 // files.
793 // In the first case, *semantically distinct* DylibFiles will have the
794 // same installName.
795 int64_t &ordinal = ordinalForInstallName[dylibFile->installName];
796 if (ordinal) {
797 dylibFile->ordinal = ordinal;
798 continue;
799 }
800
801 ordinal = dylibFile->ordinal = dylibOrdinal++;
802 LoadCommandType lcType =
803 dylibFile->forceWeakImport || dylibFile->refState == RefState::Weak
804 ? LC_LOAD_WEAK_DYLIB
805 : LC_LOAD_DYLIB;
806 in.header->addLoadCommand(make<LCDylib>(lcType, dylibFile->installName,
807 dylibFile->compatibilityVersion,
808 dylibFile->currentVersion));
809
810 if (dylibFile->reexport)
811 in.header->addLoadCommand(
812 make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->installName));
813 }
814 }
815
816 if (functionStartsSection)
817 in.header->addLoadCommand(make<LCFunctionStarts>(functionStartsSection));
818 if (dataInCodeSection)
819 in.header->addLoadCommand(make<LCDataInCode>(dataInCodeSection));
820 if (codeSignatureSection)
821 in.header->addLoadCommand(make<LCCodeSignature>(codeSignatureSection));
822
823 const uint32_t MACOS_MAXPATHLEN = 1024;
824 config->headerPad = std::max(
825 config->headerPad, (config->headerPadMaxInstallNames
826 ? LCDylib::getInstanceCount() * MACOS_MAXPATHLEN
827 : 0));
828 }
829
getSymbolPriority(const SymbolPriorityEntry & entry,const InputFile * f)830 static size_t getSymbolPriority(const SymbolPriorityEntry &entry,
831 const InputFile *f) {
832 // We don't use toString(InputFile *) here because it returns the full path
833 // for object files, and we only want the basename.
834 StringRef filename;
835 if (f->archiveName.empty())
836 filename = path::filename(f->getName());
837 else
838 filename = saver.save(path::filename(f->archiveName) + "(" +
839 path::filename(f->getName()) + ")");
840 return std::max(entry.objectFiles.lookup(filename), entry.anyObjectFile);
841 }
842
843 // Each section gets assigned the priority of the highest-priority symbol it
844 // contains.
buildInputSectionPriorities()845 static DenseMap<const InputSection *, size_t> buildInputSectionPriorities() {
846 DenseMap<const InputSection *, size_t> sectionPriorities;
847
848 if (config->priorities.empty())
849 return sectionPriorities;
850
851 auto addSym = [&](Defined &sym) {
852 if (sym.isAbsolute())
853 return;
854
855 auto it = config->priorities.find(sym.getName());
856 if (it == config->priorities.end())
857 return;
858
859 SymbolPriorityEntry &entry = it->second;
860 size_t &priority = sectionPriorities[sym.isec];
861 priority =
862 std::max(priority, getSymbolPriority(entry, sym.isec->getFile()));
863 };
864
865 // TODO: Make sure this handles weak symbols correctly.
866 for (const InputFile *file : inputFiles) {
867 if (isa<ObjFile>(file))
868 for (Symbol *sym : file->symbols)
869 if (auto *d = dyn_cast_or_null<Defined>(sym))
870 addSym(*d);
871 }
872
873 return sectionPriorities;
874 }
875
876 // Sorting only can happen once all outputs have been collected. Here we sort
877 // segments, output sections within each segment, and input sections within each
878 // output segment.
sortSegmentsAndSections()879 static void sortSegmentsAndSections() {
880 TimeTraceScope timeScope("Sort segments and sections");
881 sortOutputSegments();
882
883 DenseMap<const InputSection *, size_t> isecPriorities =
884 buildInputSectionPriorities();
885
886 uint32_t sectionIndex = 0;
887 for (OutputSegment *seg : outputSegments) {
888 seg->sortOutputSections();
889 for (OutputSection *osec : seg->getSections()) {
890 // Now that the output sections are sorted, assign the final
891 // output section indices.
892 if (!osec->isHidden())
893 osec->index = ++sectionIndex;
894 if (!firstTLVDataSection && isThreadLocalData(osec->flags))
895 firstTLVDataSection = osec;
896
897 if (!isecPriorities.empty()) {
898 if (auto *merged = dyn_cast<ConcatOutputSection>(osec)) {
899 llvm::stable_sort(merged->inputs,
900 [&](InputSection *a, InputSection *b) {
901 return isecPriorities[a] > isecPriorities[b];
902 });
903 }
904 }
905 }
906 }
907 }
908
createOutputSections()909 template <class LP> void Writer::createOutputSections() {
910 TimeTraceScope timeScope("Create output sections");
911 // First, create hidden sections
912 stringTableSection = make<StringTableSection>();
913 symtabSection = makeSymtabSection<LP>(*stringTableSection);
914 indirectSymtabSection = make<IndirectSymtabSection>();
915 if (config->adhocCodesign)
916 codeSignatureSection = make<CodeSignatureSection>();
917 if (config->emitDataInCodeInfo)
918 dataInCodeSection = make<DataInCodeSection>();
919 if (config->emitFunctionStarts)
920 functionStartsSection = make<FunctionStartsSection>();
921 if (config->emitBitcodeBundle)
922 make<BitcodeBundleSection>();
923
924 switch (config->outputType) {
925 case MH_EXECUTE:
926 make<PageZeroSection>();
927 break;
928 case MH_DYLIB:
929 case MH_BUNDLE:
930 break;
931 default:
932 llvm_unreachable("unhandled output file type");
933 }
934
935 // Then add input sections to output sections.
936 for (ConcatInputSection *isec : inputSections) {
937 if (isec->shouldOmitFromOutput())
938 continue;
939 ConcatOutputSection *osec = cast<ConcatOutputSection>(isec->parent);
940 osec->addInput(isec);
941 osec->inputOrder =
942 std::min(osec->inputOrder, static_cast<int>(isec->outSecOff));
943 }
944
945 // Once all the inputs are added, we can finalize the output section
946 // properties and create the corresponding output segments.
947 for (const auto &it : concatOutputSections) {
948 StringRef segname = it.first.first;
949 ConcatOutputSection *osec = it.second;
950 assert(segname != segment_names::ld);
951 if (osec->isNeeded())
952 getOrCreateOutputSegment(segname)->addOutputSection(osec);
953 }
954
955 for (SyntheticSection *ssec : syntheticSections) {
956 auto it = concatOutputSections.find({ssec->segname, ssec->name});
957 if (ssec->isNeeded()) {
958 if (it == concatOutputSections.end()) {
959 getOrCreateOutputSegment(ssec->segname)->addOutputSection(ssec);
960 } else {
961 fatal("section from " +
962 toString(it->second->firstSection()->getFile()) +
963 " conflicts with synthetic section " + ssec->segname + "," +
964 ssec->name);
965 }
966 }
967 }
968
969 // dyld requires __LINKEDIT segment to always exist (even if empty).
970 linkEditSegment = getOrCreateOutputSegment(segment_names::linkEdit);
971 }
972
finalizeAddresses()973 void Writer::finalizeAddresses() {
974 TimeTraceScope timeScope("Finalize addresses");
975 uint64_t pageSize = target->getPageSize();
976 // Ensure that segments (and the sections they contain) are allocated
977 // addresses in ascending order, which dyld requires.
978 //
979 // Note that at this point, __LINKEDIT sections are empty, but we need to
980 // determine addresses of other segments/sections before generating its
981 // contents.
982 for (OutputSegment *seg : outputSegments) {
983 if (seg == linkEditSegment)
984 continue;
985 seg->addr = addr;
986 assignAddresses(seg);
987 // codesign / libstuff checks for segment ordering by verifying that
988 // `fileOff + fileSize == next segment fileOff`. So we call alignTo() before
989 // (instead of after) computing fileSize to ensure that the segments are
990 // contiguous. We handle addr / vmSize similarly for the same reason.
991 fileOff = alignTo(fileOff, pageSize);
992 addr = alignTo(addr, pageSize);
993 seg->vmSize = addr - seg->addr;
994 seg->fileSize = fileOff - seg->fileOff;
995 seg->assignAddressesToStartEndSymbols();
996 }
997 }
998
finalizeLinkEditSegment()999 void Writer::finalizeLinkEditSegment() {
1000 TimeTraceScope timeScope("Finalize __LINKEDIT segment");
1001 // Fill __LINKEDIT contents.
1002 std::vector<LinkEditSection *> linkEditSections{
1003 in.rebase,
1004 in.binding,
1005 in.weakBinding,
1006 in.lazyBinding,
1007 in.exports,
1008 symtabSection,
1009 indirectSymtabSection,
1010 dataInCodeSection,
1011 functionStartsSection,
1012 };
1013 parallelForEach(linkEditSections, [](LinkEditSection *osec) {
1014 if (osec)
1015 osec->finalizeContents();
1016 });
1017
1018 // Now that __LINKEDIT is filled out, do a proper calculation of its
1019 // addresses and offsets.
1020 linkEditSegment->addr = addr;
1021 assignAddresses(linkEditSegment);
1022 // No need to page-align fileOff / addr here since this is the last segment.
1023 linkEditSegment->vmSize = addr - linkEditSegment->addr;
1024 linkEditSegment->fileSize = fileOff - linkEditSegment->fileOff;
1025 }
1026
assignAddresses(OutputSegment * seg)1027 void Writer::assignAddresses(OutputSegment *seg) {
1028 seg->fileOff = fileOff;
1029
1030 for (OutputSection *osec : seg->getSections()) {
1031 if (!osec->isNeeded())
1032 continue;
1033 addr = alignTo(addr, osec->align);
1034 fileOff = alignTo(fileOff, osec->align);
1035 osec->addr = addr;
1036 osec->fileOff = isZeroFill(osec->flags) ? 0 : fileOff;
1037 osec->finalize();
1038 osec->assignAddressesToStartEndSymbols();
1039
1040 addr += osec->getSize();
1041 fileOff += osec->getFileSize();
1042 }
1043 }
1044
openFile()1045 void Writer::openFile() {
1046 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
1047 FileOutputBuffer::create(config->outputFile, fileOff,
1048 FileOutputBuffer::F_executable);
1049
1050 if (!bufferOrErr)
1051 error("failed to open " + config->outputFile + ": " +
1052 llvm::toString(bufferOrErr.takeError()));
1053 else
1054 buffer = std::move(*bufferOrErr);
1055 }
1056
writeSections()1057 void Writer::writeSections() {
1058 uint8_t *buf = buffer->getBufferStart();
1059 for (const OutputSegment *seg : outputSegments)
1060 for (const OutputSection *osec : seg->getSections())
1061 osec->writeTo(buf + osec->fileOff);
1062 }
1063
1064 // In order to utilize multiple cores, we first split the buffer into chunks,
1065 // compute a hash for each chunk, and then compute a hash value of the hash
1066 // values.
writeUuid()1067 void Writer::writeUuid() {
1068 TimeTraceScope timeScope("Computing UUID");
1069 ArrayRef<uint8_t> data{buffer->getBufferStart(), buffer->getBufferEnd()};
1070 unsigned chunkCount = parallel::strategy.compute_thread_count() * 10;
1071 // Round-up integer division
1072 size_t chunkSize = (data.size() + chunkCount - 1) / chunkCount;
1073 std::vector<ArrayRef<uint8_t>> chunks = split(data, chunkSize);
1074 std::vector<uint64_t> hashes(chunks.size());
1075 parallelForEachN(0, chunks.size(),
1076 [&](size_t i) { hashes[i] = xxHash64(chunks[i]); });
1077 uint64_t digest = xxHash64({reinterpret_cast<uint8_t *>(hashes.data()),
1078 hashes.size() * sizeof(uint64_t)});
1079 uuidCommand->writeUuid(digest);
1080 }
1081
writeCodeSignature()1082 void Writer::writeCodeSignature() {
1083 if (codeSignatureSection)
1084 codeSignatureSection->writeHashes(buffer->getBufferStart());
1085 }
1086
writeOutputFile()1087 void Writer::writeOutputFile() {
1088 TimeTraceScope timeScope("Write output file");
1089 openFile();
1090 if (errorCount())
1091 return;
1092 writeSections();
1093 writeUuid();
1094 writeCodeSignature();
1095
1096 if (auto e = buffer->commit())
1097 error("failed to write to the output file: " + toString(std::move(e)));
1098 }
1099
run()1100 template <class LP> void Writer::run() {
1101 treatSpecialUndefineds();
1102 if (config->entry && !isa<Undefined>(config->entry))
1103 prepareBranchTarget(config->entry);
1104 scanRelocations();
1105 if (in.stubHelper->isNeeded())
1106 in.stubHelper->setup();
1107 scanSymbols();
1108 createOutputSections<LP>();
1109 // After this point, we create no new segments; HOWEVER, we might
1110 // yet create branch-range extension thunks for architectures whose
1111 // hardware call instructions have limited range, e.g., ARM(64).
1112 // The thunks are created as InputSections interspersed among
1113 // the ordinary __TEXT,_text InputSections.
1114 sortSegmentsAndSections();
1115 createLoadCommands<LP>();
1116 finalizeAddresses();
1117 finalizeLinkEditSegment();
1118 writeMapFile();
1119 writeOutputFile();
1120 }
1121
writeResult()1122 template <class LP> void macho::writeResult() { Writer().run<LP>(); }
1123
createSyntheticSections()1124 void macho::createSyntheticSections() {
1125 in.header = make<MachHeaderSection>();
1126 if (config->dedupLiterals) {
1127 in.cStringSection = make<DeduplicatedCStringSection>();
1128 } else {
1129 in.cStringSection = make<CStringSection>();
1130 }
1131 in.wordLiteralSection =
1132 config->dedupLiterals ? make<WordLiteralSection>() : nullptr;
1133 in.rebase = make<RebaseSection>();
1134 in.binding = make<BindingSection>();
1135 in.weakBinding = make<WeakBindingSection>();
1136 in.lazyBinding = make<LazyBindingSection>();
1137 in.exports = make<ExportSection>();
1138 in.got = make<GotSection>();
1139 in.tlvPointers = make<TlvPointerSection>();
1140 in.lazyPointers = make<LazyPointerSection>();
1141 in.stubs = make<StubsSection>();
1142 in.stubHelper = make<StubHelperSection>();
1143 in.unwindInfo = makeUnwindInfoSection();
1144
1145 // This section contains space for just a single word, and will be used by
1146 // dyld to cache an address to the image loader it uses.
1147 uint8_t *arr = bAlloc.Allocate<uint8_t>(target->wordSize);
1148 memset(arr, 0, target->wordSize);
1149 in.imageLoaderCache = make<ConcatInputSection>(
1150 segment_names::data, section_names::data, /*file=*/nullptr,
1151 ArrayRef<uint8_t>{arr, target->wordSize},
1152 /*align=*/target->wordSize, /*flags=*/S_REGULAR);
1153 // References from dyld are not visible to us, so ensure this section is
1154 // always treated as live.
1155 in.imageLoaderCache->live = true;
1156 }
1157
1158 OutputSection *macho::firstTLVDataSection = nullptr;
1159
1160 template void macho::writeResult<LP64>();
1161 template void macho::writeResult<ILP32>();
1162