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

source code of lld/MachO/Driver.cpp