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 // TODO: check validity of version strings, which varies by platform
878 // NOTE: ld64 accepts version strings with 5 components
879 // llvm::VersionTuple accepts no more than 4 components
880 // Has Apple ever published version strings with 5 components?
881 if (platformVersion.minimum.tryParse(string: minVersionStr))
882 error(msg: Twine("malformed minimum version: ") + minVersionStr);
883 if (platformVersion.sdk.tryParse(string: sdkVersionStr))
884 error(msg: Twine("malformed sdk version: ") + sdkVersionStr);
885 return platformVersion;
886}
887
888// Has the side-effect of setting Config::platformInfo and
889// potentially Config::secondaryPlatformInfo.
890static void setPlatformVersions(StringRef archName, const ArgList &args) {
891 std::map<PlatformType, PlatformVersion> platformVersions;
892 const PlatformVersion *lastVersionInfo = nullptr;
893 for (const Arg *arg : args.filtered(Ids: OPT_platform_version)) {
894 PlatformVersion version = parsePlatformVersion(arg);
895
896 // For each platform, the last flag wins:
897 // `-platform_version macos 2 3 -platform_version macos 4 5` has the same
898 // effect as just passing `-platform_version macos 4 5`.
899 // FIXME: ld64 warns on multiple flags for one platform. Should we?
900 platformVersions[version.platform] = version;
901 lastVersionInfo = &platformVersions[version.platform];
902 }
903
904 if (platformVersions.empty()) {
905 error(msg: "must specify -platform_version");
906 return;
907 }
908 if (platformVersions.size() > 2) {
909 error(msg: "must specify -platform_version at most twice");
910 return;
911 }
912 if (platformVersions.size() == 2) {
913 bool isZipperedCatalyst = platformVersions.count(x: PLATFORM_MACOS) &&
914 platformVersions.count(x: PLATFORM_MACCATALYST);
915
916 if (!isZipperedCatalyst) {
917 error(msg: "lld supports writing zippered outputs only for "
918 "macos and mac-catalyst");
919 } else if (config->outputType != MH_DYLIB &&
920 config->outputType != MH_BUNDLE) {
921 error(msg: "writing zippered outputs only valid for -dylib and -bundle");
922 }
923
924 config->platformInfo = {
925 .target: MachO::Target(getArchitectureFromName(Name: archName), PLATFORM_MACOS,
926 platformVersions[PLATFORM_MACOS].minimum),
927 .sdk: platformVersions[PLATFORM_MACOS].sdk};
928 config->secondaryPlatformInfo = {
929 .target: MachO::Target(getArchitectureFromName(Name: archName), PLATFORM_MACCATALYST,
930 platformVersions[PLATFORM_MACCATALYST].minimum),
931 .sdk: platformVersions[PLATFORM_MACCATALYST].sdk};
932 return;
933 }
934
935 config->platformInfo = {.target: MachO::Target(getArchitectureFromName(Name: archName),
936 lastVersionInfo->platform,
937 lastVersionInfo->minimum),
938 .sdk: lastVersionInfo->sdk};
939}
940
941// Has the side-effect of setting Config::target.
942static TargetInfo *createTargetInfo(InputArgList &args) {
943 StringRef archName = args.getLastArgValue(Id: OPT_arch);
944 if (archName.empty()) {
945 error(msg: "must specify -arch");
946 return nullptr;
947 }
948
949 setPlatformVersions(archName, args);
950 auto [cpuType, cpuSubtype] = getCPUTypeFromArchitecture(Arch: config->arch());
951 switch (cpuType) {
952 case CPU_TYPE_X86_64:
953 return createX86_64TargetInfo();
954 case CPU_TYPE_ARM64:
955 return createARM64TargetInfo();
956 case CPU_TYPE_ARM64_32:
957 return createARM64_32TargetInfo();
958 default:
959 error(msg: "missing or unsupported -arch " + archName);
960 return nullptr;
961 }
962}
963
964static UndefinedSymbolTreatment
965getUndefinedSymbolTreatment(const ArgList &args) {
966 StringRef treatmentStr = args.getLastArgValue(Id: OPT_undefined);
967 auto treatment =
968 StringSwitch<UndefinedSymbolTreatment>(treatmentStr)
969 .Cases(CaseStrings: {"error", ""}, Value: UndefinedSymbolTreatment::error)
970 .Case(S: "warning", Value: UndefinedSymbolTreatment::warning)
971 .Case(S: "suppress", Value: UndefinedSymbolTreatment::suppress)
972 .Case(S: "dynamic_lookup", Value: UndefinedSymbolTreatment::dynamic_lookup)
973 .Default(Value: UndefinedSymbolTreatment::unknown);
974 if (treatment == UndefinedSymbolTreatment::unknown) {
975 warn(msg: Twine("unknown -undefined TREATMENT '") + treatmentStr +
976 "', defaulting to 'error'");
977 treatment = UndefinedSymbolTreatment::error;
978 } else if (config->namespaceKind == NamespaceKind::twolevel &&
979 (treatment == UndefinedSymbolTreatment::warning ||
980 treatment == UndefinedSymbolTreatment::suppress)) {
981 if (treatment == UndefinedSymbolTreatment::warning)
982 fatal(msg: "'-undefined warning' only valid with '-flat_namespace'");
983 else
984 fatal(msg: "'-undefined suppress' only valid with '-flat_namespace'");
985 treatment = UndefinedSymbolTreatment::error;
986 }
987 return treatment;
988}
989
990static ICFLevel getICFLevel(const ArgList &args) {
991 StringRef icfLevelStr = args.getLastArgValue(Id: OPT_icf_eq);
992 auto icfLevel = StringSwitch<ICFLevel>(icfLevelStr)
993 .Cases(CaseStrings: {"none", ""}, Value: ICFLevel::none)
994 .Case(S: "safe", Value: ICFLevel::safe)
995 .Case(S: "safe_thunks", Value: ICFLevel::safe_thunks)
996 .Case(S: "all", Value: ICFLevel::all)
997 .Default(Value: ICFLevel::unknown);
998
999 if ((icfLevel == ICFLevel::safe_thunks) && (config->arch() != AK_arm64)) {
1000 error(msg: "--icf=safe_thunks is only supported on arm64 targets");
1001 }
1002
1003 if (icfLevel == ICFLevel::unknown) {
1004 warn(msg: Twine("unknown --icf=OPTION `") + icfLevelStr +
1005 "', defaulting to `none'");
1006 icfLevel = ICFLevel::none;
1007 }
1008 return icfLevel;
1009}
1010
1011static ObjCStubsMode getObjCStubsMode(const ArgList &args) {
1012 const Arg *arg = args.getLastArg(Ids: OPT_objc_stubs_fast, Ids: OPT_objc_stubs_small);
1013 if (!arg)
1014 return ObjCStubsMode::fast;
1015
1016 if (arg->getOption().getID() == OPT_objc_stubs_small) {
1017 if (is_contained(Set: {AK_arm64e, AK_arm64}, Element: config->arch()))
1018 return ObjCStubsMode::small;
1019 else
1020 warn(msg: "-objc_stubs_small is not yet implemented, defaulting to "
1021 "-objc_stubs_fast");
1022 }
1023 return ObjCStubsMode::fast;
1024}
1025
1026static void warnIfDeprecatedOption(const Option &opt) {
1027 if (!opt.getGroup().isValid())
1028 return;
1029 if (opt.getGroup().getID() == OPT_grp_deprecated) {
1030 warn(msg: "Option `" + opt.getPrefixedName() + "' is deprecated in ld64:");
1031 warn(msg: opt.getHelpText());
1032 }
1033}
1034
1035static void warnIfUnimplementedOption(const Option &opt) {
1036 if (!opt.getGroup().isValid() || !opt.hasFlag(Val: DriverFlag::HelpHidden))
1037 return;
1038 switch (opt.getGroup().getID()) {
1039 case OPT_grp_deprecated:
1040 // warn about deprecated options elsewhere
1041 break;
1042 case OPT_grp_undocumented:
1043 warn(msg: "Option `" + opt.getPrefixedName() +
1044 "' is undocumented. Should lld implement it?");
1045 break;
1046 case OPT_grp_obsolete:
1047 warn(msg: "Option `" + opt.getPrefixedName() +
1048 "' is obsolete. Please modernize your usage.");
1049 break;
1050 case OPT_grp_ignored:
1051 warn(msg: "Option `" + opt.getPrefixedName() + "' is ignored.");
1052 break;
1053 case OPT_grp_ignored_silently:
1054 break;
1055 default:
1056 warn(msg: "Option `" + opt.getPrefixedName() +
1057 "' is not yet implemented. Stay tuned...");
1058 break;
1059 }
1060}
1061
1062static const char *getReproduceOption(InputArgList &args) {
1063 if (const Arg *arg = args.getLastArg(Ids: OPT_reproduce))
1064 return arg->getValue();
1065 return getenv(name: "LLD_REPRODUCE");
1066}
1067
1068// Parse options of the form "old;new".
1069static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
1070 unsigned id) {
1071 auto *arg = args.getLastArg(Ids: id);
1072 if (!arg)
1073 return {"", ""};
1074
1075 StringRef s = arg->getValue();
1076 std::pair<StringRef, StringRef> ret = s.split(Separator: ';');
1077 if (ret.second.empty())
1078 error(msg: arg->getSpelling() + " expects 'old;new' format, but got " + s);
1079 return ret;
1080}
1081
1082// Parse options of the form "old;new[;extra]".
1083static std::tuple<StringRef, StringRef, StringRef>
1084getOldNewOptionsExtra(opt::InputArgList &args, unsigned id) {
1085 auto [oldDir, second] = getOldNewOptions(args, id);
1086 auto [newDir, extraDir] = second.split(Separator: ';');
1087 return {oldDir, newDir, extraDir};
1088}
1089
1090static void parseClangOption(StringRef opt, const Twine &msg) {
1091 std::string err;
1092 raw_string_ostream os(err);
1093
1094 const char *argv[] = {"lld", opt.data()};
1095 if (cl::ParseCommandLineOptions(argc: 2, argv, Overview: "", Errs: &os))
1096 return;
1097 error(msg: msg + ": " + StringRef(err).trim());
1098}
1099
1100static uint32_t parseDylibVersion(const ArgList &args, unsigned id) {
1101 const Arg *arg = args.getLastArg(Ids: id);
1102 if (!arg)
1103 return 0;
1104
1105 if (config->outputType != MH_DYLIB) {
1106 error(msg: arg->getAsString(Args: args) + ": only valid with -dylib");
1107 return 0;
1108 }
1109
1110 PackedVersion version;
1111 if (!version.parse32(Str: arg->getValue())) {
1112 error(msg: arg->getAsString(Args: args) + ": malformed version");
1113 return 0;
1114 }
1115
1116 return version.rawValue();
1117}
1118
1119static uint32_t parseProtection(StringRef protStr) {
1120 uint32_t prot = 0;
1121 for (char c : protStr) {
1122 switch (c) {
1123 case 'r':
1124 prot |= VM_PROT_READ;
1125 break;
1126 case 'w':
1127 prot |= VM_PROT_WRITE;
1128 break;
1129 case 'x':
1130 prot |= VM_PROT_EXECUTE;
1131 break;
1132 case '-':
1133 break;
1134 default:
1135 error(msg: "unknown -segprot letter '" + Twine(c) + "' in " + protStr);
1136 return 0;
1137 }
1138 }
1139 return prot;
1140}
1141
1142static std::vector<SectionAlign> parseSectAlign(const opt::InputArgList &args) {
1143 std::vector<SectionAlign> sectAligns;
1144 for (const Arg *arg : args.filtered(Ids: OPT_sectalign)) {
1145 StringRef segName = arg->getValue(N: 0);
1146 StringRef sectName = arg->getValue(N: 1);
1147 StringRef alignStr = arg->getValue(N: 2);
1148 alignStr.consume_front_insensitive(Prefix: "0x");
1149 uint32_t align;
1150 if (alignStr.getAsInteger(Radix: 16, Result&: align)) {
1151 error(msg: "-sectalign: failed to parse '" + StringRef(arg->getValue(N: 2)) +
1152 "' as number");
1153 continue;
1154 }
1155 if (!isPowerOf2_32(Value: align)) {
1156 error(msg: "-sectalign: '" + StringRef(arg->getValue(N: 2)) +
1157 "' (in base 16) not a power of two");
1158 continue;
1159 }
1160 sectAligns.push_back(x: {.segName: segName, .sectName: sectName, .align: align});
1161 }
1162 return sectAligns;
1163}
1164
1165PlatformType macho::removeSimulator(PlatformType platform) {
1166 switch (platform) {
1167 case PLATFORM_IOSSIMULATOR:
1168 return PLATFORM_IOS;
1169 case PLATFORM_TVOSSIMULATOR:
1170 return PLATFORM_TVOS;
1171 case PLATFORM_WATCHOSSIMULATOR:
1172 return PLATFORM_WATCHOS;
1173 case PLATFORM_XROS_SIMULATOR:
1174 return PLATFORM_XROS;
1175 default:
1176 return platform;
1177 }
1178}
1179
1180static bool supportsNoPie() {
1181 return !(config->arch() == AK_arm64 || config->arch() == AK_arm64e ||
1182 config->arch() == AK_arm64_32);
1183}
1184
1185static bool shouldAdhocSignByDefault(Architecture arch, PlatformType platform) {
1186 if (arch != AK_arm64 && arch != AK_arm64e)
1187 return false;
1188
1189 return platform == PLATFORM_MACOS || platform == PLATFORM_IOSSIMULATOR ||
1190 platform == PLATFORM_TVOSSIMULATOR ||
1191 platform == PLATFORM_WATCHOSSIMULATOR ||
1192 platform == PLATFORM_XROS_SIMULATOR;
1193}
1194
1195template <std::size_t N>
1196using MinVersions = std::array<std::pair<PlatformType, VersionTuple>, N>;
1197
1198/// Returns true if the platform is greater than the min version.
1199/// Returns false if the platform does not exist.
1200template <std::size_t N>
1201static bool greaterEqMinVersion(const MinVersions<N> &minVersions,
1202 bool ignoreSimulator) {
1203 PlatformType platform = config->platformInfo.target.Platform;
1204 if (ignoreSimulator)
1205 platform = removeSimulator(platform);
1206 auto it = llvm::find_if(minVersions,
1207 [&](const auto &p) { return p.first == platform; });
1208 if (it != minVersions.end())
1209 if (config->platformInfo.target.MinDeployment >= it->second)
1210 return true;
1211 return false;
1212}
1213
1214static bool dataConstDefault(const InputArgList &args) {
1215 static const MinVersions<6> minVersion = {._M_elems: {
1216 {PLATFORM_MACOS, VersionTuple(10, 15)},
1217 {PLATFORM_IOS, VersionTuple(13, 0)},
1218 {PLATFORM_TVOS, VersionTuple(13, 0)},
1219 {PLATFORM_WATCHOS, VersionTuple(6, 0)},
1220 {PLATFORM_XROS, VersionTuple(1, 0)},
1221 {PLATFORM_BRIDGEOS, VersionTuple(4, 0)},
1222 }};
1223 if (!greaterEqMinVersion(minVersions: minVersion, ignoreSimulator: true))
1224 return false;
1225
1226 switch (config->outputType) {
1227 case MH_EXECUTE:
1228 return !(args.hasArg(Ids: OPT_no_pie) && supportsNoPie());
1229 case MH_BUNDLE:
1230 // FIXME: return false when -final_name ...
1231 // has prefix "/System/Library/UserEventPlugins/"
1232 // or matches "/usr/libexec/locationd" "/usr/libexec/terminusd"
1233 return true;
1234 case MH_DYLIB:
1235 return true;
1236 case MH_OBJECT:
1237 return false;
1238 default:
1239 llvm_unreachable(
1240 "unsupported output type for determining data-const default");
1241 }
1242 return false;
1243}
1244
1245static bool shouldEmitChainedFixups(const InputArgList &args) {
1246 const Arg *arg = args.getLastArg(Ids: OPT_fixup_chains, Ids: OPT_no_fixup_chains);
1247 if (arg && arg->getOption().matches(ID: OPT_no_fixup_chains))
1248 return false;
1249
1250 bool requested = arg && arg->getOption().matches(ID: OPT_fixup_chains);
1251 if (!config->isPic) {
1252 if (requested)
1253 error(msg: "-fixup_chains is incompatible with -no_pie");
1254
1255 return false;
1256 }
1257
1258 if (!is_contained(Set: {AK_x86_64, AK_x86_64h, AK_arm64}, Element: config->arch())) {
1259 if (requested)
1260 error(msg: "-fixup_chains is only supported on x86_64 and arm64 targets");
1261
1262 return false;
1263 }
1264
1265 if (args.hasArg(Ids: OPT_preload)) {
1266 if (requested)
1267 error(msg: "-fixup_chains is incompatible with -preload");
1268
1269 return false;
1270 }
1271
1272 if (requested)
1273 return true;
1274
1275 static const MinVersions<9> minVersion = {._M_elems: {
1276 {PLATFORM_IOS, VersionTuple(13, 4)},
1277 {PLATFORM_IOSSIMULATOR, VersionTuple(16, 0)},
1278 {PLATFORM_MACOS, VersionTuple(13, 0)},
1279 {PLATFORM_TVOS, VersionTuple(14, 0)},
1280 {PLATFORM_TVOSSIMULATOR, VersionTuple(15, 0)},
1281 {PLATFORM_WATCHOS, VersionTuple(7, 0)},
1282 {PLATFORM_WATCHOSSIMULATOR, VersionTuple(8, 0)},
1283 {PLATFORM_XROS, VersionTuple(1, 0)},
1284 {PLATFORM_XROS_SIMULATOR, VersionTuple(1, 0)},
1285 }};
1286 return greaterEqMinVersion(minVersions: minVersion, ignoreSimulator: false);
1287}
1288
1289static bool shouldEmitRelativeMethodLists(const InputArgList &args) {
1290 const Arg *arg = args.getLastArg(Ids: OPT_objc_relative_method_lists,
1291 Ids: OPT_no_objc_relative_method_lists);
1292 if (arg && arg->getOption().getID() == OPT_objc_relative_method_lists)
1293 return true;
1294 if (arg && arg->getOption().getID() == OPT_no_objc_relative_method_lists)
1295 return false;
1296
1297 // If no flag is specified, enable this on newer versions by default.
1298 // The min versions is taken from
1299 // ld64(https://github.com/apple-oss-distributions/ld64/blob/47f477cb721755419018f7530038b272e9d0cdea/src/ld/ld.hpp#L310)
1300 // to mimic to operation of ld64
1301 // [here](https://github.com/apple-oss-distributions/ld64/blob/47f477cb721755419018f7530038b272e9d0cdea/src/ld/Options.cpp#L6085-L6101)
1302 static const MinVersions<6> minVersion = {._M_elems: {
1303 {PLATFORM_MACOS, VersionTuple(10, 16)},
1304 {PLATFORM_IOS, VersionTuple(14, 0)},
1305 {PLATFORM_WATCHOS, VersionTuple(7, 0)},
1306 {PLATFORM_TVOS, VersionTuple(14, 0)},
1307 {PLATFORM_BRIDGEOS, VersionTuple(5, 0)},
1308 {PLATFORM_XROS, VersionTuple(1, 0)},
1309 }};
1310 return greaterEqMinVersion(minVersions: minVersion, ignoreSimulator: true);
1311}
1312
1313void SymbolPatterns::clear() {
1314 literals.clear();
1315 globs.clear();
1316}
1317
1318void SymbolPatterns::insert(StringRef symbolName) {
1319 if (symbolName.find_first_of(Chars: "*?[]") == StringRef::npos)
1320 literals.insert(X: CachedHashStringRef(symbolName));
1321 else if (Expected<GlobPattern> pattern = GlobPattern::create(Pat: symbolName))
1322 globs.emplace_back(args&: *pattern);
1323 else
1324 error(msg: "invalid symbol-name pattern: " + symbolName);
1325}
1326
1327bool SymbolPatterns::matchLiteral(StringRef symbolName) const {
1328 return literals.contains(key: CachedHashStringRef(symbolName));
1329}
1330
1331bool SymbolPatterns::matchGlob(StringRef symbolName) const {
1332 for (const GlobPattern &glob : globs)
1333 if (glob.match(S: symbolName))
1334 return true;
1335 return false;
1336}
1337
1338bool SymbolPatterns::match(StringRef symbolName) const {
1339 return matchLiteral(symbolName) || matchGlob(symbolName);
1340}
1341
1342static void parseSymbolPatternsFile(const Arg *arg,
1343 SymbolPatterns &symbolPatterns) {
1344 StringRef path = arg->getValue();
1345 std::optional<MemoryBufferRef> buffer = readFile(path);
1346 if (!buffer) {
1347 error(msg: "Could not read symbol file: " + path);
1348 return;
1349 }
1350 MemoryBufferRef mbref = *buffer;
1351 for (StringRef line : args::getLines(mb: mbref)) {
1352 line = line.take_until(F: [](char c) { return c == '#'; }).trim();
1353 if (!line.empty())
1354 symbolPatterns.insert(symbolName: line);
1355 }
1356}
1357
1358static void handleSymbolPatterns(InputArgList &args,
1359 SymbolPatterns &symbolPatterns,
1360 unsigned singleOptionCode,
1361 unsigned listFileOptionCode) {
1362 for (const Arg *arg : args.filtered(Ids: singleOptionCode))
1363 symbolPatterns.insert(symbolName: arg->getValue());
1364 for (const Arg *arg : args.filtered(Ids: listFileOptionCode))
1365 parseSymbolPatternsFile(arg, symbolPatterns);
1366}
1367
1368static void createFiles(const InputArgList &args) {
1369 TimeTraceScope timeScope("Load input files");
1370 // This loop should be reserved for options whose exact ordering matters.
1371 // Other options should be handled via filtered() and/or getLastArg().
1372 bool isLazy = false;
1373 // If we've processed an opening --start-lib, without a matching --end-lib
1374 bool inLib = false;
1375 DeferredFiles deferredFiles;
1376
1377 for (const Arg *arg : args) {
1378 const Option &opt = arg->getOption();
1379 warnIfDeprecatedOption(opt);
1380 warnIfUnimplementedOption(opt);
1381
1382 switch (opt.getID()) {
1383 case OPT_INPUT:
1384 deferFile(path: rerootPath(path: arg->getValue()), isLazy, deferred&: deferredFiles);
1385 break;
1386 case OPT_needed_library:
1387 if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
1388 Val: addFile(path: rerootPath(path: arg->getValue()), loadType: LoadType::CommandLine)))
1389 dylibFile->forceNeeded = true;
1390 break;
1391 case OPT_reexport_library:
1392 if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
1393 Val: addFile(path: rerootPath(path: arg->getValue()), loadType: LoadType::CommandLine))) {
1394 config->hasReexports = true;
1395 dylibFile->reexport = true;
1396 }
1397 break;
1398 case OPT_weak_library:
1399 if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
1400 Val: addFile(path: rerootPath(path: arg->getValue()), loadType: LoadType::CommandLine)))
1401 dylibFile->forceWeakImport = true;
1402 break;
1403 case OPT_filelist:
1404 addFileList(path: arg->getValue(), isLazy, deferredFiles);
1405 break;
1406 case OPT_force_load:
1407 addFile(path: rerootPath(path: arg->getValue()), loadType: LoadType::CommandLineForce);
1408 break;
1409 case OPT_load_hidden:
1410 addFile(path: rerootPath(path: arg->getValue()), loadType: LoadType::CommandLine,
1411 /*isLazy=*/false, /*isExplicit=*/true, /*isBundleLoader=*/false,
1412 /*isForceHidden=*/true);
1413 break;
1414 case OPT_l:
1415 case OPT_needed_l:
1416 case OPT_reexport_l:
1417 case OPT_weak_l:
1418 case OPT_hidden_l:
1419 addLibrary(name: arg->getValue(), isNeeded: opt.getID() == OPT_needed_l,
1420 isWeak: opt.getID() == OPT_weak_l, isReexport: opt.getID() == OPT_reexport_l,
1421 isHidden: opt.getID() == OPT_hidden_l,
1422 /*isExplicit=*/true, loadType: LoadType::CommandLine);
1423 break;
1424 case OPT_framework:
1425 case OPT_needed_framework:
1426 case OPT_reexport_framework:
1427 case OPT_weak_framework:
1428 addFramework(name: arg->getValue(), isNeeded: opt.getID() == OPT_needed_framework,
1429 isWeak: opt.getID() == OPT_weak_framework,
1430 isReexport: opt.getID() == OPT_reexport_framework, /*isExplicit=*/true,
1431 loadType: LoadType::CommandLine);
1432 break;
1433 case OPT_start_lib:
1434 if (inLib)
1435 error(msg: "nested --start-lib");
1436 inLib = true;
1437 if (!config->allLoad)
1438 isLazy = true;
1439 break;
1440 case OPT_end_lib:
1441 if (!inLib)
1442 error(msg: "stray --end-lib");
1443 inLib = false;
1444 isLazy = false;
1445 break;
1446 default:
1447 break;
1448 }
1449 }
1450
1451#if LLVM_ENABLE_THREADS
1452 if (config->readWorkers) {
1453 multiThreadedPageIn(deferred: deferredFiles);
1454
1455 DeferredFiles archiveContents;
1456 std::vector<ArchiveFile *> archives;
1457 for (auto &file : deferredFiles) {
1458 auto inputFile = processFile(buffer: file.buffer, archiveContents: &archiveContents, path: file.path,
1459 loadType: LoadType::CommandLine, isLazy: file.isLazy);
1460 if (ArchiveFile *archive = dyn_cast<ArchiveFile>(Val: inputFile))
1461 archives.push_back(x: archive);
1462 }
1463
1464 if (!archiveContents.empty())
1465 multiThreadedPageIn(deferred: archiveContents);
1466 for (auto *archive : archives)
1467 archive->addLazySymbols();
1468
1469 pageInQueue.stopAllWork = true;
1470 }
1471#endif
1472}
1473
1474static void gatherInputSections() {
1475 TimeTraceScope timeScope("Gathering input sections");
1476 for (const InputFile *file : inputFiles) {
1477 for (const Section *section : file->sections) {
1478 // Compact unwind entries require special handling elsewhere. (In
1479 // contrast, EH frames are handled like regular ConcatInputSections.)
1480 if (section->name == section_names::compactUnwind)
1481 continue;
1482 // Addrsig sections contain metadata only needed at link time.
1483 if (section->name == section_names::addrSig)
1484 continue;
1485 for (const Subsection &subsection : section->subsections)
1486 addInputSection(inputSection: subsection.isec);
1487 }
1488 if (!file->objCImageInfo.empty())
1489 in.objCImageInfo->addFile(file);
1490 }
1491}
1492
1493static void codegenDataGenerate() {
1494 TimeTraceScope timeScope("Generating codegen data");
1495
1496 OutlinedHashTreeRecord globalOutlineRecord;
1497 StableFunctionMapRecord globalMergeRecord;
1498 for (ConcatInputSection *isec : inputSections) {
1499 if (isec->getSegName() != segment_names::data)
1500 continue;
1501 if (isec->getName() == section_names::outlinedHashTree) {
1502 // Read outlined hash tree from each section.
1503 OutlinedHashTreeRecord localOutlineRecord;
1504 // Use a pointer to allow modification by the function.
1505 auto *data = isec->data.data();
1506 localOutlineRecord.deserialize(Ptr&: data);
1507
1508 // Merge it to the global hash tree.
1509 globalOutlineRecord.merge(Other: localOutlineRecord);
1510 }
1511 if (isec->getName() == section_names::functionMap) {
1512 // Read stable functions from each section.
1513 StableFunctionMapRecord localMergeRecord;
1514 // Use a pointer to allow modification by the function.
1515 auto *data = isec->data.data();
1516 localMergeRecord.deserialize(Ptr&: data);
1517
1518 // Merge it to the global function map.
1519 globalMergeRecord.merge(Other: localMergeRecord);
1520 }
1521 }
1522
1523 globalMergeRecord.finalize();
1524
1525 CodeGenDataWriter Writer;
1526 if (!globalOutlineRecord.empty())
1527 Writer.addRecord(Record&: globalOutlineRecord);
1528 if (!globalMergeRecord.empty())
1529 Writer.addRecord(Record&: globalMergeRecord);
1530
1531 std::error_code EC;
1532 auto fileName = config->codegenDataGeneratePath;
1533 assert(!fileName.empty());
1534 raw_fd_ostream Output(fileName, EC, sys::fs::OF_None);
1535 if (EC)
1536 error(msg: "fail to create " + fileName + ": " + EC.message());
1537
1538 if (auto E = Writer.write(OS&: Output))
1539 error(msg: "fail to write CGData: " + toString(E: std::move(E)));
1540}
1541
1542static void foldIdenticalLiterals() {
1543 TimeTraceScope timeScope("Fold identical literals");
1544 // We always create a cStringSection, regardless of whether dedupLiterals is
1545 // true. If it isn't, we simply create a non-deduplicating CStringSection.
1546 // Either way, we must unconditionally finalize it here.
1547 for (auto *sec : in.cStringSections)
1548 sec->finalizeContents();
1549 in.wordLiteralSection->finalizeContents();
1550}
1551
1552static void addSynthenticMethnames() {
1553 std::string &data = *make<std::string>();
1554 llvm::raw_string_ostream os(data);
1555 for (Symbol *sym : symtab->getSymbols())
1556 if (isa<Undefined>(Val: sym))
1557 if (ObjCStubsSection::isObjCStubSymbol(sym))
1558 os << ObjCStubsSection::getMethname(sym) << '\0';
1559
1560 if (data.empty())
1561 return;
1562
1563 const auto *buf = reinterpret_cast<const uint8_t *>(data.c_str());
1564 Section &section = *make<Section>(/*file=*/args: nullptr, args: segment_names::text,
1565 args: section_names::objcMethname,
1566 args: S_CSTRING_LITERALS, /*addr=*/args: 0);
1567
1568 auto *isec =
1569 make<CStringInputSection>(args&: section, args: ArrayRef<uint8_t>{buf, data.size()},
1570 /*align=*/args: 1, /*dedupLiterals=*/args: true);
1571 isec->splitIntoPieces();
1572 for (auto &piece : isec->pieces)
1573 piece.live = true;
1574 section.subsections.push_back(x: {.offset: 0, .isec: isec});
1575 in.objcMethnameSection->addInput(isec);
1576 in.objcMethnameSection->isec->markLive(off: 0);
1577}
1578
1579static void referenceStubBinder() {
1580 bool needsStubHelper = config->outputType == MH_DYLIB ||
1581 config->outputType == MH_EXECUTE ||
1582 config->outputType == MH_BUNDLE;
1583 if (!needsStubHelper || !symtab->find(name: "dyld_stub_binder"))
1584 return;
1585
1586 // dyld_stub_binder is used by dyld to resolve lazy bindings. This code here
1587 // adds a opportunistic reference to dyld_stub_binder if it happens to exist.
1588 // dyld_stub_binder is in libSystem.dylib, which is usually linked in. This
1589 // isn't needed for correctness, but the presence of that symbol suppresses
1590 // "no symbols" diagnostics from `nm`.
1591 // StubHelperSection::setUp() adds a reference and errors out if
1592 // dyld_stub_binder doesn't exist in case it is actually needed.
1593 symtab->addUndefined(name: "dyld_stub_binder", /*file=*/nullptr, /*isWeak=*/isWeakRef: false);
1594}
1595
1596static void createAliases() {
1597 for (const auto &pair : config->aliasedSymbols) {
1598 if (const auto &sym = symtab->find(name: pair.first)) {
1599 if (const auto &defined = dyn_cast<Defined>(Val: sym)) {
1600 symtab->aliasDefined(src: defined, target: pair.second, newFile: defined->getFile())
1601 ->noDeadStrip = true;
1602 } else {
1603 error(msg: "TODO: support aliasing to symbols of kind " +
1604 Twine(sym->kind()));
1605 }
1606 } else {
1607 warn(msg: "undefined base symbol '" + pair.first + "' for alias '" +
1608 pair.second + "'\n");
1609 }
1610 }
1611
1612 for (const InputFile *file : inputFiles) {
1613 if (auto *objFile = dyn_cast<ObjFile>(Val: file)) {
1614 for (const AliasSymbol *alias : objFile->aliases) {
1615 if (const auto &aliased = symtab->find(name: alias->getAliasedName())) {
1616 if (const auto &defined = dyn_cast<Defined>(Val: aliased)) {
1617 symtab->aliasDefined(src: defined, target: alias->getName(), newFile: alias->getFile(),
1618 makePrivateExtern: alias->privateExtern);
1619 } else {
1620 // Common, dylib, and undefined symbols are all valid alias
1621 // referents (undefineds can become valid Defined symbols later on
1622 // in the link.)
1623 error(msg: "TODO: support aliasing to symbols of kind " +
1624 Twine(aliased->kind()));
1625 }
1626 } else {
1627 // This shouldn't happen since MC generates undefined symbols to
1628 // represent the alias referents. Thus we fatal() instead of just
1629 // warning here.
1630 fatal(msg: "unable to find alias referent " + alias->getAliasedName() +
1631 " for " + alias->getName());
1632 }
1633 }
1634 }
1635 }
1636}
1637
1638static void handleExplicitExports() {
1639 static constexpr int kMaxWarnings = 3;
1640 if (config->hasExplicitExports) {
1641 std::atomic<uint64_t> warningsCount{0};
1642 parallelForEach(R: symtab->getSymbols(), Fn: [&warningsCount](Symbol *sym) {
1643 if (auto *defined = dyn_cast<Defined>(Val: sym)) {
1644 if (config->exportedSymbols.match(symbolName: sym->getName())) {
1645 if (defined->privateExtern) {
1646 if (defined->weakDefCanBeHidden) {
1647 // weak_def_can_be_hidden symbols behave similarly to
1648 // private_extern symbols in most cases, except for when
1649 // it is explicitly exported.
1650 // The former can be exported but the latter cannot.
1651 defined->privateExtern = false;
1652 } else {
1653 // Only print the first 3 warnings verbosely, and
1654 // shorten the rest to avoid crowding logs.
1655 if (warningsCount.fetch_add(i: 1, m: std::memory_order_relaxed) <
1656 kMaxWarnings)
1657 warn(msg: "cannot export hidden symbol " + toString(*defined) +
1658 "\n>>> defined in " + toString(file: defined->getFile()));
1659 }
1660 }
1661 } else {
1662 defined->privateExtern = true;
1663 }
1664 } else if (auto *dysym = dyn_cast<DylibSymbol>(Val: sym)) {
1665 dysym->shouldReexport = config->exportedSymbols.match(symbolName: sym->getName());
1666 }
1667 });
1668 if (warningsCount > kMaxWarnings)
1669 warn(msg: "<... " + Twine(warningsCount - kMaxWarnings) +
1670 " more similar warnings...>");
1671 } else if (!config->unexportedSymbols.empty()) {
1672 parallelForEach(R: symtab->getSymbols(), Fn: [](Symbol *sym) {
1673 if (auto *defined = dyn_cast<Defined>(Val: sym))
1674 if (config->unexportedSymbols.match(symbolName: defined->getName()))
1675 defined->privateExtern = true;
1676 });
1677 }
1678}
1679
1680static void eraseInitializerSymbols() {
1681 for (ConcatInputSection *isec : in.initOffsets->inputs())
1682 for (Defined *sym : isec->symbols)
1683 sym->used = false;
1684}
1685
1686static SmallVector<StringRef, 0> getRuntimePaths(opt::InputArgList &args) {
1687 SmallVector<StringRef, 0> vals;
1688 DenseSet<StringRef> seen;
1689 for (const Arg *arg : args.filtered(Ids: OPT_rpath)) {
1690 StringRef val = arg->getValue();
1691 if (seen.insert(V: val).second)
1692 vals.push_back(Elt: val);
1693 else if (config->warnDuplicateRpath)
1694 warn(msg: "duplicate -rpath '" + val + "' ignored [--warn-duplicate-rpath]");
1695 }
1696 return vals;
1697}
1698
1699static SmallVector<StringRef, 0> getAllowableClients(opt::InputArgList &args) {
1700 SmallVector<StringRef, 0> vals;
1701 DenseSet<StringRef> seen;
1702 for (const Arg *arg : args.filtered(Ids: OPT_allowable_client)) {
1703 StringRef val = arg->getValue();
1704 if (seen.insert(V: val).second)
1705 vals.push_back(Elt: val);
1706 }
1707 return vals;
1708}
1709
1710namespace lld {
1711namespace macho {
1712bool link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
1713 llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
1714 // This driver-specific context will be freed later by lldMain().
1715 auto *ctx = new CommonLinkerContext;
1716
1717 ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
1718 ctx->e.cleanupCallback = []() {
1719 resolvedFrameworks.clear();
1720 resolvedLibraries.clear();
1721 cachedReads.clear();
1722 concatOutputSections.clear();
1723 inputFiles.clear();
1724 inputSections.clear();
1725 inputSectionsOrder = 0;
1726 loadedArchives.clear();
1727 loadedObjectFrameworks.clear();
1728 missingAutolinkWarnings.clear();
1729 syntheticSections.clear();
1730 thunkMap.clear();
1731 unprocessedLCLinkerOptions.clear();
1732 ObjCSelRefsHelper::cleanup();
1733
1734 firstTLVDataSection = nullptr;
1735 tar = nullptr;
1736 in = InStruct();
1737
1738 resetLoadedDylibs();
1739 resetOutputSegments();
1740 resetWriter();
1741 InputFile::resetIdCount();
1742
1743 objc::doCleanup();
1744 };
1745
1746 ctx->e.logName = args::getFilenameWithoutExe(path: argsArr[0]);
1747
1748 MachOOptTable parser;
1749 InputArgList args = parser.parse(ctx&: *ctx, argv: argsArr.slice(N: 1));
1750
1751 ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now "
1752 "(use --error-limit=0 to see all errors)";
1753 ctx->e.errorLimit = args::getInteger(args, key: OPT_error_limit_eq, Default: 20);
1754 ctx->e.verbose = args.hasArg(Ids: OPT_verbose);
1755
1756 if (args.hasArg(Ids: OPT_help_hidden)) {
1757 parser.printHelp(ctx&: *ctx, argv0: argsArr[0], /*showHidden=*/true);
1758 return true;
1759 }
1760 if (args.hasArg(Ids: OPT_help)) {
1761 parser.printHelp(ctx&: *ctx, argv0: argsArr[0], /*showHidden=*/false);
1762 return true;
1763 }
1764 if (args.hasArg(Ids: OPT_version)) {
1765 message(msg: getLLDVersion());
1766 return true;
1767 }
1768
1769 config = std::make_unique<Configuration>();
1770 symtab = std::make_unique<SymbolTable>();
1771 config->outputType = getOutputType(args);
1772 target = createTargetInfo(args);
1773 depTracker = std::make_unique<DependencyTracker>(
1774 args: args.getLastArgValue(Id: OPT_dependency_info));
1775
1776 config->ltoo = args::getInteger(args, key: OPT_lto_O, Default: 2);
1777 if (config->ltoo > 3)
1778 error(msg: "--lto-O: invalid optimization level: " + Twine(config->ltoo));
1779 unsigned ltoCgo =
1780 args::getInteger(args, key: OPT_lto_CGO, Default: args::getCGOptLevel(optLevelLTO: config->ltoo));
1781 if (auto level = CodeGenOpt::getLevel(OL: ltoCgo))
1782 config->ltoCgo = *level;
1783 else
1784 error(msg: "--lto-CGO: invalid codegen optimization level: " + Twine(ltoCgo));
1785
1786 if (errorCount())
1787 return false;
1788
1789 if (args.hasArg(Ids: OPT_pagezero_size)) {
1790 uint64_t pagezeroSize = args::getHex(args, key: OPT_pagezero_size, Default: 0);
1791
1792 // ld64 does something really weird. It attempts to realign the value to the
1793 // page size, but assumes the page size is 4K. This doesn't work with most
1794 // of Apple's ARM64 devices, which use a page size of 16K. This means that
1795 // it will first 4K align it by rounding down, then round up to 16K. This
1796 // probably only happened because no one using this arg with anything other
1797 // then 0, so no one checked if it did what is what it says it does.
1798
1799 // So we are not copying this weird behavior and doing the it in a logical
1800 // way, by always rounding down to page size.
1801 if (!isAligned(Lhs: Align(target->getPageSize()), SizeInBytes: pagezeroSize)) {
1802 pagezeroSize -= pagezeroSize % target->getPageSize();
1803 warn(msg: "__PAGEZERO size is not page aligned, rounding down to 0x" +
1804 Twine::utohexstr(Val: pagezeroSize));
1805 }
1806
1807 target->pageZeroSize = pagezeroSize;
1808 }
1809
1810 config->osoPrefix = args.getLastArgValue(Id: OPT_oso_prefix);
1811 if (!config->osoPrefix.empty()) {
1812 // The max path length is 4096, in theory. However that seems quite long
1813 // and seems unlikely that any one would want to strip everything from the
1814 // path. Hence we've picked a reasonably large number here.
1815 SmallString<1024> expanded;
1816 // Expand "." into the current working directory.
1817 if (config->osoPrefix == "." && !fs::current_path(result&: expanded)) {
1818 // Note: LD64 expands "." to be `<current_dir>/
1819 // (ie., it has a slash suffix) whereas current_path() doesn't.
1820 // So we have to append '/' to be consistent because this is
1821 // meaningful for our text based stripping.
1822 expanded += sys::path::get_separator();
1823 } else {
1824 expanded = config->osoPrefix;
1825 }
1826 config->osoPrefix = saver().save(S: expanded.str());
1827 }
1828
1829 bool pie = args.hasFlag(Pos: OPT_pie, Neg: OPT_no_pie, Default: true);
1830 if (!supportsNoPie() && !pie) {
1831 warn(msg: "-no_pie ignored for arm64");
1832 pie = true;
1833 }
1834
1835 config->isPic = config->outputType == MH_DYLIB ||
1836 config->outputType == MH_BUNDLE ||
1837 (config->outputType == MH_EXECUTE && pie);
1838
1839 // Must be set before any InputSections and Symbols are created.
1840 config->deadStrip = args.hasArg(Ids: OPT_dead_strip);
1841 config->interposable = args.hasArg(Ids: OPT_interposable);
1842
1843 config->systemLibraryRoots = getSystemLibraryRoots(args);
1844 if (const char *path = getReproduceOption(args)) {
1845 // Note that --reproduce is a debug option so you can ignore it
1846 // if you are trying to understand the whole picture of the code.
1847 Expected<std::unique_ptr<TarWriter>> errOrWriter =
1848 TarWriter::create(OutputPath: path, BaseDir: path::stem(path));
1849 if (errOrWriter) {
1850 tar = std::move(*errOrWriter);
1851 tar->append(Path: "response.txt", Data: createResponseFile(args));
1852 tar->append(Path: "version.txt", Data: getLLDVersion() + "\n");
1853 } else {
1854 error(msg: "--reproduce: " + toString(E: errOrWriter.takeError()));
1855 }
1856 }
1857
1858 if (auto *arg = args.getLastArg(Ids: OPT_read_workers)) {
1859#if LLVM_ENABLE_THREADS
1860 StringRef v(arg->getValue());
1861 unsigned workers = 0;
1862 if (!llvm::to_integer(S: v, Num&: workers, Base: 0))
1863 error(msg: arg->getSpelling() +
1864 ": expected a non-negative integer, but got '" + arg->getValue() +
1865 "'");
1866 config->readWorkers = workers;
1867#else
1868 warn(arg->getSpelling() +
1869 ": option unavailable because lld was not built with thread support");
1870#endif
1871 }
1872 if (auto *arg = args.getLastArg(Ids: OPT_threads_eq)) {
1873 StringRef v(arg->getValue());
1874 unsigned threads = 0;
1875 if (!llvm::to_integer(S: v, Num&: threads, Base: 0) || threads == 0)
1876 error(msg: arg->getSpelling() + ": expected a positive integer, but got '" +
1877 arg->getValue() + "'");
1878 parallel::strategy = hardware_concurrency(ThreadCount: threads);
1879 config->thinLTOJobs = v;
1880 }
1881 if (auto *arg = args.getLastArg(Ids: OPT_thinlto_jobs_eq))
1882 config->thinLTOJobs = arg->getValue();
1883 if (!get_threadpool_strategy(Num: config->thinLTOJobs))
1884 error(msg: "--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
1885
1886 for (const Arg *arg : args.filtered(Ids: OPT_u)) {
1887 config->explicitUndefineds.push_back(x: symtab->addUndefined(
1888 name: arg->getValue(), /*file=*/nullptr, /*isWeakRef=*/false));
1889 }
1890
1891 for (const Arg *arg : args.filtered(Ids: OPT_U))
1892 config->explicitDynamicLookups.insert(key: arg->getValue());
1893
1894 config->mapFile = args.getLastArgValue(Id: OPT_map);
1895 config->optimize = args::getInteger(args, key: OPT_O, Default: 1);
1896 config->outputFile = args.getLastArgValue(Id: OPT_o, Default: "a.out");
1897 config->finalOutput =
1898 args.getLastArgValue(Id: OPT_final_output, Default: config->outputFile);
1899 config->astPaths = args.getAllArgValues(Id: OPT_add_ast_path);
1900 config->headerPad = args::getHex(args, key: OPT_headerpad, /*Default=*/32);
1901 config->headerPadMaxInstallNames =
1902 args.hasArg(Ids: OPT_headerpad_max_install_names);
1903 config->printDylibSearch =
1904 args.hasArg(Ids: OPT_print_dylib_search) || getenv(name: "RC_TRACE_DYLIB_SEARCHING");
1905 config->printEachFile = args.hasArg(Ids: OPT_t);
1906 config->printWhyLoad = args.hasArg(Ids: OPT_why_load);
1907 config->omitDebugInfo = args.hasArg(Ids: OPT_S);
1908 config->errorForArchMismatch = args.hasArg(Ids: OPT_arch_errors_fatal);
1909 if (const Arg *arg = args.getLastArg(Ids: OPT_bundle_loader)) {
1910 if (config->outputType != MH_BUNDLE)
1911 error(msg: "-bundle_loader can only be used with MachO bundle output");
1912 addFile(path: arg->getValue(), loadType: LoadType::CommandLine, /*isLazy=*/false,
1913 /*isExplicit=*/false, /*isBundleLoader=*/true);
1914 }
1915 for (auto *arg : args.filtered(Ids: OPT_dyld_env)) {
1916 StringRef envPair(arg->getValue());
1917 if (!envPair.contains(C: '='))
1918 error(msg: "-dyld_env's argument is malformed. Expected "
1919 "-dyld_env <ENV_VAR>=<VALUE>, got `" +
1920 envPair + "`");
1921 config->dyldEnvs.push_back(x: envPair);
1922 }
1923 if (!config->dyldEnvs.empty() && config->outputType != MH_EXECUTE)
1924 error(msg: "-dyld_env can only be used when creating executable output");
1925
1926 if (const Arg *arg = args.getLastArg(Ids: OPT_umbrella)) {
1927 if (config->outputType != MH_DYLIB)
1928 warn(msg: "-umbrella used, but not creating dylib");
1929 config->umbrella = arg->getValue();
1930 }
1931 config->ltoObjPath = args.getLastArgValue(Id: OPT_object_path_lto);
1932 config->ltoNewPmPasses = args.getLastArgValue(Id: OPT_lto_newpm_passes);
1933 config->thinLTOCacheDir = args.getLastArgValue(Id: OPT_cache_path_lto);
1934 config->thinLTOCachePolicy = getLTOCachePolicy(args);
1935 config->thinLTOEmitImportsFiles = args.hasArg(Ids: OPT_thinlto_emit_imports_files);
1936 config->thinLTOEmitIndexFiles = args.hasArg(Ids: OPT_thinlto_emit_index_files) ||
1937 args.hasArg(Ids: OPT_thinlto_index_only) ||
1938 args.hasArg(Ids: OPT_thinlto_index_only_eq);
1939 config->thinLTOIndexOnly = args.hasArg(Ids: OPT_thinlto_index_only) ||
1940 args.hasArg(Ids: OPT_thinlto_index_only_eq);
1941 config->thinLTOIndexOnlyArg = args.getLastArgValue(Id: OPT_thinlto_index_only_eq);
1942 config->thinLTOObjectSuffixReplace =
1943 getOldNewOptions(args, id: OPT_thinlto_object_suffix_replace_eq);
1944 std::tie(args&: config->thinLTOPrefixReplaceOld, args&: config->thinLTOPrefixReplaceNew,
1945 args&: config->thinLTOPrefixReplaceNativeObject) =
1946 getOldNewOptionsExtra(args, id: OPT_thinlto_prefix_replace_eq);
1947 if (config->thinLTOEmitIndexFiles && !config->thinLTOIndexOnly) {
1948 if (args.hasArg(Ids: OPT_thinlto_object_suffix_replace_eq))
1949 error(msg: "--thinlto-object-suffix-replace is not supported with "
1950 "--thinlto-emit-index-files");
1951 else if (args.hasArg(Ids: OPT_thinlto_prefix_replace_eq))
1952 error(msg: "--thinlto-prefix-replace is not supported with "
1953 "--thinlto-emit-index-files");
1954 }
1955 if (!config->thinLTOPrefixReplaceNativeObject.empty() &&
1956 config->thinLTOIndexOnlyArg.empty()) {
1957 error(msg: "--thinlto-prefix-replace=old_dir;new_dir;obj_dir must be used with "
1958 "--thinlto-index-only=");
1959 }
1960 config->warnDuplicateRpath =
1961 args.hasFlag(Pos: OPT_warn_duplicate_rpath, Neg: OPT_no_warn_duplicate_rpath, Default: true);
1962 config->runtimePaths = getRuntimePaths(args);
1963 config->allowableClients = getAllowableClients(args);
1964 config->allLoad = args.hasFlag(Pos: OPT_all_load, Neg: OPT_noall_load, Default: false);
1965 config->archMultiple = args.hasArg(Ids: OPT_arch_multiple);
1966 config->applicationExtension = args.hasFlag(
1967 Pos: OPT_application_extension, Neg: OPT_no_application_extension, Default: false);
1968 config->exportDynamic = args.hasArg(Ids: OPT_export_dynamic);
1969 config->forceLoadObjC = args.hasArg(Ids: OPT_ObjC);
1970 config->forceLoadSwift = args.hasArg(Ids: OPT_force_load_swift_libs);
1971 config->deadStripDylibs = args.hasArg(Ids: OPT_dead_strip_dylibs);
1972 config->demangle = args.hasArg(Ids: OPT_demangle);
1973 config->implicitDylibs = !args.hasArg(Ids: OPT_no_implicit_dylibs);
1974 config->emitFunctionStarts =
1975 args.hasFlag(Pos: OPT_function_starts, Neg: OPT_no_function_starts, Default: true);
1976 config->emitDataInCodeInfo =
1977 args.hasFlag(Pos: OPT_data_in_code_info, Neg: OPT_no_data_in_code_info, Default: true);
1978 config->emitChainedFixups = shouldEmitChainedFixups(args);
1979 config->emitInitOffsets =
1980 config->emitChainedFixups || args.hasArg(Ids: OPT_init_offsets);
1981 config->emitRelativeMethodLists = shouldEmitRelativeMethodLists(args);
1982 config->icfLevel = getICFLevel(args);
1983 config->keepICFStabs = args.hasArg(Ids: OPT_keep_icf_stabs);
1984 config->dedupStrings =
1985 args.hasFlag(Pos: OPT_deduplicate_strings, Neg: OPT_no_deduplicate_strings, Default: true);
1986 config->dedupSymbolStrings = !args.hasArg(Ids: OPT_no_deduplicate_symbol_strings);
1987 config->deadStripDuplicates = args.hasArg(Ids: OPT_dead_strip_duplicates);
1988 config->warnDylibInstallName = args.hasFlag(
1989 Pos: OPT_warn_dylib_install_name, Neg: OPT_no_warn_dylib_install_name, Default: false);
1990 config->ignoreOptimizationHints = args.hasArg(Ids: OPT_ignore_optimization_hints);
1991 config->callGraphProfileSort = args.hasFlag(
1992 Pos: OPT_call_graph_profile_sort, Neg: OPT_no_call_graph_profile_sort, Default: true);
1993 config->printSymbolOrder = args.getLastArgValue(Id: OPT_print_symbol_order_eq);
1994 config->forceExactCpuSubtypeMatch =
1995 getenv(name: "LD_DYLIB_CPU_SUBTYPES_MUST_MATCH");
1996 config->objcStubsMode = getObjCStubsMode(args);
1997 config->ignoreAutoLink = args.hasArg(Ids: OPT_ignore_auto_link);
1998 for (const Arg *arg : args.filtered(Ids: OPT_ignore_auto_link_option))
1999 config->ignoreAutoLinkOptions.insert(key: arg->getValue());
2000 config->strictAutoLink = args.hasArg(Ids: OPT_strict_auto_link);
2001 config->ltoDebugPassManager = args.hasArg(Ids: OPT_lto_debug_pass_manager);
2002 config->emitLLVM = args.hasArg(Ids: OPT_lto_emit_llvm);
2003 config->codegenDataGeneratePath =
2004 args.getLastArgValue(Id: OPT_codegen_data_generate_path);
2005 config->csProfileGenerate = args.hasArg(Ids: OPT_cs_profile_generate);
2006 config->csProfilePath = args.getLastArgValue(Id: OPT_cs_profile_path);
2007 config->pgoWarnMismatch =
2008 args.hasFlag(Pos: OPT_pgo_warn_mismatch, Neg: OPT_no_pgo_warn_mismatch, Default: true);
2009 config->warnThinArchiveMissingMembers =
2010 args.hasFlag(Pos: OPT_warn_thin_archive_missing_members,
2011 Neg: OPT_no_warn_thin_archive_missing_members, Default: true);
2012 config->generateUuid = !args.hasArg(Ids: OPT_no_uuid);
2013 config->disableVerify = args.hasArg(Ids: OPT_disable_verify);
2014 config->separateCstringLiteralSections =
2015 args.hasFlag(Pos: OPT_separate_cstring_literal_sections,
2016 Neg: OPT_no_separate_cstring_literal_sections, Default: false);
2017 config->tailMergeStrings =
2018 args.hasFlag(Pos: OPT_tail_merge_strings, Neg: OPT_no_tail_merge_strings, Default: false);
2019 if (auto *arg = args.getLastArg(Ids: OPT_slop_scale_eq)) {
2020 StringRef v(arg->getValue());
2021 unsigned slop = 0;
2022 if (!llvm::to_integer(S: v, Num&: slop))
2023 error(msg: arg->getSpelling() +
2024 ": expected a non-negative integer, but got '" + v + "'");
2025 config->slopScale = slop;
2026 }
2027
2028 auto IncompatWithCGSort = [&](StringRef firstArgStr) {
2029 // Throw an error only if --call-graph-profile-sort is explicitly specified
2030 if (config->callGraphProfileSort)
2031 if (const Arg *arg = args.getLastArgNoClaim(Ids: OPT_call_graph_profile_sort))
2032 error(msg: firstArgStr + " is incompatible with " + arg->getSpelling());
2033 };
2034 if (args.hasArg(Ids: OPT_irpgo_profile_sort) ||
2035 args.hasArg(Ids: OPT_irpgo_profile_sort_eq))
2036 warn(msg: "--irpgo-profile-sort is deprecated. Please use "
2037 "--bp-startup-sort=function");
2038 if (const Arg *arg = args.getLastArg(Ids: OPT_irpgo_profile))
2039 config->irpgoProfilePath = arg->getValue();
2040
2041 if (const Arg *arg = args.getLastArg(Ids: OPT_irpgo_profile_sort)) {
2042 config->irpgoProfilePath = arg->getValue();
2043 config->bpStartupFunctionSort = true;
2044 IncompatWithCGSort(arg->getSpelling());
2045 }
2046 config->bpCompressionSortStartupFunctions =
2047 args.hasFlag(Pos: OPT_bp_compression_sort_startup_functions,
2048 Neg: OPT_no_bp_compression_sort_startup_functions, Default: false);
2049 if (const Arg *arg = args.getLastArg(Ids: OPT_bp_startup_sort)) {
2050 StringRef startupSortStr = arg->getValue();
2051 if (startupSortStr == "function") {
2052 config->bpStartupFunctionSort = true;
2053 } else if (startupSortStr != "none") {
2054 error(msg: "unknown value `" + startupSortStr + "` for " + arg->getSpelling());
2055 }
2056 if (startupSortStr != "none")
2057 IncompatWithCGSort(arg->getSpelling());
2058 }
2059 if (!config->bpStartupFunctionSort &&
2060 config->bpCompressionSortStartupFunctions)
2061 error(msg: "--bp-compression-sort-startup-functions must be used with "
2062 "--bp-startup-sort=function");
2063 if (config->irpgoProfilePath.empty() && config->bpStartupFunctionSort)
2064 error(msg: "--bp-startup-sort=function must be used with "
2065 "--irpgo-profile");
2066 if (const Arg *arg = args.getLastArg(Ids: OPT_bp_compression_sort)) {
2067 StringRef compressionSortStr = arg->getValue();
2068 if (compressionSortStr == "function") {
2069 config->bpFunctionOrderForCompression = true;
2070 } else if (compressionSortStr == "data") {
2071 config->bpDataOrderForCompression = true;
2072 } else if (compressionSortStr == "both") {
2073 config->bpFunctionOrderForCompression = true;
2074 config->bpDataOrderForCompression = true;
2075 } else if (compressionSortStr != "none") {
2076 error(msg: "unknown value `" + compressionSortStr + "` for " +
2077 arg->getSpelling());
2078 }
2079 if (compressionSortStr != "none")
2080 IncompatWithCGSort(arg->getSpelling());
2081 }
2082 config->bpVerboseSectionOrderer = args.hasArg(Ids: OPT_verbose_bp_section_orderer);
2083
2084 for (const Arg *arg : args.filtered(Ids: OPT_alias)) {
2085 config->aliasedSymbols.push_back(
2086 x: std::make_pair(x: arg->getValue(N: 0), y: arg->getValue(N: 1)));
2087 }
2088
2089 if (const char *zero = getenv(name: "ZERO_AR_DATE"))
2090 config->zeroModTime = strcmp(s1: zero, s2: "0") != 0;
2091 if (args.getLastArg(Ids: OPT_reproducible))
2092 config->zeroModTime = true;
2093
2094 std::array<PlatformType, 4> encryptablePlatforms{
2095 PLATFORM_IOS, PLATFORM_WATCHOS, PLATFORM_TVOS, PLATFORM_XROS};
2096 config->emitEncryptionInfo =
2097 args.hasFlag(Pos: OPT_encryptable, Neg: OPT_no_encryption,
2098 Default: is_contained(Range&: encryptablePlatforms, Element: config->platform()));
2099
2100 if (const Arg *arg = args.getLastArg(Ids: OPT_install_name)) {
2101 if (config->warnDylibInstallName && config->outputType != MH_DYLIB)
2102 warn(
2103 msg: arg->getAsString(Args: args) +
2104 ": ignored, only has effect with -dylib [--warn-dylib-install-name]");
2105 else
2106 config->installName = arg->getValue();
2107 } else if (config->outputType == MH_DYLIB) {
2108 config->installName = config->finalOutput;
2109 }
2110
2111 auto getClientName = [&]() {
2112 StringRef cn = path::filename(path: config->finalOutput);
2113 cn.consume_front(Prefix: "lib");
2114 auto firstDotOrUnderscore = cn.find_first_of(Chars: "._");
2115 cn = cn.take_front(N: firstDotOrUnderscore);
2116 return cn;
2117 };
2118 config->clientName = args.getLastArgValue(Id: OPT_client_name, Default: getClientName());
2119
2120 if (args.hasArg(Ids: OPT_mark_dead_strippable_dylib)) {
2121 if (config->outputType != MH_DYLIB)
2122 warn(msg: "-mark_dead_strippable_dylib: ignored, only has effect with -dylib");
2123 else
2124 config->markDeadStrippableDylib = true;
2125 }
2126
2127 if (const Arg *arg = args.getLastArg(Ids: OPT_static, Ids: OPT_dynamic))
2128 config->staticLink = (arg->getOption().getID() == OPT_static);
2129
2130 if (const Arg *arg =
2131 args.getLastArg(Ids: OPT_flat_namespace, Ids: OPT_twolevel_namespace))
2132 config->namespaceKind = arg->getOption().getID() == OPT_twolevel_namespace
2133 ? NamespaceKind::twolevel
2134 : NamespaceKind::flat;
2135
2136 config->undefinedSymbolTreatment = getUndefinedSymbolTreatment(args);
2137
2138 if (config->outputType == MH_EXECUTE)
2139 config->entry = symtab->addUndefined(name: args.getLastArgValue(Id: OPT_e, Default: "_main"),
2140 /*file=*/nullptr,
2141 /*isWeakRef=*/false);
2142
2143 config->librarySearchPaths =
2144 getLibrarySearchPaths(args, roots: config->systemLibraryRoots);
2145 config->frameworkSearchPaths =
2146 getFrameworkSearchPaths(args, roots: config->systemLibraryRoots);
2147 if (const Arg *arg =
2148 args.getLastArg(Ids: OPT_search_paths_first, Ids: OPT_search_dylibs_first))
2149 config->searchDylibsFirst =
2150 arg->getOption().getID() == OPT_search_dylibs_first;
2151
2152 config->dylibCompatibilityVersion =
2153 parseDylibVersion(args, id: OPT_compatibility_version);
2154 config->dylibCurrentVersion = parseDylibVersion(args, id: OPT_current_version);
2155
2156 config->dataConst =
2157 args.hasFlag(Pos: OPT_data_const, Neg: OPT_no_data_const, Default: dataConstDefault(args));
2158 // Populate config->sectionRenameMap with builtin default renames.
2159 // Options -rename_section and -rename_segment are able to override.
2160 initializeSectionRenameMap();
2161 // Reject every special character except '.' and '$'
2162 // TODO(gkm): verify that this is the proper set of invalid chars
2163 StringRef invalidNameChars("!\"#%&'()*+,-/:;<=>?@[\\]^`{|}~");
2164 auto validName = [invalidNameChars](StringRef s) {
2165 if (s.find_first_of(Chars: invalidNameChars) != StringRef::npos)
2166 error(msg: "invalid name for segment or section: " + s);
2167 return s;
2168 };
2169 for (const Arg *arg : args.filtered(Ids: OPT_rename_section)) {
2170 config->sectionRenameMap[{validName(arg->getValue(N: 0)),
2171 validName(arg->getValue(N: 1))}] = {
2172 validName(arg->getValue(N: 2)), validName(arg->getValue(N: 3))};
2173 }
2174 for (const Arg *arg : args.filtered(Ids: OPT_rename_segment)) {
2175 config->segmentRenameMap[validName(arg->getValue(N: 0))] =
2176 validName(arg->getValue(N: 1));
2177 }
2178
2179 config->sectionAlignments = parseSectAlign(args);
2180
2181 for (const Arg *arg : args.filtered(Ids: OPT_segprot)) {
2182 StringRef segName = arg->getValue(N: 0);
2183 uint32_t maxProt = parseProtection(protStr: arg->getValue(N: 1));
2184 uint32_t initProt = parseProtection(protStr: arg->getValue(N: 2));
2185
2186 // FIXME: Check if this works on more platforms.
2187 bool allowsDifferentInitAndMaxProt =
2188 config->platform() == PLATFORM_MACOS ||
2189 config->platform() == PLATFORM_MACCATALYST;
2190 if (allowsDifferentInitAndMaxProt) {
2191 if (initProt > maxProt)
2192 error(msg: "invalid argument '" + arg->getAsString(Args: args) +
2193 "': init must not be more permissive than max");
2194 } else {
2195 if (maxProt != initProt && config->arch() != AK_i386)
2196 error(msg: "invalid argument '" + arg->getAsString(Args: args) +
2197 "': max and init must be the same for non-macOS non-i386 archs");
2198 }
2199
2200 if (segName == segment_names::linkEdit)
2201 error(msg: "-segprot cannot be used to change __LINKEDIT's protections");
2202 config->segmentProtections.push_back(x: {.name: segName, .maxProt: maxProt, .initProt: initProt});
2203 }
2204
2205 config->hasExplicitExports =
2206 args.hasArg(Ids: OPT_no_exported_symbols) ||
2207 args.hasArgNoClaim(Ids: OPT_exported_symbol, Ids: OPT_exported_symbols_list);
2208 handleSymbolPatterns(args, symbolPatterns&: config->exportedSymbols, singleOptionCode: OPT_exported_symbol,
2209 listFileOptionCode: OPT_exported_symbols_list);
2210 handleSymbolPatterns(args, symbolPatterns&: config->unexportedSymbols, singleOptionCode: OPT_unexported_symbol,
2211 listFileOptionCode: OPT_unexported_symbols_list);
2212 if (config->hasExplicitExports && !config->unexportedSymbols.empty())
2213 error(msg: "cannot use both -exported_symbol* and -unexported_symbol* options");
2214
2215 if (args.hasArg(Ids: OPT_no_exported_symbols) && !config->exportedSymbols.empty())
2216 error(msg: "cannot use both -exported_symbol* and -no_exported_symbols options");
2217
2218 // Imitating LD64's:
2219 // -non_global_symbols_no_strip_list and -non_global_symbols_strip_list can't
2220 // both be present.
2221 // But -x can be used with either of these two, in which case, the last arg
2222 // takes effect.
2223 // (TODO: This is kind of confusing - considering disallowing using them
2224 // together for a more straightforward behaviour)
2225 {
2226 bool includeLocal = false;
2227 bool excludeLocal = false;
2228 for (const Arg *arg :
2229 args.filtered(Ids: OPT_x, Ids: OPT_non_global_symbols_no_strip_list,
2230 Ids: OPT_non_global_symbols_strip_list)) {
2231 switch (arg->getOption().getID()) {
2232 case OPT_x:
2233 config->localSymbolsPresence = SymtabPresence::None;
2234 break;
2235 case OPT_non_global_symbols_no_strip_list:
2236 if (excludeLocal) {
2237 error(msg: "cannot use both -non_global_symbols_no_strip_list and "
2238 "-non_global_symbols_strip_list");
2239 } else {
2240 includeLocal = true;
2241 config->localSymbolsPresence = SymtabPresence::SelectivelyIncluded;
2242 parseSymbolPatternsFile(arg, symbolPatterns&: config->localSymbolPatterns);
2243 }
2244 break;
2245 case OPT_non_global_symbols_strip_list:
2246 if (includeLocal) {
2247 error(msg: "cannot use both -non_global_symbols_no_strip_list and "
2248 "-non_global_symbols_strip_list");
2249 } else {
2250 excludeLocal = true;
2251 config->localSymbolsPresence = SymtabPresence::SelectivelyExcluded;
2252 parseSymbolPatternsFile(arg, symbolPatterns&: config->localSymbolPatterns);
2253 }
2254 break;
2255 default:
2256 llvm_unreachable("unexpected option");
2257 }
2258 }
2259 }
2260 // Explicitly-exported literal symbols must be defined, but might
2261 // languish in an archive if unreferenced elsewhere or if they are in the
2262 // non-global strip list. Light a fire under those lazy symbols!
2263 for (const CachedHashStringRef &cachedName : config->exportedSymbols.literals)
2264 symtab->addUndefined(name: cachedName.val(), /*file=*/nullptr,
2265 /*isWeakRef=*/false);
2266
2267 for (const Arg *arg : args.filtered(Ids: OPT_why_live))
2268 config->whyLive.insert(symbolName: arg->getValue());
2269 if (!config->whyLive.empty() && !config->deadStrip)
2270 warn(msg: "-why_live has no effect without -dead_strip, ignoring");
2271
2272 config->saveTemps = args.hasArg(Ids: OPT_save_temps);
2273
2274 config->adhocCodesign = args.hasFlag(
2275 Pos: OPT_adhoc_codesign, Neg: OPT_no_adhoc_codesign,
2276 Default: shouldAdhocSignByDefault(arch: config->arch(), platform: config->platform()));
2277
2278 if (args.hasArg(Ids: OPT_v)) {
2279 message(msg: getLLDVersion(), s&: ctx->e.errs());
2280 message(msg: StringRef("Library search paths:") +
2281 (config->librarySearchPaths.empty()
2282 ? ""
2283 : "\n\t" + join(R&: config->librarySearchPaths, Separator: "\n\t")),
2284 s&: ctx->e.errs());
2285 message(msg: StringRef("Framework search paths:") +
2286 (config->frameworkSearchPaths.empty()
2287 ? ""
2288 : "\n\t" + join(R&: config->frameworkSearchPaths, Separator: "\n\t")),
2289 s&: ctx->e.errs());
2290 }
2291
2292 config->progName = argsArr[0];
2293
2294 config->timeTraceEnabled = args.hasArg(Ids: OPT_time_trace_eq);
2295 config->timeTraceGranularity =
2296 args::getInteger(args, key: OPT_time_trace_granularity_eq, Default: 500);
2297
2298 // Initialize time trace profiler.
2299 if (config->timeTraceEnabled)
2300 timeTraceProfilerInitialize(TimeTraceGranularity: config->timeTraceGranularity, ProcName: config->progName);
2301
2302 {
2303 TimeTraceScope timeScope("ExecuteLinker");
2304
2305 initLLVM(); // must be run before any call to addFile()
2306 createFiles(args);
2307
2308 // Now that all dylibs have been loaded, search for those that should be
2309 // re-exported.
2310 {
2311 auto reexportHandler = [](const Arg *arg,
2312 const std::vector<StringRef> &extensions) {
2313 config->hasReexports = true;
2314 StringRef searchName = arg->getValue();
2315 if (!markReexport(searchName, extensions))
2316 error(msg: arg->getSpelling() + " " + searchName +
2317 " does not match a supplied dylib");
2318 };
2319 std::vector<StringRef> extensions = {".tbd"};
2320 for (const Arg *arg : args.filtered(Ids: OPT_sub_umbrella))
2321 reexportHandler(arg, extensions);
2322
2323 extensions.push_back(x: ".dylib");
2324 for (const Arg *arg : args.filtered(Ids: OPT_sub_library))
2325 reexportHandler(arg, extensions);
2326 }
2327
2328 cl::ResetAllOptionOccurrences();
2329
2330 // Parse LTO options.
2331 if (const Arg *arg = args.getLastArg(Ids: OPT_mcpu))
2332 parseClangOption(opt: saver().save(S: "-mcpu=" + StringRef(arg->getValue())),
2333 msg: arg->getSpelling());
2334
2335 for (const Arg *arg : args.filtered(Ids: OPT_mllvm)) {
2336 parseClangOption(opt: arg->getValue(), msg: arg->getSpelling());
2337 config->mllvmOpts.emplace_back(Args: arg->getValue());
2338 }
2339
2340 config->passPlugins = args::getStrings(args, id: OPT_load_pass_plugins);
2341
2342 createSyntheticSections();
2343 createSyntheticSymbols();
2344 addSynthenticMethnames();
2345
2346 createAliases();
2347 // If we are in "explicit exports" mode, hide everything that isn't
2348 // explicitly exported. Do this before running LTO so that LTO can better
2349 // optimize.
2350 handleExplicitExports();
2351
2352 bool didCompileBitcodeFiles = compileBitcodeFiles();
2353
2354 resolveLCLinkerOptions();
2355
2356 // If either --thinlto-index-only or --lto-emit-llvm is given, we should
2357 // not create object files. Index file creation is already done in
2358 // compileBitcodeFiles, so we are done if that's the case.
2359 if (config->thinLTOIndexOnly || config->emitLLVM)
2360 return errorCount() == 0;
2361
2362 // LTO may emit a non-hidden (extern) object file symbol even if the
2363 // corresponding bitcode symbol is hidden. In particular, this happens for
2364 // cross-module references to hidden symbols under ThinLTO. Thus, if we
2365 // compiled any bitcode files, we must redo the symbol hiding.
2366 if (didCompileBitcodeFiles)
2367 handleExplicitExports();
2368 replaceCommonSymbols();
2369
2370 StringRef orderFile = args.getLastArgValue(Id: OPT_order_file);
2371 if (!orderFile.empty())
2372 priorityBuilder.parseOrderFile(path: orderFile);
2373
2374 referenceStubBinder();
2375
2376 // FIXME: should terminate the link early based on errors encountered so
2377 // far?
2378
2379 for (const Arg *arg : args.filtered(Ids: OPT_sectcreate)) {
2380 StringRef segName = arg->getValue(N: 0);
2381 StringRef sectName = arg->getValue(N: 1);
2382 StringRef fileName = arg->getValue(N: 2);
2383 std::optional<MemoryBufferRef> buffer = readFile(path: fileName);
2384 if (buffer)
2385 inputFiles.insert(X: make<OpaqueFile>(args&: *buffer, args&: segName, args&: sectName));
2386 }
2387
2388 for (const Arg *arg : args.filtered(Ids: OPT_add_empty_section)) {
2389 StringRef segName = arg->getValue(N: 0);
2390 StringRef sectName = arg->getValue(N: 1);
2391 inputFiles.insert(X: make<OpaqueFile>(args: MemoryBufferRef(), args&: segName, args&: sectName));
2392 }
2393
2394 gatherInputSections();
2395
2396 if (!config->codegenDataGeneratePath.empty())
2397 codegenDataGenerate();
2398
2399 if (config->callGraphProfileSort)
2400 priorityBuilder.extractCallGraphProfile();
2401
2402 if (config->deadStrip)
2403 markLive();
2404
2405 // Ensure that no symbols point inside __mod_init_func sections if they are
2406 // removed due to -init_offsets. This must run after dead stripping.
2407 if (config->emitInitOffsets)
2408 eraseInitializerSymbols();
2409
2410 // Categories are not subject to dead-strip. The __objc_catlist section is
2411 // marked as NO_DEAD_STRIP and that propagates into all category data.
2412 if (args.hasArg(Ids: OPT_check_category_conflicts))
2413 objc::checkCategories();
2414
2415 // Category merging uses "->live = false" to erase old category data, so
2416 // it has to run after dead-stripping (markLive).
2417 if (args.hasFlag(Pos: OPT_objc_category_merging, Neg: OPT_no_objc_category_merging,
2418 Default: false))
2419 objc::mergeCategories();
2420
2421 // ICF assumes that all literals have been folded already, so we must run
2422 // foldIdenticalLiterals before foldIdenticalSections.
2423 foldIdenticalLiterals();
2424 if (config->icfLevel != ICFLevel::none) {
2425 if (config->icfLevel == ICFLevel::safe ||
2426 config->icfLevel == ICFLevel::safe_thunks)
2427 markAddrSigSymbols();
2428 foldIdenticalSections(/*onlyCfStrings=*/false);
2429 } else if (config->dedupStrings) {
2430 foldIdenticalSections(/*onlyCfStrings=*/true);
2431 }
2432
2433 // Write to an output file.
2434 if (target->wordSize == 8)
2435 writeResult<LP64>();
2436 else
2437 writeResult<ILP32>();
2438
2439 depTracker->write(version: getLLDVersion(), inputs: inputFiles, output: config->outputFile);
2440 }
2441
2442 if (config->timeTraceEnabled) {
2443 checkError(e: timeTraceProfilerWrite(
2444 PreferredFileName: args.getLastArgValue(Id: OPT_time_trace_eq).str(), FallbackFileName: config->outputFile));
2445
2446 timeTraceProfilerCleanup();
2447 }
2448
2449 if (errorCount() != 0 || config->strictAutoLink)
2450 for (const auto &warning : missingAutolinkWarnings)
2451 warn(msg: warning);
2452
2453 return errorCount() == 0;
2454}
2455} // namespace macho
2456} // namespace lld
2457