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

source code of lld/MachO/Driver.cpp