1//===- Driver.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 "Driver.h"
10#include "Config.h"
11#include "ICF.h"
12#include "InputFiles.h"
13#include "LTO.h"
14#include "MarkLive.h"
15#include "ObjC.h"
16#include "OutputSection.h"
17#include "OutputSegment.h"
18#include "SectionPriorities.h"
19#include "SymbolTable.h"
20#include "Symbols.h"
21#include "SyntheticSections.h"
22#include "Target.h"
23#include "UnwindInfoSection.h"
24#include "Writer.h"
25
26#include "lld/Common/Args.h"
27#include "lld/Common/CommonLinkerContext.h"
28#include "lld/Common/ErrorHandler.h"
29#include "lld/Common/LLVM.h"
30#include "lld/Common/Memory.h"
31#include "lld/Common/Reproduce.h"
32#include "lld/Common/Version.h"
33#include "llvm/ADT/DenseSet.h"
34#include "llvm/ADT/StringExtras.h"
35#include "llvm/ADT/StringRef.h"
36#include "llvm/BinaryFormat/MachO.h"
37#include "llvm/BinaryFormat/Magic.h"
38#include "llvm/CGData/CodeGenDataWriter.h"
39#include "llvm/Config/llvm-config.h"
40#include "llvm/LTO/LTO.h"
41#include "llvm/Object/Archive.h"
42#include "llvm/Option/ArgList.h"
43#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/Debug.h"
45#include "llvm/Support/FileSystem.h"
46#include "llvm/Support/Parallel.h"
47#include "llvm/Support/Path.h"
48#include "llvm/Support/Process.h"
49#include "llvm/Support/TarWriter.h"
50#include "llvm/Support/TargetSelect.h"
51#include "llvm/Support/Threading.h"
52#include "llvm/Support/TimeProfiler.h"
53#include "llvm/TargetParser/Host.h"
54#include "llvm/TextAPI/Architecture.h"
55#include "llvm/TextAPI/PackedVersion.h"
56
57#if !_WIN32
58#include <sys/mman.h>
59#endif
60
61using namespace llvm;
62using namespace llvm::MachO;
63using namespace llvm::object;
64using namespace llvm::opt;
65using namespace llvm::sys;
66using namespace lld;
67using namespace lld::macho;
68
69std::unique_ptr<Configuration> macho::config;
70std::unique_ptr<DependencyTracker> macho::depTracker;
71
72static HeaderFileType getOutputType(const InputArgList &args) {
73 // TODO: -r, -dylinker, -preload...
74 Arg *outputArg = args.getLastArg(Ids: OPT_bundle, Ids: OPT_dylib, Ids: OPT_execute);
75 if (outputArg == nullptr)
76 return MH_EXECUTE;
77
78 switch (outputArg->getOption().getID()) {
79 case OPT_bundle:
80 return MH_BUNDLE;
81 case OPT_dylib:
82 return MH_DYLIB;
83 case OPT_execute:
84 return MH_EXECUTE;
85 default:
86 llvm_unreachable("internal error");
87 }
88}
89
90static DenseMap<CachedHashStringRef, StringRef> resolvedLibraries;
91static std::optional<StringRef> findLibrary(StringRef name) {
92 CachedHashStringRef key(name);
93 auto entry = resolvedLibraries.find(Val: key);
94 if (entry != resolvedLibraries.end())
95 return entry->second;
96
97 auto doFind = [&] {
98 // Special case for Csu support files required for Mac OS X 10.7 and older
99 // (crt1.o)
100 if (name.ends_with(Suffix: ".o"))
101 return findPathCombination(name, roots: config->librarySearchPaths, extensions: {""});
102 if (config->searchDylibsFirst) {
103 if (std::optional<StringRef> path =
104 findPathCombination(name: "lib" + name, roots: config->librarySearchPaths,
105 extensions: {".tbd", ".dylib", ".so"}))
106 return path;
107 return findPathCombination(name: "lib" + name, roots: config->librarySearchPaths,
108 extensions: {".a"});
109 }
110 return findPathCombination(name: "lib" + name, roots: config->librarySearchPaths,
111 extensions: {".tbd", ".dylib", ".so", ".a"});
112 };
113
114 std::optional<StringRef> path = doFind();
115 if (path)
116 resolvedLibraries[key] = *path;
117
118 return path;
119}
120
121static DenseMap<CachedHashStringRef, StringRef> resolvedFrameworks;
122static std::optional<StringRef> findFramework(StringRef name) {
123 CachedHashStringRef key(name);
124 auto entry = resolvedFrameworks.find(Val: key);
125 if (entry != resolvedFrameworks.end())
126 return entry->second;
127
128 SmallString<260> symlink;
129 StringRef suffix;
130 std::tie(args&: name, args&: suffix) = name.split(Separator: ",");
131 for (StringRef dir : config->frameworkSearchPaths) {
132 symlink = dir;
133 path::append(path&: symlink, a: name + ".framework", b: name);
134
135 if (!suffix.empty()) {
136 // NOTE: we must resolve the symlink before trying the suffixes, because
137 // there are no symlinks for the suffixed paths.
138 SmallString<260> location;
139 if (!fs::real_path(path: symlink, output&: location)) {
140 // only append suffix if realpath() succeeds
141 Twine suffixed = location + suffix;
142 if (fs::exists(Path: suffixed))
143 return resolvedFrameworks[key] = saver().save(S: suffixed.str());
144 }
145 // Suffix lookup failed, fall through to the no-suffix case.
146 }
147
148 if (std::optional<StringRef> path = resolveDylibPath(path: symlink.str()))
149 return resolvedFrameworks[key] = *path;
150 }
151 return {};
152}
153
154static bool warnIfNotDirectory(StringRef option, StringRef path) {
155 if (!fs::exists(Path: path)) {
156 warn(msg: "directory not found for option -" + option + path);
157 return false;
158 } else if (!fs::is_directory(Path: path)) {
159 warn(msg: "option -" + option + path + " references a non-directory path");
160 return false;
161 }
162 return true;
163}
164
165static std::vector<StringRef>
166getSearchPaths(unsigned optionCode, InputArgList &args,
167 const std::vector<StringRef> &roots,
168 const SmallVector<StringRef, 2> &systemPaths) {
169 std::vector<StringRef> paths;
170 StringRef optionLetter{optionCode == OPT_F ? "F" : "L"};
171 for (StringRef path : args::getStrings(args, id: optionCode)) {
172 // NOTE: only absolute paths are re-rooted to syslibroot(s)
173 bool found = false;
174 if (path::is_absolute(path, style: path::Style::posix)) {
175 for (StringRef root : roots) {
176 SmallString<261> buffer(root);
177 path::append(path&: buffer, a: path);
178 // Do not warn about paths that are computed via the syslib roots
179 if (fs::is_directory(Path: buffer)) {
180 paths.push_back(x: saver().save(S: buffer.str()));
181 found = true;
182 }
183 }
184 }
185 if (!found && warnIfNotDirectory(option: optionLetter, path))
186 paths.push_back(x: path);
187 }
188
189 // `-Z` suppresses the standard "system" search paths.
190 if (args.hasArg(Ids: OPT_Z))
191 return paths;
192
193 for (const StringRef &path : systemPaths) {
194 for (const StringRef &root : roots) {
195 SmallString<261> buffer(root);
196 path::append(path&: buffer, a: path);
197 if (fs::is_directory(Path: buffer))
198 paths.push_back(x: saver().save(S: buffer.str()));
199 }
200 }
201 return paths;
202}
203
204static std::vector<StringRef> getSystemLibraryRoots(InputArgList &args) {
205 std::vector<StringRef> roots;
206 for (const Arg *arg : args.filtered(Ids: OPT_syslibroot))
207 roots.push_back(x: arg->getValue());
208 // NOTE: the final `-syslibroot` being `/` will ignore all roots
209 if (!roots.empty() && roots.back() == "/")
210 roots.clear();
211 // NOTE: roots can never be empty - add an empty root to simplify the library
212 // and framework search path computation.
213 if (roots.empty())
214 roots.emplace_back(args: "");
215 return roots;
216}
217
218static std::vector<StringRef>
219getLibrarySearchPaths(InputArgList &args, const std::vector<StringRef> &roots) {
220 return getSearchPaths(optionCode: OPT_L, args, roots, systemPaths: {"/usr/lib", "/usr/local/lib"});
221}
222
223static std::vector<StringRef>
224getFrameworkSearchPaths(InputArgList &args,
225 const std::vector<StringRef> &roots) {
226 return getSearchPaths(optionCode: OPT_F, args, roots,
227 systemPaths: {"/Library/Frameworks", "/System/Library/Frameworks"});
228}
229
230static llvm::CachePruningPolicy getLTOCachePolicy(InputArgList &args) {
231 SmallString<128> ltoPolicy;
232 auto add = [&ltoPolicy](Twine val) {
233 if (!ltoPolicy.empty())
234 ltoPolicy += ":";
235 val.toVector(Out&: ltoPolicy);
236 };
237 for (const Arg *arg :
238 args.filtered(Ids: OPT_thinlto_cache_policy_eq, Ids: OPT_prune_interval_lto,
239 Ids: OPT_prune_after_lto, Ids: OPT_max_relative_cache_size_lto)) {
240 switch (arg->getOption().getID()) {
241 case OPT_thinlto_cache_policy_eq:
242 add(arg->getValue());
243 break;
244 case OPT_prune_interval_lto:
245 if (!strcmp(s1: "-1", s2: arg->getValue()))
246 add("prune_interval=87600h"); // 10 years
247 else
248 add(Twine("prune_interval=") + arg->getValue() + "s");
249 break;
250 case OPT_prune_after_lto:
251 add(Twine("prune_after=") + arg->getValue() + "s");
252 break;
253 case OPT_max_relative_cache_size_lto:
254 add(Twine("cache_size=") + arg->getValue() + "%");
255 break;
256 }
257 }
258 return CHECK(parseCachePruningPolicy(ltoPolicy), "invalid LTO cache policy");
259}
260
261// What caused a given library to be loaded. Only relevant for archives.
262// Note that this does not tell us *how* we should load the library, i.e.
263// whether we should do it lazily or eagerly (AKA force loading). The "how" is
264// decided within addFile().
265enum class LoadType {
266 CommandLine, // Library was passed as a regular CLI argument
267 CommandLineForce, // Library was passed via `-force_load`
268 LCLinkerOption, // Library was passed via LC_LINKER_OPTIONS
269};
270
271struct ArchiveFileInfo {
272 ArchiveFile *file;
273 bool isCommandLineLoad;
274};
275
276static DenseMap<StringRef, ArchiveFileInfo> loadedArchives;
277
278static void saveThinArchiveToRepro(ArchiveFile const *file) {
279 assert(tar && file->getArchive().isThin());
280
281 Error e = Error::success();
282 for (const object::Archive::Child &c : file->getArchive().children(Err&: e)) {
283 MemoryBufferRef mb = CHECK(c.getMemoryBufferRef(),
284 toString(file) + ": failed to get buffer");
285 tar->append(Path: relativeToRoot(CHECK(c.getFullName(), file)), Data: mb.getBuffer());
286 }
287 if (e)
288 error(msg: toString(file) +
289 ": Archive::children failed: " + toString(E: std::move(e)));
290}
291
292struct DeferredFile {
293 StringRef path;
294 bool isLazy;
295 MemoryBufferRef buffer;
296};
297using DeferredFiles = std::vector<DeferredFile>;
298
299#if LLVM_ENABLE_THREADS
300class SerialBackgroundWorkQueue {
301 std::deque<std::function<void()>> queue;
302 std::thread *running;
303 std::mutex mutex;
304
305public:
306 std::atomic_bool stopAllWork = false;
307 void queueWork(std::function<void()> work) {
308 mutex.lock();
309 if (running && queue.empty()) {
310 mutex.unlock();
311 running->join();
312 mutex.lock();
313 delete running;
314 running = nullptr;
315 }
316
317 if (work) {
318 queue.emplace_back(args: std::move(work));
319 if (!running)
320 running = new std::thread([&]() {
321 while (!stopAllWork) {
322 mutex.lock();
323 if (queue.empty()) {
324 mutex.unlock();
325 break;
326 }
327 auto work = std::move(queue.front());
328 mutex.unlock();
329 work();
330 mutex.lock();
331 queue.pop_front();
332 mutex.unlock();
333 }
334 });
335 }
336 mutex.unlock();
337 }
338};
339
340static SerialBackgroundWorkQueue pageInQueue;
341
342// Most input files have been mapped but not yet paged in.
343// This code forces the page-ins on multiple threads so
344// the process is not stalled waiting on disk buffer i/o.
345void multiThreadedPageInBackground(DeferredFiles &deferred) {
346 static const size_t pageSize = Process::getPageSizeEstimate();
347 static const size_t largeArchive = 10 * 1024 * 1024;
348#ifndef NDEBUG
349 using namespace std::chrono;
350 static std::atomic_uint64_t totalBytes = 0;
351 std::atomic_int numDeferedFilesAdvised = 0;
352 auto t0 = high_resolution_clock::now();
353#endif
354
355 auto preloadDeferredFile = [&](const DeferredFile &deferredFile) {
356 const StringRef &buff = deferredFile.buffer.getBuffer();
357 if (buff.size() > largeArchive)
358 return;
359
360#ifndef NDEBUG
361 totalBytes += buff.size();
362 numDeferedFilesAdvised += 1;
363#endif
364#if _WIN32
365 // Reference all file's mmap'd pages to load them into memory.
366 for (const char *page = buff.data(), *end = page + buff.size();
367 page < end && !pageInQueue.stopAllWork; page += pageSize) {
368 [[maybe_unused]] volatile char t = *page;
369 (void)t;
370 }
371#else
372#define DEBUG_TYPE "lld-madvise"
373 auto aligned =
374 llvm::alignDown(Value: reinterpret_cast<uintptr_t>(buff.data()), Align: pageSize);
375 if (madvise(addr: (void *)aligned, len: buff.size(), MADV_WILLNEED) < 0)
376 LLVM_DEBUG(llvm::dbgs() << "madvise error: " << strerror(errno) << "\n");
377#undef DEBUG_TYPE
378#endif
379 };
380
381 { // Create scope for waiting for the taskGroup
382 std::atomic_size_t index = 0;
383 llvm::parallel::TaskGroup taskGroup;
384 for (int w = 0; w < config->readWorkers; w++)
385 taskGroup.spawn(f: [&index, &preloadDeferredFile, &deferred]() {
386 while (!pageInQueue.stopAllWork) {
387 size_t localIndex = index.fetch_add(i: 1);
388 if (localIndex >= deferred.size())
389 break;
390 preloadDeferredFile(deferred[localIndex]);
391 }
392 });
393 }
394
395#ifndef NDEBUG
396 auto dt = high_resolution_clock::now() - t0;
397 if (Process::GetEnv("LLD_MULTI_THREAD_PAGE"))
398 llvm::dbgs() << "multiThreadedPageIn " << totalBytes << "/"
399 << numDeferedFilesAdvised << "/" << deferred.size() << "/"
400 << duration_cast<milliseconds>(dt).count() / 1000. << "\n";
401#endif
402}
403
404static void multiThreadedPageIn(const DeferredFiles &deferred) {
405 pageInQueue.queueWork(work: [=]() {
406 DeferredFiles files = deferred;
407 multiThreadedPageInBackground(deferred&: files);
408 });
409}
410#endif
411
412static InputFile *processFile(std::optional<MemoryBufferRef> buffer,
413 DeferredFiles *archiveContents, StringRef path,
414 LoadType loadType, bool isLazy = false,
415 bool isExplicit = true,
416 bool isBundleLoader = false,
417 bool isForceHidden = false) {
418 if (!buffer)
419 return nullptr;
420 MemoryBufferRef mbref = *buffer;
421 InputFile *newFile = nullptr;
422
423 file_magic magic = identify_magic(magic: mbref.getBuffer());
424 switch (magic) {
425 case file_magic::archive: {
426 bool isCommandLineLoad = loadType != LoadType::LCLinkerOption;
427 // Avoid loading archives twice. If the archives are being force-loaded,
428 // loading them twice would create duplicate symbol errors. In the
429 // non-force-loading case, this is just a minor performance optimization.
430 // We don't take a reference to cachedFile here because the
431 // loadArchiveMember() call below may recursively call addFile() and
432 // invalidate this reference.
433 auto entry = loadedArchives.find(Val: path);
434
435 ArchiveFile *file;
436 if (entry == loadedArchives.end()) {
437 // No cached archive, we need to create a new one
438 std::unique_ptr<object::Archive> archive = CHECK(
439 object::Archive::create(mbref), path + ": failed to parse archive");
440
441 file = make<ArchiveFile>(args: std::move(archive), args&: isForceHidden);
442
443 if (tar && file->getArchive().isThin())
444 saveThinArchiveToRepro(file);
445 } else {
446 file = entry->second.file;
447 // Command-line loads take precedence. If file is previously loaded via
448 // command line, or is loaded via LC_LINKER_OPTION and being loaded via
449 // LC_LINKER_OPTION again, using the cached archive is enough.
450 if (entry->second.isCommandLineLoad || !isCommandLineLoad)
451 return file;
452 }
453
454 bool isLCLinkerForceLoad = loadType == LoadType::LCLinkerOption &&
455 config->forceLoadSwift &&
456 path::filename(path).starts_with(Prefix: "libswift");
457 if ((isCommandLineLoad && config->allLoad) ||
458 loadType == LoadType::CommandLineForce || isLCLinkerForceLoad) {
459 if (readFile(path)) {
460 Error e = Error::success();
461 for (const object::Archive::Child &c : file->getArchive().children(Err&: e)) {
462 StringRef reason;
463 switch (loadType) {
464 case LoadType::LCLinkerOption:
465 reason = "LC_LINKER_OPTION";
466 break;
467 case LoadType::CommandLineForce:
468 reason = "-force_load";
469 break;
470 case LoadType::CommandLine:
471 reason = "-all_load";
472 break;
473 }
474 if (Error e = file->fetch(c, reason)) {
475 if (config->warnThinArchiveMissingMembers)
476 warn(msg: toString(file) + ": " + reason +
477 " failed to load archive member: " + toString(E: std::move(e)));
478 else
479 llvm::consumeError(Err: std::move(e));
480 }
481 }
482 if (e)
483 error(msg: toString(file) +
484 ": Archive::children failed: " + toString(E: std::move(e)));
485 }
486 } else if (isCommandLineLoad && config->forceLoadObjC) {
487 if (file->getArchive().hasSymbolTable()) {
488 for (const object::Archive::Symbol &sym : file->getArchive().symbols())
489 if (sym.getName().starts_with(Prefix: objc::symbol_names::klass))
490 file->fetch(sym);
491 }
492
493 // TODO: no need to look for ObjC sections for a given archive member if
494 // we already found that it contains an ObjC symbol.
495 if (readFile(path)) {
496 Error e = Error::success();
497 for (const object::Archive::Child &c : file->getArchive().children(Err&: e)) {
498 Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();
499 if (!mb) {
500 // We used to create broken repro tarballs that only included those
501 // object files from thin archives that ended up being used.
502 if (config->warnThinArchiveMissingMembers)
503 warn(msg: toString(file) + ": -ObjC failed to open archive member: " +
504 toString(E: mb.takeError()));
505 else
506 llvm::consumeError(Err: mb.takeError());
507 continue;
508 }
509
510 if (config->readWorkers && archiveContents)
511 archiveContents->push_back(x: {.path: path, .isLazy: isLazy, .buffer: *mb});
512 if (!hasObjCSection(*mb))
513 continue;
514 if (Error e = file->fetch(c, reason: "-ObjC"))
515 error(msg: toString(file) + ": -ObjC failed to load archive member: " +
516 toString(E: std::move(e)));
517 }
518 if (e)
519 error(msg: toString(file) +
520 ": Archive::children failed: " + toString(E: std::move(e)));
521 }
522 }
523 if (!archiveContents || archiveContents->empty())
524 file->addLazySymbols();
525 loadedArchives[path] = ArchiveFileInfo{.file: file, .isCommandLineLoad: isCommandLineLoad};
526 newFile = file;
527 break;
528 }
529 case file_magic::macho_object:
530 newFile = make<ObjFile>(args&: mbref, args: getModTime(path), args: "", args&: isLazy);
531 break;
532 case file_magic::macho_dynamically_linked_shared_lib:
533 case file_magic::macho_dynamically_linked_shared_lib_stub:
534 case file_magic::tapi_file:
535 if (DylibFile *dylibFile =
536 loadDylib(mbref, umbrella: nullptr, /*isBundleLoader=*/false, explicitlyLinked: isExplicit))
537 newFile = dylibFile;
538 break;
539 case file_magic::bitcode:
540 newFile = make<BitcodeFile>(args&: mbref, args: "", args: 0, args&: isLazy);
541 break;
542 case file_magic::macho_executable:
543 case file_magic::macho_bundle:
544 // We only allow executable and bundle type here if it is used
545 // as a bundle loader.
546 if (!isBundleLoader)
547 error(msg: path + ": unhandled file type");
548 if (DylibFile *dylibFile = loadDylib(mbref, umbrella: nullptr, isBundleLoader))
549 newFile = dylibFile;
550 break;
551 default:
552 error(msg: path + ": unhandled file type");
553 }
554 if (newFile && !isa<DylibFile>(Val: newFile)) {
555 if ((isa<ObjFile>(Val: newFile) || isa<BitcodeFile>(Val: newFile)) && newFile->lazy &&
556 config->forceLoadObjC) {
557 for (Symbol *sym : newFile->symbols)
558 if (sym && sym->getName().starts_with(Prefix: objc::symbol_names::klass)) {
559 extract(file&: *newFile, reason: "-ObjC");
560 break;
561 }
562 if (newFile->lazy && hasObjCSection(mbref))
563 extract(file&: *newFile, reason: "-ObjC");
564 }
565
566 // printArchiveMemberLoad() prints both .a and .o names, so no need to
567 // print the .a name here. Similarly skip lazy files.
568 if (config->printEachFile && magic != file_magic::archive && !isLazy)
569 message(msg: toString(file: newFile));
570 inputFiles.insert(X: newFile);
571 }
572 return newFile;
573}
574
575static InputFile *addFile(StringRef path, LoadType loadType,
576 bool isLazy = false, bool isExplicit = true,
577 bool isBundleLoader = false,
578 bool isForceHidden = false) {
579 return processFile(buffer: readFile(path), archiveContents: nullptr, path, loadType, isLazy,
580 isExplicit, isBundleLoader, isForceHidden);
581}
582
583static void deferFile(StringRef path, bool isLazy, DeferredFiles &deferred) {
584 std::optional<MemoryBufferRef> buffer = readFile(path);
585 if (!buffer)
586 return;
587 if (config->readWorkers)
588 deferred.push_back(x: {.path: path, .isLazy: isLazy, .buffer: *buffer});
589 else
590 processFile(buffer, archiveContents: nullptr, path, loadType: LoadType::CommandLine, isLazy);
591}
592
593static std::vector<StringRef> missingAutolinkWarnings;
594static void addLibrary(StringRef name, bool isNeeded, bool isWeak,
595 bool isReexport, bool isHidden, bool isExplicit,
596 LoadType loadType) {
597 if (std::optional<StringRef> path = findLibrary(name)) {
598 if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
599 Val: addFile(path: *path, loadType, /*isLazy=*/false, isExplicit,
600 /*isBundleLoader=*/false, isForceHidden: isHidden))) {
601 if (isNeeded)
602 dylibFile->forceNeeded = true;
603 if (isWeak)
604 dylibFile->forceWeakImport = true;
605 if (isReexport) {
606 config->hasReexports = true;
607 dylibFile->reexport = true;
608 }
609 }
610 return;
611 }
612 if (loadType == LoadType::LCLinkerOption) {
613 missingAutolinkWarnings.push_back(
614 x: saver().save(S: "auto-linked library not found for -l" + name));
615 return;
616 }
617 error(msg: "library not found for -l" + name);
618}
619
620static DenseSet<StringRef> loadedObjectFrameworks;
621static void addFramework(StringRef name, bool isNeeded, bool isWeak,
622 bool isReexport, bool isExplicit, LoadType loadType) {
623 if (std::optional<StringRef> path = findFramework(name)) {
624 if (loadedObjectFrameworks.contains(V: *path))
625 return;
626
627 InputFile *file =
628 addFile(path: *path, loadType, /*isLazy=*/false, isExplicit, isBundleLoader: false);
629 if (auto *dylibFile = dyn_cast_or_null<DylibFile>(Val: file)) {
630 if (isNeeded)
631 dylibFile->forceNeeded = true;
632 if (isWeak)
633 dylibFile->forceWeakImport = true;
634 if (isReexport) {
635 config->hasReexports = true;
636 dylibFile->reexport = true;
637 }
638 } else if (isa_and_nonnull<ObjFile>(Val: file) ||
639 isa_and_nonnull<BitcodeFile>(Val: file)) {
640 // Cache frameworks containing object or bitcode files to avoid duplicate
641 // symbols. Frameworks containing static archives are cached separately
642 // in addFile() to share caching with libraries, and frameworks
643 // containing dylibs should allow overwriting of attributes such as
644 // forceNeeded by subsequent loads
645 loadedObjectFrameworks.insert(V: *path);
646 }
647 return;
648 }
649 if (loadType == LoadType::LCLinkerOption) {
650 missingAutolinkWarnings.push_back(
651 x: saver().save(S: "auto-linked framework not found for -framework " + name));
652 return;
653 }
654 error(msg: "framework not found for -framework " + name);
655}
656
657// Parses LC_LINKER_OPTION contents, which can add additional command line
658// flags. This directly parses the flags instead of using the standard argument
659// parser to improve performance.
660void macho::parseLCLinkerOption(
661 llvm::SmallVectorImpl<StringRef> &LCLinkerOptions, InputFile *f,
662 unsigned argc, StringRef data) {
663 if (config->ignoreAutoLink)
664 return;
665
666 SmallVector<StringRef, 4> argv;
667 size_t offset = 0;
668 for (unsigned i = 0; i < argc && offset < data.size(); ++i) {
669 argv.push_back(Elt: data.data() + offset);
670 offset += strlen(s: data.data() + offset) + 1;
671 }
672 if (argv.size() != argc || offset > data.size())
673 fatal(msg: toString(file: f) + ": invalid LC_LINKER_OPTION");
674
675 unsigned i = 0;
676 StringRef arg = argv[i];
677 if (arg.consume_front(Prefix: "-l")) {
678 if (config->ignoreAutoLinkOptions.contains(key: arg))
679 return;
680 } else if (arg == "-framework") {
681 StringRef name = argv[++i];
682 if (config->ignoreAutoLinkOptions.contains(key: name))
683 return;
684 } else {
685 error(msg: arg + " is not allowed in LC_LINKER_OPTION");
686 }
687
688 LCLinkerOptions.append(RHS: argv);
689}
690
691void macho::resolveLCLinkerOptions() {
692 while (!unprocessedLCLinkerOptions.empty()) {
693 SmallVector<StringRef> LCLinkerOptions(unprocessedLCLinkerOptions);
694 unprocessedLCLinkerOptions.clear();
695
696 for (unsigned i = 0; i < LCLinkerOptions.size(); ++i) {
697 StringRef arg = LCLinkerOptions[i];
698 if (arg.consume_front(Prefix: "-l")) {
699 assert(!config->ignoreAutoLinkOptions.contains(arg));
700 addLibrary(name: arg, /*isNeeded=*/false, /*isWeak=*/false,
701 /*isReexport=*/false, /*isHidden=*/false,
702 /*isExplicit=*/false, loadType: LoadType::LCLinkerOption);
703 } else if (arg == "-framework") {
704 StringRef name = LCLinkerOptions[++i];
705 assert(!config->ignoreAutoLinkOptions.contains(name));
706 addFramework(name, /*isNeeded=*/false, /*isWeak=*/false,
707 /*isReexport=*/false, /*isExplicit=*/false,
708 loadType: LoadType::LCLinkerOption);
709 } else {
710 error(msg: arg + " is not allowed in LC_LINKER_OPTION");
711 }
712 }
713 }
714}
715
716static void addFileList(StringRef path, bool isLazy,
717 DeferredFiles &deferredFiles) {
718 std::optional<MemoryBufferRef> buffer = readFile(path);
719 if (!buffer)
720 return;
721 MemoryBufferRef mbref = *buffer;
722 for (StringRef path : args::getLines(mb: mbref))
723 deferFile(path: rerootPath(path), isLazy, deferred&: deferredFiles);
724}
725
726// We expect sub-library names of the form "libfoo", which will match a dylib
727// with a path of .*/libfoo.{dylib, tbd}.
728// XXX ld64 seems to ignore the extension entirely when matching sub-libraries;
729// I'm not sure what the use case for that is.
730static bool markReexport(StringRef searchName, ArrayRef<StringRef> extensions) {
731 for (InputFile *file : inputFiles) {
732 if (auto *dylibFile = dyn_cast<DylibFile>(Val: file)) {
733 StringRef filename = path::filename(path: dylibFile->getName());
734 if (filename.consume_front(Prefix: searchName) &&
735 (filename.empty() || llvm::is_contained(Range&: extensions, Element: filename))) {
736 dylibFile->reexport = true;
737 return true;
738 }
739 }
740 }
741 return false;
742}
743
744// This function is called on startup. We need this for LTO since
745// LTO calls LLVM functions to compile bitcode files to native code.
746// Technically this can be delayed until we read bitcode files, but
747// we don't bother to do lazily because the initialization is fast.
748static void initLLVM() {
749 InitializeAllTargets();
750 InitializeAllTargetMCs();
751 InitializeAllAsmPrinters();
752 InitializeAllAsmParsers();
753}
754
755static bool compileBitcodeFiles() {
756 TimeTraceScope timeScope("LTO");
757 auto *lto = make<BitcodeCompiler>();
758 for (InputFile *file : inputFiles)
759 if (auto *bitcodeFile = dyn_cast<BitcodeFile>(Val: file))
760 if (!file->lazy)
761 lto->add(f&: *bitcodeFile);
762
763 std::vector<ObjFile *> compiled = lto->compile();
764 inputFiles.insert_range(R&: compiled);
765
766 return !compiled.empty();
767}
768
769// Replaces common symbols with defined symbols residing in __common sections.
770// This function must be called after all symbol names are resolved (i.e. after
771// all InputFiles have been loaded.) As a result, later operations won't see
772// any CommonSymbols.
773static void replaceCommonSymbols() {
774 TimeTraceScope timeScope("Replace common symbols");
775 ConcatOutputSection *osec = nullptr;
776 for (Symbol *sym : symtab->getSymbols()) {
777 auto *common = dyn_cast<CommonSymbol>(Val: sym);
778 if (common == nullptr)
779 continue;
780
781 // Casting to size_t will truncate large values on 32-bit architectures,
782 // but it's not really worth supporting the linking of 64-bit programs on
783 // 32-bit archs.
784 ArrayRef<uint8_t> data = {nullptr, static_cast<size_t>(common->size)};
785 // FIXME avoid creating one Section per symbol?
786 auto *section =
787 make<Section>(args: common->getFile(), args: segment_names::data,
788 args: section_names::common, args: S_ZEROFILL, /*addr=*/args: 0);
789 auto *isec = make<ConcatInputSection>(args&: *section, args&: data, args: common->align);
790 if (!osec)
791 osec = ConcatOutputSection::getOrCreateForInput(isec);
792 isec->parent = osec;
793 addInputSection(inputSection: isec);
794
795 // FIXME: CommonSymbol should store isReferencedDynamically, noDeadStrip
796 // and pass them on here.
797 replaceSymbol<Defined>(
798 s: sym, arg: sym->getName(), arg: common->getFile(), arg&: isec, /*value=*/arg: 0, arg: common->size,
799 /*isWeakDef=*/arg: false, /*isExternal=*/arg: true, arg: common->privateExtern,
800 /*includeInSymtab=*/arg: true, /*isReferencedDynamically=*/arg: false,
801 /*noDeadStrip=*/arg: false);
802 }
803}
804
805static void initializeSectionRenameMap() {
806 if (config->dataConst) {
807 SmallVector<StringRef> v{section_names::got,
808 section_names::authGot,
809 section_names::authPtr,
810 section_names::nonLazySymbolPtr,
811 section_names::const_,
812 section_names::cfString,
813 section_names::moduleInitFunc,
814 section_names::moduleTermFunc,
815 section_names::objcClassList,
816 section_names::objcNonLazyClassList,
817 section_names::objcCatList,
818 section_names::objcNonLazyCatList,
819 section_names::objcProtoList,
820 section_names::objCImageInfo};
821 for (StringRef s : v)
822 config->sectionRenameMap[{segment_names::data, s}] = {
823 segment_names::dataConst, s};
824 }
825 config->sectionRenameMap[{segment_names::text, section_names::staticInit}] = {
826 segment_names::text, section_names::text};
827 config->sectionRenameMap[{segment_names::import, section_names::pointers}] = {
828 config->dataConst ? segment_names::dataConst : segment_names::data,
829 section_names::nonLazySymbolPtr};
830}
831
832static inline char toLowerDash(char x) {
833 if (x >= 'A' && x <= 'Z')
834 return x - 'A' + 'a';
835 else if (x == ' ')
836 return '-';
837 return x;
838}
839
840static std::string lowerDash(StringRef s) {
841 return std::string(map_iterator(I: s.begin(), F: toLowerDash),
842 map_iterator(I: s.end(), F: toLowerDash));
843}
844
845struct PlatformVersion {
846 PlatformType platform = PLATFORM_UNKNOWN;
847 llvm::VersionTuple minimum;
848 llvm::VersionTuple sdk;
849};
850
851static PlatformVersion parsePlatformVersion(const Arg *arg) {
852 assert(arg->getOption().getID() == OPT_platform_version);
853 StringRef platformStr = arg->getValue(N: 0);
854 StringRef minVersionStr = arg->getValue(N: 1);
855 StringRef sdkVersionStr = arg->getValue(N: 2);
856
857 PlatformVersion platformVersion;
858
859 // TODO(compnerd) see if we can generate this case list via XMACROS
860 platformVersion.platform =
861 StringSwitch<PlatformType>(lowerDash(s: platformStr))
862 .Cases(CaseStrings: {"macos", "1"}, Value: PLATFORM_MACOS)
863 .Cases(CaseStrings: {"ios", "2"}, Value: PLATFORM_IOS)
864 .Cases(CaseStrings: {"tvos", "3"}, Value: PLATFORM_TVOS)
865 .Cases(CaseStrings: {"watchos", "4"}, Value: PLATFORM_WATCHOS)
866 .Cases(CaseStrings: {"bridgeos", "5"}, Value: PLATFORM_BRIDGEOS)
867 .Cases(CaseStrings: {"mac-catalyst", "6"}, Value: PLATFORM_MACCATALYST)
868 .Cases(CaseStrings: {"ios-simulator", "7"}, Value: PLATFORM_IOSSIMULATOR)
869 .Cases(CaseStrings: {"tvos-simulator", "8"}, Value: PLATFORM_TVOSSIMULATOR)
870 .Cases(CaseStrings: {"watchos-simulator", "9"}, Value: PLATFORM_WATCHOSSIMULATOR)
871 .Cases(CaseStrings: {"driverkit", "10"}, Value: PLATFORM_DRIVERKIT)
872 .Cases(CaseStrings: {"xros", "11"}, Value: PLATFORM_XROS)
873 .Cases(CaseStrings: {"xros-simulator", "12"}, Value: PLATFORM_XROS_SIMULATOR)
874 .Default(Value: PLATFORM_UNKNOWN);
875 if (platformVersion.platform == PLATFORM_UNKNOWN)
876 error(msg: Twine("malformed platform: ") + platformStr);
877 // The underlying load command only supports 3 components.
878 if (platformVersion.minimum.tryParse(string: minVersionStr) ||
879 platformVersion.minimum.getBuild())
880 error(msg: Twine("malformed minimum version: ") + minVersionStr);
881 if (platformVersion.sdk.tryParse(string: sdkVersionStr) ||
882 platformVersion.sdk.getBuild())
883 error(msg: Twine("malformed sdk version: ") + sdkVersionStr);
884 return platformVersion;
885}
886
887// Has the side-effect of setting Config::platformInfo and
888// potentially Config::secondaryPlatformInfo.
889static void setPlatformVersions(StringRef archName, const ArgList &args) {
890 std::map<PlatformType, PlatformVersion> platformVersions;
891 const PlatformVersion *lastVersionInfo = nullptr;
892 for (const Arg *arg : args.filtered(Ids: OPT_platform_version)) {
893 PlatformVersion version = parsePlatformVersion(arg);
894
895 // For each platform, the last flag wins:
896 // `-platform_version macos 2 3 -platform_version macos 4 5` has the same
897 // effect as just passing `-platform_version macos 4 5`.
898 // FIXME: ld64 warns on multiple flags for one platform. Should we?
899 platformVersions[version.platform] = version;
900 lastVersionInfo = &platformVersions[version.platform];
901 }
902
903 if (platformVersions.empty()) {
904 error(msg: "must specify -platform_version");
905 return;
906 }
907 if (platformVersions.size() > 2) {
908 error(msg: "must specify -platform_version at most twice");
909 return;
910 }
911 if (platformVersions.size() == 2) {
912 bool isZipperedCatalyst = platformVersions.count(x: PLATFORM_MACOS) &&
913 platformVersions.count(x: PLATFORM_MACCATALYST);
914
915 if (!isZipperedCatalyst) {
916 error(msg: "lld supports writing zippered outputs only for "
917 "macos and mac-catalyst");
918 } else if (config->outputType != MH_DYLIB &&
919 config->outputType != MH_BUNDLE) {
920 error(msg: "writing zippered outputs only valid for -dylib and -bundle");
921 }
922
923 config->platformInfo = {
924 .target: MachO::Target(getArchitectureFromName(Name: archName), PLATFORM_MACOS,
925 platformVersions[PLATFORM_MACOS].minimum),
926 .sdk: platformVersions[PLATFORM_MACOS].sdk};
927 config->secondaryPlatformInfo = {
928 .target: MachO::Target(getArchitectureFromName(Name: archName), PLATFORM_MACCATALYST,
929 platformVersions[PLATFORM_MACCATALYST].minimum),
930 .sdk: platformVersions[PLATFORM_MACCATALYST].sdk};
931 return;
932 }
933
934 config->platformInfo = {.target: MachO::Target(getArchitectureFromName(Name: archName),
935 lastVersionInfo->platform,
936 lastVersionInfo->minimum),
937 .sdk: lastVersionInfo->sdk};
938}
939
940// Has the side-effect of setting Config::target.
941static TargetInfo *createTargetInfo(InputArgList &args) {
942 StringRef archName = args.getLastArgValue(Id: OPT_arch);
943 if (archName.empty()) {
944 error(msg: "must specify -arch");
945 return nullptr;
946 }
947
948 setPlatformVersions(archName, args);
949 auto [cpuType, cpuSubtype] = getCPUTypeFromArchitecture(Arch: config->arch());
950 switch (cpuType) {
951 case CPU_TYPE_X86_64:
952 return createX86_64TargetInfo();
953 case CPU_TYPE_ARM64:
954 return createARM64TargetInfo();
955 case CPU_TYPE_ARM64_32:
956 return createARM64_32TargetInfo();
957 default:
958 error(msg: "missing or unsupported -arch " + archName);
959 return nullptr;
960 }
961}
962
963static UndefinedSymbolTreatment
964getUndefinedSymbolTreatment(const ArgList &args) {
965 StringRef treatmentStr = args.getLastArgValue(Id: OPT_undefined);
966 auto treatment =
967 StringSwitch<UndefinedSymbolTreatment>(treatmentStr)
968 .Cases(CaseStrings: {"error", ""}, Value: UndefinedSymbolTreatment::error)
969 .Case(S: "warning", Value: UndefinedSymbolTreatment::warning)
970 .Case(S: "suppress", Value: UndefinedSymbolTreatment::suppress)
971 .Case(S: "dynamic_lookup", Value: UndefinedSymbolTreatment::dynamic_lookup)
972 .Default(Value: UndefinedSymbolTreatment::unknown);
973 if (treatment == UndefinedSymbolTreatment::unknown) {
974 warn(msg: Twine("unknown -undefined TREATMENT '") + treatmentStr +
975 "', defaulting to 'error'");
976 treatment = UndefinedSymbolTreatment::error;
977 } else if (config->namespaceKind == NamespaceKind::twolevel &&
978 (treatment == UndefinedSymbolTreatment::warning ||
979 treatment == UndefinedSymbolTreatment::suppress)) {
980 if (treatment == UndefinedSymbolTreatment::warning)
981 fatal(msg: "'-undefined warning' only valid with '-flat_namespace'");
982 else
983 fatal(msg: "'-undefined suppress' only valid with '-flat_namespace'");
984 treatment = UndefinedSymbolTreatment::error;
985 }
986 return treatment;
987}
988
989static ICFLevel getICFLevel(const ArgList &args) {
990 StringRef icfLevelStr = args.getLastArgValue(Id: OPT_icf_eq);
991 auto icfLevel = StringSwitch<ICFLevel>(icfLevelStr)
992 .Cases(CaseStrings: {"none", ""}, Value: ICFLevel::none)
993 .Case(S: "safe", Value: ICFLevel::safe)
994 .Case(S: "safe_thunks", Value: ICFLevel::safe_thunks)
995 .Case(S: "all", Value: ICFLevel::all)
996 .Default(Value: ICFLevel::unknown);
997
998 if ((icfLevel == ICFLevel::safe_thunks) && (config->arch() != AK_arm64)) {
999 error(msg: "--icf=safe_thunks is only supported on arm64 targets");
1000 }
1001
1002 if (icfLevel == ICFLevel::unknown) {
1003 warn(msg: Twine("unknown --icf=OPTION `") + icfLevelStr +
1004 "', defaulting to `none'");
1005 icfLevel = ICFLevel::none;
1006 }
1007 return icfLevel;
1008}
1009
1010static ObjCStubsMode getObjCStubsMode(const ArgList &args) {
1011 const Arg *arg = args.getLastArg(Ids: OPT_objc_stubs_fast, Ids: OPT_objc_stubs_small);
1012 if (!arg)
1013 return ObjCStubsMode::fast;
1014
1015 if (arg->getOption().getID() == OPT_objc_stubs_small) {
1016 if (is_contained(Set: {AK_arm64e, AK_arm64}, Element: config->arch()))
1017 return ObjCStubsMode::small;
1018 else
1019 warn(msg: "-objc_stubs_small is not yet implemented, defaulting to "
1020 "-objc_stubs_fast");
1021 }
1022 return ObjCStubsMode::fast;
1023}
1024
1025static void warnIfDeprecatedOption(const Option &opt) {
1026 if (!opt.getGroup().isValid())
1027 return;
1028 if (opt.getGroup().getID() == OPT_grp_deprecated) {
1029 warn(msg: "Option `" + opt.getPrefixedName() + "' is deprecated in ld64:");
1030 warn(msg: opt.getHelpText());
1031 }
1032}
1033
1034static void warnIfUnimplementedOption(const Option &opt) {
1035 if (!opt.getGroup().isValid() || !opt.hasFlag(Val: DriverFlag::HelpHidden))
1036 return;
1037 switch (opt.getGroup().getID()) {
1038 case OPT_grp_deprecated:
1039 // warn about deprecated options elsewhere
1040 break;
1041 case OPT_grp_undocumented:
1042 warn(msg: "Option `" + opt.getPrefixedName() +
1043 "' is undocumented. Should lld implement it?");
1044 break;
1045 case OPT_grp_obsolete:
1046 warn(msg: "Option `" + opt.getPrefixedName() +
1047 "' is obsolete. Please modernize your usage.");
1048 break;
1049 case OPT_grp_ignored:
1050 warn(msg: "Option `" + opt.getPrefixedName() + "' is ignored.");
1051 break;
1052 case OPT_grp_ignored_silently:
1053 break;
1054 default:
1055 warn(msg: "Option `" + opt.getPrefixedName() +
1056 "' is not yet implemented. Stay tuned...");
1057 break;
1058 }
1059}
1060
1061static const char *getReproduceOption(InputArgList &args) {
1062 if (const Arg *arg = args.getLastArg(Ids: OPT_reproduce))
1063 return arg->getValue();
1064 return getenv(name: "LLD_REPRODUCE");
1065}
1066
1067// Parse options of the form "old;new".
1068static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
1069 unsigned id) {
1070 auto *arg = args.getLastArg(Ids: id);
1071 if (!arg)
1072 return {"", ""};
1073
1074 StringRef s = arg->getValue();
1075 std::pair<StringRef, StringRef> ret = s.split(Separator: ';');
1076 if (ret.second.empty())
1077 error(msg: arg->getSpelling() + " expects 'old;new' format, but got " + s);
1078 return ret;
1079}
1080
1081// Parse options of the form "old;new[;extra]".
1082static std::tuple<StringRef, StringRef, StringRef>
1083getOldNewOptionsExtra(opt::InputArgList &args, unsigned id) {
1084 auto [oldDir, second] = getOldNewOptions(args, id);
1085 auto [newDir, extraDir] = second.split(Separator: ';');
1086 return {oldDir, newDir, extraDir};
1087}
1088
1089static void parseClangOption(StringRef opt, const Twine &msg) {
1090 std::string err;
1091 raw_string_ostream os(err);
1092
1093 const char *argv[] = {"lld", opt.data()};
1094 if (cl::ParseCommandLineOptions(argc: 2, argv, Overview: "", Errs: &os))
1095 return;
1096 error(msg: msg + ": " + StringRef(err).trim());
1097}
1098
1099static uint32_t parseDylibVersion(const ArgList &args, unsigned id) {
1100 const Arg *arg = args.getLastArg(Ids: id);
1101 if (!arg)
1102 return 0;
1103
1104 if (config->outputType != MH_DYLIB) {
1105 error(msg: arg->getAsString(Args: args) + ": only valid with -dylib");
1106 return 0;
1107 }
1108
1109 PackedVersion version;
1110 if (!version.parse32(Str: arg->getValue())) {
1111 error(msg: arg->getAsString(Args: args) + ": malformed version");
1112 return 0;
1113 }
1114
1115 return version.rawValue();
1116}
1117
1118static uint32_t parseProtection(StringRef protStr) {
1119 uint32_t prot = 0;
1120 for (char c : protStr) {
1121 switch (c) {
1122 case 'r':
1123 prot |= VM_PROT_READ;
1124 break;
1125 case 'w':
1126 prot |= VM_PROT_WRITE;
1127 break;
1128 case 'x':
1129 prot |= VM_PROT_EXECUTE;
1130 break;
1131 case '-':
1132 break;
1133 default:
1134 error(msg: "unknown -segprot letter '" + Twine(c) + "' in " + protStr);
1135 return 0;
1136 }
1137 }
1138 return prot;
1139}
1140
1141static std::vector<SectionAlign> parseSectAlign(const opt::InputArgList &args) {
1142 std::vector<SectionAlign> sectAligns;
1143 for (const Arg *arg : args.filtered(Ids: OPT_sectalign)) {
1144 StringRef segName = arg->getValue(N: 0);
1145 StringRef sectName = arg->getValue(N: 1);
1146 StringRef alignStr = arg->getValue(N: 2);
1147 alignStr.consume_front_insensitive(Prefix: "0x");
1148 uint32_t align;
1149 if (alignStr.getAsInteger(Radix: 16, Result&: align)) {
1150 error(msg: "-sectalign: failed to parse '" + StringRef(arg->getValue(N: 2)) +
1151 "' as number");
1152 continue;
1153 }
1154 if (!isPowerOf2_32(Value: align)) {
1155 error(msg: "-sectalign: '" + StringRef(arg->getValue(N: 2)) +
1156 "' (in base 16) not a power of two");
1157 continue;
1158 }
1159 sectAligns.push_back(x: {.segName: segName, .sectName: sectName, .align: align});
1160 }
1161 return sectAligns;
1162}
1163
1164PlatformType macho::removeSimulator(PlatformType platform) {
1165 switch (platform) {
1166 case PLATFORM_IOSSIMULATOR:
1167 return PLATFORM_IOS;
1168 case PLATFORM_TVOSSIMULATOR:
1169 return PLATFORM_TVOS;
1170 case PLATFORM_WATCHOSSIMULATOR:
1171 return PLATFORM_WATCHOS;
1172 case PLATFORM_XROS_SIMULATOR:
1173 return PLATFORM_XROS;
1174 default:
1175 return platform;
1176 }
1177}
1178
1179static bool supportsNoPie() {
1180 return !(config->arch() == AK_arm64 || config->arch() == AK_arm64e ||
1181 config->arch() == AK_arm64_32);
1182}
1183
1184static bool shouldAdhocSignByDefault(Architecture arch, PlatformType platform) {
1185 if (arch != AK_arm64 && arch != AK_arm64e)
1186 return false;
1187
1188 return platform == PLATFORM_MACOS || platform == PLATFORM_IOSSIMULATOR ||
1189 platform == PLATFORM_TVOSSIMULATOR ||
1190 platform == PLATFORM_WATCHOSSIMULATOR ||
1191 platform == PLATFORM_XROS_SIMULATOR;
1192}
1193
1194template <std::size_t N>
1195using MinVersions = std::array<std::pair<PlatformType, VersionTuple>, N>;
1196
1197/// Returns true if the platform is greater than the min version.
1198/// Returns false if the platform does not exist.
1199template <std::size_t N>
1200static bool greaterEqMinVersion(const MinVersions<N> &minVersions,
1201 bool ignoreSimulator) {
1202 PlatformType platform = config->platformInfo.target.Platform;
1203 if (ignoreSimulator)
1204 platform = removeSimulator(platform);
1205 auto it = llvm::find_if(minVersions,
1206 [&](const auto &p) { return p.first == platform; });
1207 if (it != minVersions.end())
1208 if (config->platformInfo.target.MinDeployment >= it->second)
1209 return true;
1210 return false;
1211}
1212
1213static bool dataConstDefault(const InputArgList &args) {
1214 static const MinVersions<6> minVersion = {._M_elems: {
1215 {PLATFORM_MACOS, VersionTuple(10, 15)},
1216 {PLATFORM_IOS, VersionTuple(13, 0)},
1217 {PLATFORM_TVOS, VersionTuple(13, 0)},
1218 {PLATFORM_WATCHOS, VersionTuple(6, 0)},
1219 {PLATFORM_XROS, VersionTuple(1, 0)},
1220 {PLATFORM_BRIDGEOS, VersionTuple(4, 0)},
1221 }};
1222 if (!greaterEqMinVersion(minVersions: minVersion, ignoreSimulator: true))
1223 return false;
1224
1225 switch (config->outputType) {
1226 case MH_EXECUTE:
1227 return !(args.hasArg(Ids: OPT_no_pie) && supportsNoPie());
1228 case MH_BUNDLE:
1229 // FIXME: return false when -final_name ...
1230 // has prefix "/System/Library/UserEventPlugins/"
1231 // or matches "/usr/libexec/locationd" "/usr/libexec/terminusd"
1232 return true;
1233 case MH_DYLIB:
1234 return true;
1235 case MH_OBJECT:
1236 return false;
1237 default:
1238 llvm_unreachable(
1239 "unsupported output type for determining data-const default");
1240 }
1241 return false;
1242}
1243
1244static bool shouldEmitChainedFixups(const InputArgList &args) {
1245 const Arg *arg = args.getLastArg(Ids: OPT_fixup_chains, Ids: OPT_no_fixup_chains);
1246 if (arg && arg->getOption().matches(ID: OPT_no_fixup_chains))
1247 return false;
1248
1249 bool requested = arg && arg->getOption().matches(ID: OPT_fixup_chains);
1250 if (!config->isPic) {
1251 if (requested)
1252 error(msg: "-fixup_chains is incompatible with -no_pie");
1253
1254 return false;
1255 }
1256
1257 if (!is_contained(Set: {AK_x86_64, AK_x86_64h, AK_arm64}, Element: config->arch())) {
1258 if (requested)
1259 error(msg: "-fixup_chains is only supported on x86_64 and arm64 targets");
1260
1261 return false;
1262 }
1263
1264 if (args.hasArg(Ids: OPT_preload)) {
1265 if (requested)
1266 error(msg: "-fixup_chains is incompatible with -preload");
1267
1268 return false;
1269 }
1270
1271 if (requested)
1272 return true;
1273
1274 static const MinVersions<9> minVersion = {._M_elems: {
1275 {PLATFORM_IOS, VersionTuple(13, 4)},
1276 {PLATFORM_IOSSIMULATOR, VersionTuple(16, 0)},
1277 {PLATFORM_MACOS, VersionTuple(13, 0)},
1278 {PLATFORM_TVOS, VersionTuple(14, 0)},
1279 {PLATFORM_TVOSSIMULATOR, VersionTuple(15, 0)},
1280 {PLATFORM_WATCHOS, VersionTuple(7, 0)},
1281 {PLATFORM_WATCHOSSIMULATOR, VersionTuple(8, 0)},
1282 {PLATFORM_XROS, VersionTuple(1, 0)},
1283 {PLATFORM_XROS_SIMULATOR, VersionTuple(1, 0)},
1284 }};
1285 return greaterEqMinVersion(minVersions: minVersion, ignoreSimulator: false);
1286}
1287
1288static bool shouldEmitRelativeMethodLists(const InputArgList &args) {
1289 const Arg *arg = args.getLastArg(Ids: OPT_objc_relative_method_lists,
1290 Ids: OPT_no_objc_relative_method_lists);
1291 if (arg && arg->getOption().getID() == OPT_objc_relative_method_lists)
1292 return true;
1293 if (arg && arg->getOption().getID() == OPT_no_objc_relative_method_lists)
1294 return false;
1295
1296 // If no flag is specified, enable this on newer versions by default.
1297 // The min versions is taken from
1298 // ld64(https://github.com/apple-oss-distributions/ld64/blob/47f477cb721755419018f7530038b272e9d0cdea/src/ld/ld.hpp#L310)
1299 // to mimic to operation of ld64
1300 // [here](https://github.com/apple-oss-distributions/ld64/blob/47f477cb721755419018f7530038b272e9d0cdea/src/ld/Options.cpp#L6085-L6101)
1301 static const MinVersions<6> minVersion = {._M_elems: {
1302 {PLATFORM_MACOS, VersionTuple(10, 16)},
1303 {PLATFORM_IOS, VersionTuple(14, 0)},
1304 {PLATFORM_WATCHOS, VersionTuple(7, 0)},
1305 {PLATFORM_TVOS, VersionTuple(14, 0)},
1306 {PLATFORM_BRIDGEOS, VersionTuple(5, 0)},
1307 {PLATFORM_XROS, VersionTuple(1, 0)},
1308 }};
1309 return greaterEqMinVersion(minVersions: minVersion, ignoreSimulator: true);
1310}
1311
1312void SymbolPatterns::clear() {
1313 literals.clear();
1314 globs.clear();
1315}
1316
1317void SymbolPatterns::insert(StringRef symbolName) {
1318 if (symbolName.find_first_of(Chars: "*?[]") == StringRef::npos)
1319 literals.insert(X: CachedHashStringRef(symbolName));
1320 else if (Expected<GlobPattern> pattern = GlobPattern::create(Pat: symbolName))
1321 globs.emplace_back(args&: *pattern);
1322 else
1323 error(msg: "invalid symbol-name pattern: " + symbolName);
1324}
1325
1326bool SymbolPatterns::matchLiteral(StringRef symbolName) const {
1327 return literals.contains(key: CachedHashStringRef(symbolName));
1328}
1329
1330bool SymbolPatterns::matchGlob(StringRef symbolName) const {
1331 for (const GlobPattern &glob : globs)
1332 if (glob.match(S: symbolName))
1333 return true;
1334 return false;
1335}
1336
1337bool SymbolPatterns::match(StringRef symbolName) const {
1338 return matchLiteral(symbolName) || matchGlob(symbolName);
1339}
1340
1341static void parseSymbolPatternsFile(const Arg *arg,
1342 SymbolPatterns &symbolPatterns) {
1343 StringRef path = arg->getValue();
1344 std::optional<MemoryBufferRef> buffer = readFile(path);
1345 if (!buffer) {
1346 error(msg: "Could not read symbol file: " + path);
1347 return;
1348 }
1349 MemoryBufferRef mbref = *buffer;
1350 for (StringRef line : args::getLines(mb: mbref)) {
1351 line = line.take_until(F: [](char c) { return c == '#'; }).trim();
1352 if (!line.empty())
1353 symbolPatterns.insert(symbolName: line);
1354 }
1355}
1356
1357static void handleSymbolPatterns(InputArgList &args,
1358 SymbolPatterns &symbolPatterns,
1359 unsigned singleOptionCode,
1360 unsigned listFileOptionCode) {
1361 for (const Arg *arg : args.filtered(Ids: singleOptionCode))
1362 symbolPatterns.insert(symbolName: arg->getValue());
1363 for (const Arg *arg : args.filtered(Ids: listFileOptionCode))
1364 parseSymbolPatternsFile(arg, symbolPatterns);
1365}
1366
1367static void createFiles(const InputArgList &args) {
1368 TimeTraceScope timeScope("Load input files");
1369 // This loop should be reserved for options whose exact ordering matters.
1370 // Other options should be handled via filtered() and/or getLastArg().
1371 bool isLazy = false;
1372 // If we've processed an opening --start-lib, without a matching --end-lib
1373 bool inLib = false;
1374 DeferredFiles deferredFiles;
1375
1376 for (const Arg *arg : args) {
1377 const Option &opt = arg->getOption();
1378 warnIfDeprecatedOption(opt);
1379 warnIfUnimplementedOption(opt);
1380
1381 switch (opt.getID()) {
1382 case OPT_INPUT:
1383 deferFile(path: rerootPath(path: arg->getValue()), isLazy, deferred&: deferredFiles);
1384 break;
1385 case OPT_needed_library:
1386 if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
1387 Val: addFile(path: rerootPath(path: arg->getValue()), loadType: LoadType::CommandLine)))
1388 dylibFile->forceNeeded = true;
1389 break;
1390 case OPT_reexport_library:
1391 if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
1392 Val: addFile(path: rerootPath(path: arg->getValue()), loadType: LoadType::CommandLine))) {
1393 config->hasReexports = true;
1394 dylibFile->reexport = true;
1395 }
1396 break;
1397 case OPT_weak_library:
1398 if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
1399 Val: addFile(path: rerootPath(path: arg->getValue()), loadType: LoadType::CommandLine)))
1400 dylibFile->forceWeakImport = true;
1401 break;
1402 case OPT_filelist:
1403 addFileList(path: arg->getValue(), isLazy, deferredFiles);
1404 break;
1405 case OPT_force_load:
1406 addFile(path: rerootPath(path: arg->getValue()), loadType: LoadType::CommandLineForce);
1407 break;
1408 case OPT_load_hidden:
1409 addFile(path: rerootPath(path: arg->getValue()), loadType: LoadType::CommandLine,
1410 /*isLazy=*/false, /*isExplicit=*/true, /*isBundleLoader=*/false,
1411 /*isForceHidden=*/true);
1412 break;
1413 case OPT_l:
1414 case OPT_needed_l:
1415 case OPT_reexport_l:
1416 case OPT_weak_l:
1417 case OPT_hidden_l:
1418 addLibrary(name: arg->getValue(), isNeeded: opt.getID() == OPT_needed_l,
1419 isWeak: opt.getID() == OPT_weak_l, isReexport: opt.getID() == OPT_reexport_l,
1420 isHidden: opt.getID() == OPT_hidden_l,
1421 /*isExplicit=*/true, loadType: LoadType::CommandLine);
1422 break;
1423 case OPT_framework:
1424 case OPT_needed_framework:
1425 case OPT_reexport_framework:
1426 case OPT_weak_framework:
1427 addFramework(name: arg->getValue(), isNeeded: opt.getID() == OPT_needed_framework,
1428 isWeak: opt.getID() == OPT_weak_framework,
1429 isReexport: opt.getID() == OPT_reexport_framework, /*isExplicit=*/true,
1430 loadType: LoadType::CommandLine);
1431 break;
1432 case OPT_start_lib:
1433 if (inLib)
1434 error(msg: "nested --start-lib");
1435 inLib = true;
1436 if (!config->allLoad)
1437 isLazy = true;
1438 break;
1439 case OPT_end_lib:
1440 if (!inLib)
1441 error(msg: "stray --end-lib");
1442 inLib = false;
1443 isLazy = false;
1444 break;
1445 default:
1446 break;
1447 }
1448 }
1449
1450#if LLVM_ENABLE_THREADS
1451 if (config->readWorkers) {
1452 multiThreadedPageIn(deferred: deferredFiles);
1453
1454 DeferredFiles archiveContents;
1455 std::vector<ArchiveFile *> archives;
1456 for (auto &file : deferredFiles) {
1457 auto inputFile = processFile(buffer: file.buffer, archiveContents: &archiveContents, path: file.path,
1458 loadType: LoadType::CommandLine, isLazy: file.isLazy);
1459 if (ArchiveFile *archive = dyn_cast<ArchiveFile>(Val: inputFile))
1460 archives.push_back(x: archive);
1461 }
1462
1463 if (!archiveContents.empty())
1464 multiThreadedPageIn(deferred: archiveContents);
1465 for (auto *archive : archives)
1466 archive->addLazySymbols();
1467
1468 pageInQueue.stopAllWork = true;
1469 }
1470#endif
1471}
1472
1473static void gatherInputSections() {
1474 TimeTraceScope timeScope("Gathering input sections");
1475 for (const InputFile *file : inputFiles) {
1476 for (const Section *section : file->sections) {
1477 // Compact unwind entries require special handling elsewhere. (In
1478 // contrast, EH frames are handled like regular ConcatInputSections.)
1479 if (section->name == section_names::compactUnwind)
1480 continue;
1481 // Addrsig sections contain metadata only needed at link time.
1482 if (section->name == section_names::addrSig)
1483 continue;
1484 for (const Subsection &subsection : section->subsections)
1485 addInputSection(inputSection: subsection.isec);
1486 }
1487 if (!file->objCImageInfo.empty())
1488 in.objCImageInfo->addFile(file);
1489 }
1490}
1491
1492static void codegenDataGenerate() {
1493 TimeTraceScope timeScope("Generating codegen data");
1494
1495 OutlinedHashTreeRecord globalOutlineRecord;
1496 StableFunctionMapRecord globalMergeRecord;
1497 for (ConcatInputSection *isec : inputSections) {
1498 if (isec->getSegName() != segment_names::data)
1499 continue;
1500 if (isec->getName() == section_names::outlinedHashTree) {
1501 // Read outlined hash tree from each section.
1502 OutlinedHashTreeRecord localOutlineRecord;
1503 // Use a pointer to allow modification by the function.
1504 auto *data = isec->data.data();
1505 localOutlineRecord.deserialize(Ptr&: data);
1506
1507 // Merge it to the global hash tree.
1508 globalOutlineRecord.merge(Other: localOutlineRecord);
1509 }
1510 if (isec->getName() == section_names::functionMap) {
1511 // Read stable functions from each section.
1512 StableFunctionMapRecord localMergeRecord;
1513 // Use a pointer to allow modification by the function.
1514 auto *data = isec->data.data();
1515 localMergeRecord.deserialize(Ptr&: data);
1516
1517 // Merge it to the global function map.
1518 globalMergeRecord.merge(Other: localMergeRecord);
1519 }
1520 }
1521
1522 globalMergeRecord.finalize();
1523
1524 CodeGenDataWriter Writer;
1525 if (!globalOutlineRecord.empty())
1526 Writer.addRecord(Record&: globalOutlineRecord);
1527 if (!globalMergeRecord.empty())
1528 Writer.addRecord(Record&: globalMergeRecord);
1529
1530 std::error_code EC;
1531 auto fileName = config->codegenDataGeneratePath;
1532 assert(!fileName.empty());
1533 raw_fd_ostream Output(fileName, EC, sys::fs::OF_None);
1534 if (EC)
1535 error(msg: "fail to create " + fileName + ": " + EC.message());
1536
1537 if (auto E = Writer.write(OS&: Output))
1538 error(msg: "fail to write CGData: " + toString(E: std::move(E)));
1539}
1540
1541static void foldIdenticalLiterals() {
1542 TimeTraceScope timeScope("Fold identical literals");
1543 // We always create a cStringSection, regardless of whether dedupLiterals is
1544 // true. If it isn't, we simply create a non-deduplicating CStringSection.
1545 // Either way, we must unconditionally finalize it here.
1546 for (auto *sec : in.cStringSections)
1547 sec->finalizeContents();
1548 in.wordLiteralSection->finalizeContents();
1549}
1550
1551static void addSynthenticMethnames() {
1552 std::string &data = *make<std::string>();
1553 llvm::raw_string_ostream os(data);
1554 for (Symbol *sym : symtab->getSymbols())
1555 if (isa<Undefined>(Val: sym))
1556 if (ObjCStubsSection::isObjCStubSymbol(sym))
1557 os << ObjCStubsSection::getMethname(sym) << '\0';
1558
1559 if (data.empty())
1560 return;
1561
1562 const auto *buf = reinterpret_cast<const uint8_t *>(data.c_str());
1563 Section &section = *make<Section>(/*file=*/args: nullptr, args: segment_names::text,
1564 args: section_names::objcMethname,
1565 args: S_CSTRING_LITERALS, /*addr=*/args: 0);
1566
1567 auto *isec =
1568 make<CStringInputSection>(args&: section, args: ArrayRef<uint8_t>{buf, data.size()},
1569 /*align=*/args: 1, /*dedupLiterals=*/args: true);
1570 isec->splitIntoPieces();
1571 for (auto &piece : isec->pieces)
1572 piece.live = true;
1573 section.subsections.push_back(x: {.offset: 0, .isec: isec});
1574 in.objcMethnameSection->addInput(isec);
1575 in.objcMethnameSection->isec->markLive(off: 0);
1576}
1577
1578static void referenceStubBinder() {
1579 bool needsStubHelper = config->outputType == MH_DYLIB ||
1580 config->outputType == MH_EXECUTE ||
1581 config->outputType == MH_BUNDLE;
1582 if (!needsStubHelper || !symtab->find(name: "dyld_stub_binder"))
1583 return;
1584
1585 // dyld_stub_binder is used by dyld to resolve lazy bindings. This code here
1586 // adds a opportunistic reference to dyld_stub_binder if it happens to exist.
1587 // dyld_stub_binder is in libSystem.dylib, which is usually linked in. This
1588 // isn't needed for correctness, but the presence of that symbol suppresses
1589 // "no symbols" diagnostics from `nm`.
1590 // StubHelperSection::setUp() adds a reference and errors out if
1591 // dyld_stub_binder doesn't exist in case it is actually needed.
1592 symtab->addUndefined(name: "dyld_stub_binder", /*file=*/nullptr, /*isWeak=*/isWeakRef: false);
1593}
1594
1595static void createAliases() {
1596 for (const auto &pair : config->aliasedSymbols) {
1597 if (const auto &sym = symtab->find(name: pair.first)) {
1598 if (const auto &defined = dyn_cast<Defined>(Val: sym)) {
1599 symtab->aliasDefined(src: defined, target: pair.second, newFile: defined->getFile())
1600 ->noDeadStrip = true;
1601 } else {
1602 error(msg: "TODO: support aliasing to symbols of kind " +
1603 Twine(sym->kind()));
1604 }
1605 } else {
1606 warn(msg: "undefined base symbol '" + pair.first + "' for alias '" +
1607 pair.second + "'\n");
1608 }
1609 }
1610
1611 for (const InputFile *file : inputFiles) {
1612 if (auto *objFile = dyn_cast<ObjFile>(Val: file)) {
1613 for (const AliasSymbol *alias : objFile->aliases) {
1614 if (const auto &aliased = symtab->find(name: alias->getAliasedName())) {
1615 if (const auto &defined = dyn_cast<Defined>(Val: aliased)) {
1616 symtab->aliasDefined(src: defined, target: alias->getName(), newFile: alias->getFile(),
1617 makePrivateExtern: alias->privateExtern);
1618 } else {
1619 // Common, dylib, and undefined symbols are all valid alias
1620 // referents (undefineds can become valid Defined symbols later on
1621 // in the link.)
1622 error(msg: "TODO: support aliasing to symbols of kind " +
1623 Twine(aliased->kind()));
1624 }
1625 } else {
1626 // This shouldn't happen since MC generates undefined symbols to
1627 // represent the alias referents. Thus we fatal() instead of just
1628 // warning here.
1629 fatal(msg: "unable to find alias referent " + alias->getAliasedName() +
1630 " for " + alias->getName());
1631 }
1632 }
1633 }
1634 }
1635}
1636
1637static void handleExplicitExports() {
1638 static constexpr int kMaxWarnings = 3;
1639 if (config->hasExplicitExports) {
1640 std::atomic<uint64_t> warningsCount{0};
1641 parallelForEach(R: symtab->getSymbols(), Fn: [&warningsCount](Symbol *sym) {
1642 if (auto *defined = dyn_cast<Defined>(Val: sym)) {
1643 if (config->exportedSymbols.match(symbolName: sym->getName())) {
1644 if (defined->privateExtern) {
1645 if (defined->weakDefCanBeHidden) {
1646 // weak_def_can_be_hidden symbols behave similarly to
1647 // private_extern symbols in most cases, except for when
1648 // it is explicitly exported.
1649 // The former can be exported but the latter cannot.
1650 defined->privateExtern = false;
1651 } else {
1652 // Only print the first 3 warnings verbosely, and
1653 // shorten the rest to avoid crowding logs.
1654 if (warningsCount.fetch_add(i: 1, m: std::memory_order_relaxed) <
1655 kMaxWarnings)
1656 warn(msg: "cannot export hidden symbol " + toString(*defined) +
1657 "\n>>> defined in " + toString(file: defined->getFile()));
1658 }
1659 }
1660 } else {
1661 defined->privateExtern = true;
1662 }
1663 } else if (auto *dysym = dyn_cast<DylibSymbol>(Val: sym)) {
1664 dysym->shouldReexport = config->exportedSymbols.match(symbolName: sym->getName());
1665 }
1666 });
1667 if (warningsCount > kMaxWarnings)
1668 warn(msg: "<... " + Twine(warningsCount - kMaxWarnings) +
1669 " more similar warnings...>");
1670 } else if (!config->unexportedSymbols.empty()) {
1671 parallelForEach(R: symtab->getSymbols(), Fn: [](Symbol *sym) {
1672 if (auto *defined = dyn_cast<Defined>(Val: sym))
1673 if (config->unexportedSymbols.match(symbolName: defined->getName()))
1674 defined->privateExtern = true;
1675 });
1676 }
1677}
1678
1679static void eraseInitializerSymbols() {
1680 for (ConcatInputSection *isec : in.initOffsets->inputs())
1681 for (Defined *sym : isec->symbols)
1682 sym->used = false;
1683}
1684
1685static SmallVector<StringRef, 0> getRuntimePaths(opt::InputArgList &args) {
1686 SmallVector<StringRef, 0> vals;
1687 DenseSet<StringRef> seen;
1688 for (const Arg *arg : args.filtered(Ids: OPT_rpath)) {
1689 StringRef val = arg->getValue();
1690 if (seen.insert(V: val).second)
1691 vals.push_back(Elt: val);
1692 else if (config->warnDuplicateRpath)
1693 warn(msg: "duplicate -rpath '" + val + "' ignored [--warn-duplicate-rpath]");
1694 }
1695 return vals;
1696}
1697
1698static SmallVector<StringRef, 0> getAllowableClients(opt::InputArgList &args) {
1699 SmallVector<StringRef, 0> vals;
1700 DenseSet<StringRef> seen;
1701 for (const Arg *arg : args.filtered(Ids: OPT_allowable_client)) {
1702 StringRef val = arg->getValue();
1703 if (seen.insert(V: val).second)
1704 vals.push_back(Elt: val);
1705 }
1706 return vals;
1707}
1708
1709namespace lld {
1710namespace macho {
1711bool link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
1712 llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
1713 // This driver-specific context will be freed later by lldMain().
1714 auto *ctx = new CommonLinkerContext;
1715
1716 ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
1717 ctx->e.cleanupCallback = []() {
1718 resolvedFrameworks.clear();
1719 resolvedLibraries.clear();
1720 cachedReads.clear();
1721 concatOutputSections.clear();
1722 inputFiles.clear();
1723 inputSections.clear();
1724 inputSectionsOrder = 0;
1725 loadedArchives.clear();
1726 loadedObjectFrameworks.clear();
1727 missingAutolinkWarnings.clear();
1728 syntheticSections.clear();
1729 thunkMap.clear();
1730 unprocessedLCLinkerOptions.clear();
1731 ObjCSelRefsHelper::cleanup();
1732
1733 firstTLVDataSection = nullptr;
1734 tar = nullptr;
1735 in = InStruct();
1736
1737 resetLoadedDylibs();
1738 resetOutputSegments();
1739 resetWriter();
1740 InputFile::resetIdCount();
1741
1742 objc::doCleanup();
1743 };
1744
1745 ctx->e.logName = args::getFilenameWithoutExe(path: argsArr[0]);
1746
1747 MachOOptTable parser;
1748 InputArgList args = parser.parse(ctx&: *ctx, argv: argsArr.slice(N: 1));
1749
1750 ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now "
1751 "(use --error-limit=0 to see all errors)";
1752 ctx->e.errorLimit = args::getInteger(args, key: OPT_error_limit_eq, Default: 20);
1753 ctx->e.verbose = args.hasArg(Ids: OPT_verbose);
1754
1755 if (args.hasArg(Ids: OPT_help_hidden)) {
1756 parser.printHelp(ctx&: *ctx, argv0: argsArr[0], /*showHidden=*/true);
1757 return true;
1758 }
1759 if (args.hasArg(Ids: OPT_help)) {
1760 parser.printHelp(ctx&: *ctx, argv0: argsArr[0], /*showHidden=*/false);
1761 return true;
1762 }
1763 if (args.hasArg(Ids: OPT_version)) {
1764 message(msg: getLLDVersion());
1765 return true;
1766 }
1767
1768 config = std::make_unique<Configuration>();
1769 symtab = std::make_unique<SymbolTable>();
1770 config->outputType = getOutputType(args);
1771 target = createTargetInfo(args);
1772 depTracker = std::make_unique<DependencyTracker>(
1773 args: args.getLastArgValue(Id: OPT_dependency_info));
1774
1775 config->ltoo = args::getInteger(args, key: OPT_lto_O, Default: 2);
1776 if (config->ltoo > 3)
1777 error(msg: "--lto-O: invalid optimization level: " + Twine(config->ltoo));
1778 unsigned ltoCgo =
1779 args::getInteger(args, key: OPT_lto_CGO, Default: args::getCGOptLevel(optLevelLTO: config->ltoo));
1780 if (auto level = CodeGenOpt::getLevel(OL: ltoCgo))
1781 config->ltoCgo = *level;
1782 else
1783 error(msg: "--lto-CGO: invalid codegen optimization level: " + Twine(ltoCgo));
1784
1785 if (errorCount())
1786 return false;
1787
1788 if (args.hasArg(Ids: OPT_pagezero_size)) {
1789 uint64_t pagezeroSize = args::getHex(args, key: OPT_pagezero_size, Default: 0);
1790
1791 // ld64 does something really weird. It attempts to realign the value to the
1792 // page size, but assumes the page size is 4K. This doesn't work with most
1793 // of Apple's ARM64 devices, which use a page size of 16K. This means that
1794 // it will first 4K align it by rounding down, then round up to 16K. This
1795 // probably only happened because no one using this arg with anything other
1796 // then 0, so no one checked if it did what is what it says it does.
1797
1798 // So we are not copying this weird behavior and doing the it in a logical
1799 // way, by always rounding down to page size.
1800 if (!isAligned(Lhs: Align(target->getPageSize()), SizeInBytes: pagezeroSize)) {
1801 pagezeroSize -= pagezeroSize % target->getPageSize();
1802 warn(msg: "__PAGEZERO size is not page aligned, rounding down to 0x" +
1803 Twine::utohexstr(Val: pagezeroSize));
1804 }
1805
1806 target->pageZeroSize = pagezeroSize;
1807 }
1808
1809 config->osoPrefix = args.getLastArgValue(Id: OPT_oso_prefix);
1810 if (!config->osoPrefix.empty()) {
1811 // The max path length is 4096, in theory. However that seems quite long
1812 // and seems unlikely that any one would want to strip everything from the
1813 // path. Hence we've picked a reasonably large number here.
1814 SmallString<1024> expanded;
1815 // Expand "." into the current working directory.
1816 if (config->osoPrefix == "." && !fs::current_path(result&: expanded)) {
1817 // Note: LD64 expands "." to be `<current_dir>/
1818 // (ie., it has a slash suffix) whereas current_path() doesn't.
1819 // So we have to append '/' to be consistent because this is
1820 // meaningful for our text based stripping.
1821 expanded += sys::path::get_separator();
1822 } else {
1823 expanded = config->osoPrefix;
1824 }
1825 config->osoPrefix = saver().save(S: expanded.str());
1826 }
1827
1828 bool pie = args.hasFlag(Pos: OPT_pie, Neg: OPT_no_pie, Default: true);
1829 if (!supportsNoPie() && !pie) {
1830 warn(msg: "-no_pie ignored for arm64");
1831 pie = true;
1832 }
1833
1834 config->isPic = config->outputType == MH_DYLIB ||
1835 config->outputType == MH_BUNDLE ||
1836 (config->outputType == MH_EXECUTE && pie);
1837
1838 // Must be set before any InputSections and Symbols are created.
1839 config->deadStrip = args.hasArg(Ids: OPT_dead_strip);
1840 config->interposable = args.hasArg(Ids: OPT_interposable);
1841
1842 config->systemLibraryRoots = getSystemLibraryRoots(args);
1843 if (const char *path = getReproduceOption(args)) {
1844 // Note that --reproduce is a debug option so you can ignore it
1845 // if you are trying to understand the whole picture of the code.
1846 Expected<std::unique_ptr<TarWriter>> errOrWriter =
1847 TarWriter::create(OutputPath: path, BaseDir: path::stem(path));
1848 if (errOrWriter) {
1849 tar = std::move(*errOrWriter);
1850 tar->append(Path: "response.txt", Data: createResponseFile(args));
1851 tar->append(Path: "version.txt", Data: getLLDVersion() + "\n");
1852 } else {
1853 error(msg: "--reproduce: " + toString(E: errOrWriter.takeError()));
1854 }
1855 }
1856
1857 if (auto *arg = args.getLastArg(Ids: OPT_read_workers)) {
1858#if LLVM_ENABLE_THREADS
1859 StringRef v(arg->getValue());
1860 unsigned workers = 0;
1861 if (!llvm::to_integer(S: v, Num&: workers, Base: 0))
1862 error(msg: arg->getSpelling() +
1863 ": expected a non-negative integer, but got '" + arg->getValue() +
1864 "'");
1865 config->readWorkers = workers;
1866#else
1867 warn(arg->getSpelling() +
1868 ": option unavailable because lld was not built with thread support");
1869#endif
1870 }
1871 if (auto *arg = args.getLastArg(Ids: OPT_threads_eq)) {
1872 StringRef v(arg->getValue());
1873 unsigned threads = 0;
1874 if (!llvm::to_integer(S: v, Num&: threads, Base: 0) || threads == 0)
1875 error(msg: arg->getSpelling() + ": expected a positive integer, but got '" +
1876 arg->getValue() + "'");
1877 parallel::strategy = hardware_concurrency(ThreadCount: threads);
1878 config->thinLTOJobs = v;
1879 }
1880 if (auto *arg = args.getLastArg(Ids: OPT_thinlto_jobs_eq))
1881 config->thinLTOJobs = arg->getValue();
1882 if (!get_threadpool_strategy(Num: config->thinLTOJobs))
1883 error(msg: "--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
1884
1885 for (const Arg *arg : args.filtered(Ids: OPT_u)) {
1886 config->explicitUndefineds.push_back(x: symtab->addUndefined(
1887 name: arg->getValue(), /*file=*/nullptr, /*isWeakRef=*/false));
1888 }
1889
1890 for (const Arg *arg : args.filtered(Ids: OPT_U))
1891 config->explicitDynamicLookups.insert(key: arg->getValue());
1892
1893 config->mapFile = args.getLastArgValue(Id: OPT_map);
1894 config->optimize = args::getInteger(args, key: OPT_O, Default: 1);
1895 config->outputFile = args.getLastArgValue(Id: OPT_o, Default: "a.out");
1896 config->finalOutput =
1897 args.getLastArgValue(Id: OPT_final_output, Default: config->outputFile);
1898 config->astPaths = args.getAllArgValues(Id: OPT_add_ast_path);
1899 config->headerPad = args::getHex(args, key: OPT_headerpad, /*Default=*/32);
1900 config->headerPadMaxInstallNames =
1901 args.hasArg(Ids: OPT_headerpad_max_install_names);
1902 config->printDylibSearch =
1903 args.hasArg(Ids: OPT_print_dylib_search) || getenv(name: "RC_TRACE_DYLIB_SEARCHING");
1904 config->printEachFile = args.hasArg(Ids: OPT_t);
1905 config->printWhyLoad = args.hasArg(Ids: OPT_why_load);
1906 config->omitDebugInfo = args.hasArg(Ids: OPT_S);
1907 config->errorForArchMismatch = args.hasArg(Ids: OPT_arch_errors_fatal);
1908 if (const Arg *arg = args.getLastArg(Ids: OPT_bundle_loader)) {
1909 if (config->outputType != MH_BUNDLE)
1910 error(msg: "-bundle_loader can only be used with MachO bundle output");
1911 addFile(path: arg->getValue(), loadType: LoadType::CommandLine, /*isLazy=*/false,
1912 /*isExplicit=*/false, /*isBundleLoader=*/true);
1913 }
1914 for (auto *arg : args.filtered(Ids: OPT_dyld_env)) {
1915 StringRef envPair(arg->getValue());
1916 if (!envPair.contains(C: '='))
1917 error(msg: "-dyld_env's argument is malformed. Expected "
1918 "-dyld_env <ENV_VAR>=<VALUE>, got `" +
1919 envPair + "`");
1920 config->dyldEnvs.push_back(x: envPair);
1921 }
1922 if (!config->dyldEnvs.empty() && config->outputType != MH_EXECUTE)
1923 error(msg: "-dyld_env can only be used when creating executable output");
1924
1925 if (const Arg *arg = args.getLastArg(Ids: OPT_umbrella)) {
1926 if (config->outputType != MH_DYLIB)
1927 warn(msg: "-umbrella used, but not creating dylib");
1928 config->umbrella = arg->getValue();
1929 }
1930 config->ltoObjPath = args.getLastArgValue(Id: OPT_object_path_lto);
1931 config->ltoNewPmPasses = args.getLastArgValue(Id: OPT_lto_newpm_passes);
1932 config->thinLTOCacheDir = args.getLastArgValue(Id: OPT_cache_path_lto);
1933 config->thinLTOCachePolicy = getLTOCachePolicy(args);
1934 config->thinLTOEmitImportsFiles = args.hasArg(Ids: OPT_thinlto_emit_imports_files);
1935 config->thinLTOEmitIndexFiles = args.hasArg(Ids: OPT_thinlto_emit_index_files) ||
1936 args.hasArg(Ids: OPT_thinlto_index_only) ||
1937 args.hasArg(Ids: OPT_thinlto_index_only_eq);
1938 config->thinLTOIndexOnly = args.hasArg(Ids: OPT_thinlto_index_only) ||
1939 args.hasArg(Ids: OPT_thinlto_index_only_eq);
1940 config->thinLTOIndexOnlyArg = args.getLastArgValue(Id: OPT_thinlto_index_only_eq);
1941 config->thinLTOObjectSuffixReplace =
1942 getOldNewOptions(args, id: OPT_thinlto_object_suffix_replace_eq);
1943 std::tie(args&: config->thinLTOPrefixReplaceOld, args&: config->thinLTOPrefixReplaceNew,
1944 args&: config->thinLTOPrefixReplaceNativeObject) =
1945 getOldNewOptionsExtra(args, id: OPT_thinlto_prefix_replace_eq);
1946 if (config->thinLTOEmitIndexFiles && !config->thinLTOIndexOnly) {
1947 if (args.hasArg(Ids: OPT_thinlto_object_suffix_replace_eq))
1948 error(msg: "--thinlto-object-suffix-replace is not supported with "
1949 "--thinlto-emit-index-files");
1950 else if (args.hasArg(Ids: OPT_thinlto_prefix_replace_eq))
1951 error(msg: "--thinlto-prefix-replace is not supported with "
1952 "--thinlto-emit-index-files");
1953 }
1954 if (!config->thinLTOPrefixReplaceNativeObject.empty() &&
1955 config->thinLTOIndexOnlyArg.empty()) {
1956 error(msg: "--thinlto-prefix-replace=old_dir;new_dir;obj_dir must be used with "
1957 "--thinlto-index-only=");
1958 }
1959 config->warnDuplicateRpath =
1960 args.hasFlag(Pos: OPT_warn_duplicate_rpath, Neg: OPT_no_warn_duplicate_rpath, Default: true);
1961 config->runtimePaths = getRuntimePaths(args);
1962 config->allowableClients = getAllowableClients(args);
1963 config->allLoad = args.hasFlag(Pos: OPT_all_load, Neg: OPT_noall_load, Default: false);
1964 config->archMultiple = args.hasArg(Ids: OPT_arch_multiple);
1965 config->applicationExtension = args.hasFlag(
1966 Pos: OPT_application_extension, Neg: OPT_no_application_extension, Default: false);
1967 config->exportDynamic = args.hasArg(Ids: OPT_export_dynamic);
1968 config->forceLoadObjC = args.hasArg(Ids: OPT_ObjC);
1969 config->forceLoadSwift = args.hasArg(Ids: OPT_force_load_swift_libs);
1970 config->deadStripDylibs = args.hasArg(Ids: OPT_dead_strip_dylibs);
1971 config->demangle = args.hasArg(Ids: OPT_demangle);
1972 config->implicitDylibs = !args.hasArg(Ids: OPT_no_implicit_dylibs);
1973 config->emitFunctionStarts =
1974 args.hasFlag(Pos: OPT_function_starts, Neg: OPT_no_function_starts, Default: true);
1975 config->emitDataInCodeInfo =
1976 args.hasFlag(Pos: OPT_data_in_code_info, Neg: OPT_no_data_in_code_info, Default: true);
1977 config->emitChainedFixups = shouldEmitChainedFixups(args);
1978 config->emitInitOffsets =
1979 config->emitChainedFixups || args.hasArg(Ids: OPT_init_offsets);
1980 config->emitRelativeMethodLists = shouldEmitRelativeMethodLists(args);
1981 config->icfLevel = getICFLevel(args);
1982 config->keepICFStabs = args.hasArg(Ids: OPT_keep_icf_stabs);
1983 config->dedupStrings =
1984 args.hasFlag(Pos: OPT_deduplicate_strings, Neg: OPT_no_deduplicate_strings, Default: true);
1985 config->dedupSymbolStrings = !args.hasArg(Ids: OPT_no_deduplicate_symbol_strings);
1986 config->deadStripDuplicates = args.hasArg(Ids: OPT_dead_strip_duplicates);
1987 config->warnDylibInstallName = args.hasFlag(
1988 Pos: OPT_warn_dylib_install_name, Neg: OPT_no_warn_dylib_install_name, Default: false);
1989 config->ignoreOptimizationHints = args.hasArg(Ids: OPT_ignore_optimization_hints);
1990 config->callGraphProfileSort = args.hasFlag(
1991 Pos: OPT_call_graph_profile_sort, Neg: OPT_no_call_graph_profile_sort, Default: true);
1992 config->printSymbolOrder = args.getLastArgValue(Id: OPT_print_symbol_order_eq);
1993 config->forceExactCpuSubtypeMatch =
1994 getenv(name: "LD_DYLIB_CPU_SUBTYPES_MUST_MATCH");
1995 config->objcStubsMode = getObjCStubsMode(args);
1996 config->ignoreAutoLink = args.hasArg(Ids: OPT_ignore_auto_link);
1997 for (const Arg *arg : args.filtered(Ids: OPT_ignore_auto_link_option))
1998 config->ignoreAutoLinkOptions.insert(key: arg->getValue());
1999 config->strictAutoLink = args.hasArg(Ids: OPT_strict_auto_link);
2000 config->ltoDebugPassManager = args.hasArg(Ids: OPT_lto_debug_pass_manager);
2001 config->emitLLVM = args.hasArg(Ids: OPT_lto_emit_llvm);
2002 config->codegenDataGeneratePath =
2003 args.getLastArgValue(Id: OPT_codegen_data_generate_path);
2004 config->csProfileGenerate = args.hasArg(Ids: OPT_cs_profile_generate);
2005 config->csProfilePath = args.getLastArgValue(Id: OPT_cs_profile_path);
2006 config->pgoWarnMismatch =
2007 args.hasFlag(Pos: OPT_pgo_warn_mismatch, Neg: OPT_no_pgo_warn_mismatch, Default: true);
2008 config->warnThinArchiveMissingMembers =
2009 args.hasFlag(Pos: OPT_warn_thin_archive_missing_members,
2010 Neg: OPT_no_warn_thin_archive_missing_members, Default: true);
2011 config->generateUuid = !args.hasArg(Ids: OPT_no_uuid);
2012 config->disableVerify = args.hasArg(Ids: OPT_disable_verify);
2013 config->separateCstringLiteralSections =
2014 args.hasFlag(Pos: OPT_separate_cstring_literal_sections,
2015 Neg: OPT_no_separate_cstring_literal_sections, Default: false);
2016 config->tailMergeStrings =
2017 args.hasFlag(Pos: OPT_tail_merge_strings, Neg: OPT_no_tail_merge_strings, Default: false);
2018 if (auto *arg = args.getLastArg(Ids: OPT_slop_scale_eq)) {
2019 StringRef v(arg->getValue());
2020 unsigned slop = 0;
2021 if (!llvm::to_integer(S: v, Num&: slop))
2022 error(msg: arg->getSpelling() +
2023 ": expected a non-negative integer, but got '" + v + "'");
2024 config->slopScale = slop;
2025 }
2026
2027 auto IncompatWithCGSort = [&](StringRef firstArgStr) {
2028 // Throw an error only if --call-graph-profile-sort is explicitly specified
2029 if (config->callGraphProfileSort)
2030 if (const Arg *arg = args.getLastArgNoClaim(Ids: OPT_call_graph_profile_sort))
2031 error(msg: firstArgStr + " is incompatible with " + arg->getSpelling());
2032 };
2033 if (args.hasArg(Ids: OPT_irpgo_profile_sort) ||
2034 args.hasArg(Ids: OPT_irpgo_profile_sort_eq))
2035 warn(msg: "--irpgo-profile-sort is deprecated. Please use "
2036 "--bp-startup-sort=function");
2037 if (const Arg *arg = args.getLastArg(Ids: OPT_irpgo_profile))
2038 config->irpgoProfilePath = arg->getValue();
2039
2040 if (const Arg *arg = args.getLastArg(Ids: OPT_irpgo_profile_sort)) {
2041 config->irpgoProfilePath = arg->getValue();
2042 config->bpStartupFunctionSort = true;
2043 IncompatWithCGSort(arg->getSpelling());
2044 }
2045 config->bpCompressionSortStartupFunctions =
2046 args.hasFlag(Pos: OPT_bp_compression_sort_startup_functions,
2047 Neg: OPT_no_bp_compression_sort_startup_functions, Default: false);
2048 if (const Arg *arg = args.getLastArg(Ids: OPT_bp_startup_sort)) {
2049 StringRef startupSortStr = arg->getValue();
2050 if (startupSortStr == "function") {
2051 config->bpStartupFunctionSort = true;
2052 } else if (startupSortStr != "none") {
2053 error(msg: "unknown value `" + startupSortStr + "` for " + arg->getSpelling());
2054 }
2055 if (startupSortStr != "none")
2056 IncompatWithCGSort(arg->getSpelling());
2057 }
2058 if (!config->bpStartupFunctionSort &&
2059 config->bpCompressionSortStartupFunctions)
2060 error(msg: "--bp-compression-sort-startup-functions must be used with "
2061 "--bp-startup-sort=function");
2062 if (config->irpgoProfilePath.empty() && config->bpStartupFunctionSort)
2063 error(msg: "--bp-startup-sort=function must be used with "
2064 "--irpgo-profile");
2065 if (const Arg *arg = args.getLastArg(Ids: OPT_bp_compression_sort)) {
2066 StringRef compressionSortStr = arg->getValue();
2067 if (compressionSortStr == "function") {
2068 config->bpFunctionOrderForCompression = true;
2069 } else if (compressionSortStr == "data") {
2070 config->bpDataOrderForCompression = true;
2071 } else if (compressionSortStr == "both") {
2072 config->bpFunctionOrderForCompression = true;
2073 config->bpDataOrderForCompression = true;
2074 } else if (compressionSortStr != "none") {
2075 error(msg: "unknown value `" + compressionSortStr + "` for " +
2076 arg->getSpelling());
2077 }
2078 if (compressionSortStr != "none")
2079 IncompatWithCGSort(arg->getSpelling());
2080 }
2081 config->bpVerboseSectionOrderer = args.hasArg(Ids: OPT_verbose_bp_section_orderer);
2082
2083 for (const Arg *arg : args.filtered(Ids: OPT_alias)) {
2084 config->aliasedSymbols.push_back(
2085 x: std::make_pair(x: arg->getValue(N: 0), y: arg->getValue(N: 1)));
2086 }
2087
2088 if (const char *zero = getenv(name: "ZERO_AR_DATE"))
2089 config->zeroModTime = strcmp(s1: zero, s2: "0") != 0;
2090 if (args.getLastArg(Ids: OPT_reproducible))
2091 config->zeroModTime = true;
2092
2093 std::array<PlatformType, 4> encryptablePlatforms{
2094 PLATFORM_IOS, PLATFORM_WATCHOS, PLATFORM_TVOS, PLATFORM_XROS};
2095 config->emitEncryptionInfo =
2096 args.hasFlag(Pos: OPT_encryptable, Neg: OPT_no_encryption,
2097 Default: is_contained(Range&: encryptablePlatforms, Element: config->platform()));
2098
2099 if (const Arg *arg = args.getLastArg(Ids: OPT_install_name)) {
2100 if (config->warnDylibInstallName && config->outputType != MH_DYLIB)
2101 warn(
2102 msg: arg->getAsString(Args: args) +
2103 ": ignored, only has effect with -dylib [--warn-dylib-install-name]");
2104 else
2105 config->installName = arg->getValue();
2106 } else if (config->outputType == MH_DYLIB) {
2107 config->installName = config->finalOutput;
2108 }
2109
2110 auto getClientName = [&]() {
2111 StringRef cn = path::filename(path: config->finalOutput);
2112 cn.consume_front(Prefix: "lib");
2113 auto firstDotOrUnderscore = cn.find_first_of(Chars: "._");
2114 cn = cn.take_front(N: firstDotOrUnderscore);
2115 return cn;
2116 };
2117 config->clientName = args.getLastArgValue(Id: OPT_client_name, Default: getClientName());
2118
2119 if (args.hasArg(Ids: OPT_mark_dead_strippable_dylib)) {
2120 if (config->outputType != MH_DYLIB)
2121 warn(msg: "-mark_dead_strippable_dylib: ignored, only has effect with -dylib");
2122 else
2123 config->markDeadStrippableDylib = true;
2124 }
2125
2126 if (const Arg *arg = args.getLastArg(Ids: OPT_static, Ids: OPT_dynamic))
2127 config->staticLink = (arg->getOption().getID() == OPT_static);
2128
2129 if (const Arg *arg =
2130 args.getLastArg(Ids: OPT_flat_namespace, Ids: OPT_twolevel_namespace))
2131 config->namespaceKind = arg->getOption().getID() == OPT_twolevel_namespace
2132 ? NamespaceKind::twolevel
2133 : NamespaceKind::flat;
2134
2135 config->undefinedSymbolTreatment = getUndefinedSymbolTreatment(args);
2136
2137 if (config->outputType == MH_EXECUTE)
2138 config->entry = symtab->addUndefined(name: args.getLastArgValue(Id: OPT_e, Default: "_main"),
2139 /*file=*/nullptr,
2140 /*isWeakRef=*/false);
2141
2142 config->librarySearchPaths =
2143 getLibrarySearchPaths(args, roots: config->systemLibraryRoots);
2144 config->frameworkSearchPaths =
2145 getFrameworkSearchPaths(args, roots: config->systemLibraryRoots);
2146 if (const Arg *arg =
2147 args.getLastArg(Ids: OPT_search_paths_first, Ids: OPT_search_dylibs_first))
2148 config->searchDylibsFirst =
2149 arg->getOption().getID() == OPT_search_dylibs_first;
2150
2151 config->dylibCompatibilityVersion =
2152 parseDylibVersion(args, id: OPT_compatibility_version);
2153 config->dylibCurrentVersion = parseDylibVersion(args, id: OPT_current_version);
2154
2155 config->dataConst =
2156 args.hasFlag(Pos: OPT_data_const, Neg: OPT_no_data_const, Default: dataConstDefault(args));
2157 // Populate config->sectionRenameMap with builtin default renames.
2158 // Options -rename_section and -rename_segment are able to override.
2159 initializeSectionRenameMap();
2160 // Reject every special character except '.' and '$'
2161 // TODO(gkm): verify that this is the proper set of invalid chars
2162 StringRef invalidNameChars("!\"#%&'()*+,-/:;<=>?@[\\]^`{|}~");
2163 auto validName = [invalidNameChars](StringRef s) {
2164 if (s.find_first_of(Chars: invalidNameChars) != StringRef::npos)
2165 error(msg: "invalid name for segment or section: " + s);
2166 return s;
2167 };
2168 for (const Arg *arg : args.filtered(Ids: OPT_rename_section)) {
2169 config->sectionRenameMap[{validName(arg->getValue(N: 0)),
2170 validName(arg->getValue(N: 1))}] = {
2171 validName(arg->getValue(N: 2)), validName(arg->getValue(N: 3))};
2172 }
2173 for (const Arg *arg : args.filtered(Ids: OPT_rename_segment)) {
2174 config->segmentRenameMap[validName(arg->getValue(N: 0))] =
2175 validName(arg->getValue(N: 1));
2176 }
2177
2178 config->sectionAlignments = parseSectAlign(args);
2179
2180 for (const Arg *arg : args.filtered(Ids: OPT_segprot)) {
2181 StringRef segName = arg->getValue(N: 0);
2182 uint32_t maxProt = parseProtection(protStr: arg->getValue(N: 1));
2183 uint32_t initProt = parseProtection(protStr: arg->getValue(N: 2));
2184
2185 // FIXME: Check if this works on more platforms.
2186 bool allowsDifferentInitAndMaxProt =
2187 config->platform() == PLATFORM_MACOS ||
2188 config->platform() == PLATFORM_MACCATALYST;
2189 if (allowsDifferentInitAndMaxProt) {
2190 if (initProt > maxProt)
2191 error(msg: "invalid argument '" + arg->getAsString(Args: args) +
2192 "': init must not be more permissive than max");
2193 } else {
2194 if (maxProt != initProt && config->arch() != AK_i386)
2195 error(msg: "invalid argument '" + arg->getAsString(Args: args) +
2196 "': max and init must be the same for non-macOS non-i386 archs");
2197 }
2198
2199 if (segName == segment_names::linkEdit)
2200 error(msg: "-segprot cannot be used to change __LINKEDIT's protections");
2201 config->segmentProtections.push_back(x: {.name: segName, .maxProt: maxProt, .initProt: initProt});
2202 }
2203
2204 config->hasExplicitExports =
2205 args.hasArg(Ids: OPT_no_exported_symbols) ||
2206 args.hasArgNoClaim(Ids: OPT_exported_symbol, Ids: OPT_exported_symbols_list);
2207 handleSymbolPatterns(args, symbolPatterns&: config->exportedSymbols, singleOptionCode: OPT_exported_symbol,
2208 listFileOptionCode: OPT_exported_symbols_list);
2209 handleSymbolPatterns(args, symbolPatterns&: config->unexportedSymbols, singleOptionCode: OPT_unexported_symbol,
2210 listFileOptionCode: OPT_unexported_symbols_list);
2211 if (config->hasExplicitExports && !config->unexportedSymbols.empty())
2212 error(msg: "cannot use both -exported_symbol* and -unexported_symbol* options");
2213
2214 if (args.hasArg(Ids: OPT_no_exported_symbols) && !config->exportedSymbols.empty())
2215 error(msg: "cannot use both -exported_symbol* and -no_exported_symbols options");
2216
2217 // Imitating LD64's:
2218 // -non_global_symbols_no_strip_list and -non_global_symbols_strip_list can't
2219 // both be present.
2220 // But -x can be used with either of these two, in which case, the last arg
2221 // takes effect.
2222 // (TODO: This is kind of confusing - considering disallowing using them
2223 // together for a more straightforward behaviour)
2224 {
2225 bool includeLocal = false;
2226 bool excludeLocal = false;
2227 for (const Arg *arg :
2228 args.filtered(Ids: OPT_x, Ids: OPT_non_global_symbols_no_strip_list,
2229 Ids: OPT_non_global_symbols_strip_list)) {
2230 switch (arg->getOption().getID()) {
2231 case OPT_x:
2232 config->localSymbolsPresence = SymtabPresence::None;
2233 break;
2234 case OPT_non_global_symbols_no_strip_list:
2235 if (excludeLocal) {
2236 error(msg: "cannot use both -non_global_symbols_no_strip_list and "
2237 "-non_global_symbols_strip_list");
2238 } else {
2239 includeLocal = true;
2240 config->localSymbolsPresence = SymtabPresence::SelectivelyIncluded;
2241 parseSymbolPatternsFile(arg, symbolPatterns&: config->localSymbolPatterns);
2242 }
2243 break;
2244 case OPT_non_global_symbols_strip_list:
2245 if (includeLocal) {
2246 error(msg: "cannot use both -non_global_symbols_no_strip_list and "
2247 "-non_global_symbols_strip_list");
2248 } else {
2249 excludeLocal = true;
2250 config->localSymbolsPresence = SymtabPresence::SelectivelyExcluded;
2251 parseSymbolPatternsFile(arg, symbolPatterns&: config->localSymbolPatterns);
2252 }
2253 break;
2254 default:
2255 llvm_unreachable("unexpected option");
2256 }
2257 }
2258 }
2259 // Explicitly-exported literal symbols must be defined, but might
2260 // languish in an archive if unreferenced elsewhere or if they are in the
2261 // non-global strip list. Light a fire under those lazy symbols!
2262 for (const CachedHashStringRef &cachedName : config->exportedSymbols.literals)
2263 symtab->addUndefined(name: cachedName.val(), /*file=*/nullptr,
2264 /*isWeakRef=*/false);
2265
2266 for (const Arg *arg : args.filtered(Ids: OPT_why_live))
2267 config->whyLive.insert(symbolName: arg->getValue());
2268 if (!config->whyLive.empty() && !config->deadStrip)
2269 warn(msg: "-why_live has no effect without -dead_strip, ignoring");
2270
2271 config->saveTemps = args.hasArg(Ids: OPT_save_temps);
2272
2273 config->adhocCodesign = args.hasFlag(
2274 Pos: OPT_adhoc_codesign, Neg: OPT_no_adhoc_codesign,
2275 Default: shouldAdhocSignByDefault(arch: config->arch(), platform: config->platform()));
2276
2277 if (args.hasArg(Ids: OPT_v)) {
2278 message(msg: getLLDVersion(), s&: ctx->e.errs());
2279 message(msg: StringRef("Library search paths:") +
2280 (config->librarySearchPaths.empty()
2281 ? ""
2282 : "\n\t" + join(R&: config->librarySearchPaths, Separator: "\n\t")),
2283 s&: ctx->e.errs());
2284 message(msg: StringRef("Framework search paths:") +
2285 (config->frameworkSearchPaths.empty()
2286 ? ""
2287 : "\n\t" + join(R&: config->frameworkSearchPaths, Separator: "\n\t")),
2288 s&: ctx->e.errs());
2289 }
2290
2291 config->progName = argsArr[0];
2292
2293 config->timeTraceEnabled = args.hasArg(Ids: OPT_time_trace_eq);
2294 config->timeTraceGranularity =
2295 args::getInteger(args, key: OPT_time_trace_granularity_eq, Default: 500);
2296
2297 // Initialize time trace profiler.
2298 if (config->timeTraceEnabled)
2299 timeTraceProfilerInitialize(TimeTraceGranularity: config->timeTraceGranularity, ProcName: config->progName);
2300
2301 {
2302 TimeTraceScope timeScope("ExecuteLinker");
2303
2304 initLLVM(); // must be run before any call to addFile()
2305 createFiles(args);
2306
2307 // Now that all dylibs have been loaded, search for those that should be
2308 // re-exported.
2309 {
2310 auto reexportHandler = [](const Arg *arg,
2311 const std::vector<StringRef> &extensions) {
2312 config->hasReexports = true;
2313 StringRef searchName = arg->getValue();
2314 if (!markReexport(searchName, extensions))
2315 error(msg: arg->getSpelling() + " " + searchName +
2316 " does not match a supplied dylib");
2317 };
2318 std::vector<StringRef> extensions = {".tbd"};
2319 for (const Arg *arg : args.filtered(Ids: OPT_sub_umbrella))
2320 reexportHandler(arg, extensions);
2321
2322 extensions.push_back(x: ".dylib");
2323 for (const Arg *arg : args.filtered(Ids: OPT_sub_library))
2324 reexportHandler(arg, extensions);
2325 }
2326
2327 cl::ResetAllOptionOccurrences();
2328
2329 // Parse LTO options.
2330 if (const Arg *arg = args.getLastArg(Ids: OPT_mcpu))
2331 parseClangOption(opt: saver().save(S: "-mcpu=" + StringRef(arg->getValue())),
2332 msg: arg->getSpelling());
2333
2334 for (const Arg *arg : args.filtered(Ids: OPT_mllvm)) {
2335 parseClangOption(opt: arg->getValue(), msg: arg->getSpelling());
2336 config->mllvmOpts.emplace_back(Args: arg->getValue());
2337 }
2338
2339 config->passPlugins = args::getStrings(args, id: OPT_load_pass_plugins);
2340
2341 createSyntheticSections();
2342 createSyntheticSymbols();
2343 addSynthenticMethnames();
2344
2345 createAliases();
2346 // If we are in "explicit exports" mode, hide everything that isn't
2347 // explicitly exported. Do this before running LTO so that LTO can better
2348 // optimize.
2349 handleExplicitExports();
2350
2351 bool didCompileBitcodeFiles = compileBitcodeFiles();
2352
2353 resolveLCLinkerOptions();
2354
2355 // If either --thinlto-index-only or --lto-emit-llvm is given, we should
2356 // not create object files. Index file creation is already done in
2357 // compileBitcodeFiles, so we are done if that's the case.
2358 if (config->thinLTOIndexOnly || config->emitLLVM)
2359 return errorCount() == 0;
2360
2361 // LTO may emit a non-hidden (extern) object file symbol even if the
2362 // corresponding bitcode symbol is hidden. In particular, this happens for
2363 // cross-module references to hidden symbols under ThinLTO. Thus, if we
2364 // compiled any bitcode files, we must redo the symbol hiding.
2365 if (didCompileBitcodeFiles)
2366 handleExplicitExports();
2367 replaceCommonSymbols();
2368
2369 StringRef orderFile = args.getLastArgValue(Id: OPT_order_file);
2370 if (!orderFile.empty())
2371 priorityBuilder.parseOrderFile(path: orderFile);
2372
2373 referenceStubBinder();
2374
2375 // FIXME: should terminate the link early based on errors encountered so
2376 // far?
2377
2378 for (const Arg *arg : args.filtered(Ids: OPT_sectcreate)) {
2379 StringRef segName = arg->getValue(N: 0);
2380 StringRef sectName = arg->getValue(N: 1);
2381 StringRef fileName = arg->getValue(N: 2);
2382 std::optional<MemoryBufferRef> buffer = readFile(path: fileName);
2383 if (buffer)
2384 inputFiles.insert(X: make<OpaqueFile>(args&: *buffer, args&: segName, args&: sectName));
2385 }
2386
2387 for (const Arg *arg : args.filtered(Ids: OPT_add_empty_section)) {
2388 StringRef segName = arg->getValue(N: 0);
2389 StringRef sectName = arg->getValue(N: 1);
2390 inputFiles.insert(X: make<OpaqueFile>(args: MemoryBufferRef(), args&: segName, args&: sectName));
2391 }
2392
2393 gatherInputSections();
2394
2395 if (!config->codegenDataGeneratePath.empty())
2396 codegenDataGenerate();
2397
2398 if (config->callGraphProfileSort)
2399 priorityBuilder.extractCallGraphProfile();
2400
2401 if (config->deadStrip)
2402 markLive();
2403
2404 // Ensure that no symbols point inside __mod_init_func sections if they are
2405 // removed due to -init_offsets. This must run after dead stripping.
2406 if (config->emitInitOffsets)
2407 eraseInitializerSymbols();
2408
2409 // Categories are not subject to dead-strip. The __objc_catlist section is
2410 // marked as NO_DEAD_STRIP and that propagates into all category data.
2411 if (args.hasArg(Ids: OPT_check_category_conflicts))
2412 objc::checkCategories();
2413
2414 // Category merging uses "->live = false" to erase old category data, so
2415 // it has to run after dead-stripping (markLive).
2416 if (args.hasFlag(Pos: OPT_objc_category_merging, Neg: OPT_no_objc_category_merging,
2417 Default: false))
2418 objc::mergeCategories();
2419
2420 // ICF assumes that all literals have been folded already, so we must run
2421 // foldIdenticalLiterals before foldIdenticalSections.
2422 foldIdenticalLiterals();
2423 if (config->icfLevel != ICFLevel::none) {
2424 if (config->icfLevel == ICFLevel::safe ||
2425 config->icfLevel == ICFLevel::safe_thunks)
2426 markAddrSigSymbols();
2427 foldIdenticalSections(/*onlyCfStrings=*/false);
2428 } else if (config->dedupStrings) {
2429 foldIdenticalSections(/*onlyCfStrings=*/true);
2430 }
2431
2432 // Write to an output file.
2433 if (target->wordSize == 8)
2434 writeResult<LP64>();
2435 else
2436 writeResult<ILP32>();
2437
2438 depTracker->write(version: getLLDVersion(), inputs: inputFiles, output: config->outputFile);
2439 }
2440
2441 if (config->timeTraceEnabled) {
2442 checkError(e: timeTraceProfilerWrite(
2443 PreferredFileName: args.getLastArgValue(Id: OPT_time_trace_eq).str(), FallbackFileName: config->outputFile));
2444
2445 timeTraceProfilerCleanup();
2446 }
2447
2448 if (errorCount() != 0 || config->strictAutoLink)
2449 for (const auto &warning : missingAutolinkWarnings)
2450 warn(msg: warning);
2451
2452 return errorCount() == 0;
2453}
2454} // namespace macho
2455} // namespace lld
2456