Lines Matching +full:- +full:- +full:config
1 //===- Driver.cpp ---------------------------------------------------------===//
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
19 // be harmful when you are doing cross-linking. Therefore, in LLD, we
23 //===----------------------------------------------------------------------===//
26 #include "Config.h"
53 #include "llvm/Config/llvm-config.h"
81 ConfigWrapper elf::config;
88 if (config->noinhibitExec)
130 // This driver-specific context will be freed later by unsafeLldMain().
133 ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
134 ctx->e.cleanupCallback = []() {
149 ctx->e.logName = args::getFilenameWithoutExe(args[0]);
150 ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now (use "
151 "--error-limit=0 to see all errors)";
153 config = ConfigWrapper();
161 config->progName = args[0];
170 // Parses a linker -m option.
227 bool addToTar = file->isThin() && tar;
228 for (const Archive::Child &c : file->children(err)) {
234 tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer());
242 std::vector<std::unique_ptr<MemoryBuffer>> mbs = file->takeThinBuffers();
254 if (!config->fatLTOObjects)
274 if (config->formatBinary) {
297 // Handle archives and --start-lib/--end-lib using the same code path. This
301 // utilization rates and it is a net performance win. --start-lib scans
302 // symbols in the same order that llvm-ar adds them to the index, so in the
308 // references for --warn-backrefs.
328 if (config->isStatic) {
334 // DT_SONAME and falls back to filename. If a file was specified by -lfoo,
340 f->init();
361 error("unable to find library -l" + name, ErrorTag::LibNotFound, {name});
378 // The MIPS ABI as of 2016 does not support the GNU-style symbol lookup
380 if (config->emachine == EM_MIPS && config->gnuHash)
383 if (config->emachine == EM_ARM) {
384 if (!config->cmseImplib) {
385 if (!config->cmseInputLib.empty())
386 error("--in-implib may not be used without --cmse-implib");
387 if (!config->cmseOutputLib.empty())
388 error("--out-implib may not be used without --cmse-implib");
391 if (config->cmseImplib)
392 error("--cmse-implib is only supported on ARM targets");
393 if (!config->cmseInputLib.empty())
394 error("--in-implib is only supported on ARM targets");
395 if (!config->cmseOutputLib.empty())
396 error("--out-implib is only supported on ARM targets");
399 if (config->fixCortexA53Errata843419 && config->emachine != EM_AARCH64)
400 error("--fix-cortex-a53-843419 is only supported on AArch64 targets");
402 if (config->fixCortexA8 && config->emachine != EM_ARM)
403 error("--fix-cortex-a8 is only supported on ARM targets");
405 if (config->armBe8 && config->emachine != EM_ARM)
406 error("--be8 is only supported on ARM targets");
408 if (config->fixCortexA8 && !config->isLE)
409 error("--fix-cortex-a8 is not supported on big endian targets");
411 if (config->tocOptimize && config->emachine != EM_PPC64)
412 error("--toc-optimize is only supported on PowerPC64 targets");
414 if (config->pcRelOptimize && config->emachine != EM_PPC64)
415 error("--pcrel-optimize is only supported on PowerPC64 targets");
417 if (config->relaxGP && config->emachine != EM_RISCV)
418 error("--relax-gp is only supported on RISC-V targets");
420 if (config->pie && config->shared)
421 error("-shared and -pie may not be used together");
423 if (!config->shared && !config->filterList.empty())
424 error("-F may not be used without -shared");
426 if (!config->shared && !config->auxiliaryList.empty())
427 error("-f may not be used without -shared");
429 if (config->strip == StripPolicy::All && config->emitRelocs)
430 error("--strip-all and --emit-relocs may not be used together");
432 if (config->zText && config->zIfuncNoplt)
433 error("-z text and -z ifunc-noplt may not be used together");
435 if (config->relocatable) {
436 if (config->shared)
437 error("-r and -shared may not be used together");
438 if (config->gdbIndex)
439 error("-r and --gdb-index may not be used together");
440 if (config->icf != ICFLevel::None)
441 error("-r and --icf may not be used together");
442 if (config->pie)
443 error("-r and -pie may not be used together");
444 if (config->exportDynamic)
445 error("-r and --export-dynamic may not be used together");
446 if (config->debugNames)
447 error("-r and --debug-names may not be used together");
450 if (config->executeOnly) {
451 if (config->emachine != EM_AARCH64)
452 error("--execute-only is only supported on AArch64 targets");
454 if (config->singleRoRx && !script->hasSectionsCommand)
455 error("--execute-only and --no-rosegment cannot be used together");
458 if (config->zRetpolineplt && config->zForceIbt)
459 error("-z force-ibt may not be used with -z retpolineplt");
461 if (config->emachine != EM_AARCH64) {
462 if (config->zPacPlt)
463 error("-z pac-plt only supported on AArch64");
464 if (config->zForceBti)
465 error("-z force-bti only supported on AArch64");
466 if (config->zBtiReport != "none")
467 error("-z bti-report only supported on AArch64");
468 if (config->zPauthReport != "none")
469 error("-z pauth-report only supported on AArch64");
470 if (config->zGcsReport != "none")
471 error("-z gcs-report only supported on AArch64");
472 if (config->zGcs != GcsPolicy::Implicit)
473 error("-z gcs only supported on AArch64");
476 if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
477 config->zCetReport != "none")
478 error("-z cet-report only supported on X86 and X86_64");
483 return arg->getValue();
490 if (key == arg->getValue()) {
492 arg->claim();
500 StringRef v = arg->getValue();
507 arg->claim();
515 StringRef v = arg->getValue();
516 if (v == "noseparate-code")
518 else if (v == "separate-code")
520 else if (v == "separate-loadable-segments")
524 arg->claim();
532 StringRef v = arg->getValue();
541 arg->claim();
549 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
550 if (kv.first == "start-stop-visibility") {
551 arg->claim();
561 error("unknown -z start-stop-visibility= value: " +
571 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
573 arg->claim();
581 error("unknown -z gcs= value: " + kv.second);
587 // Report a warning for an unknown -z option.
591 args::getZOptionValue(args, OPT_z, "max-page-size", 0);
592 args::getZOptionValue(args, OPT_z, "common-page-size", 0);
595 if (!arg->isClaimed())
596 warn("unknown -z value: " + StringRef(arg->getValue()));
614 // Handle -help
620 // Handle -v or -version.
623 // scripts generated by GNU Libtool up to 2021-10 to recognize LLD as
625 // <https://lists.gnu.org/archive/html/libtool/2017-01/msg00007.html>.
633 // the latest version and re-generate scripts. So we have this hack.
638 // Note that --reproduce is a debug option so you can ignore it
644 tar->append("response.txt", createResponseFile(args));
645 tar->append("version.txt", getLLDVersion() + "\n");
650 error("--reproduce: " + toString(errOrWriter.takeError()));
657 // The behavior of -v or --version is a bit strange, but this is
665 if (config->timeTraceEnabled)
666 timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);
685 if (config->timeTraceEnabled) {
687 args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile));
704 // -shared implies --unresolved-symbols=ignore-all because missing
706 bool diagRegular = !config->shared, diagShlib = !config->shared;
709 switch (arg->getOption().getID()) {
711 StringRef s = arg->getValue();
712 if (s == "ignore-all") {
715 } else if (s == "ignore-in-object-files") {
718 } else if (s == "ignore-in-shared-libs") {
721 } else if (s == "report-all") {
725 error("unknown --unresolved-symbols value: " + s);
733 if (StringRef(arg->getValue()) == "defs")
735 else if (StringRef(arg->getValue()) == "undefs")
739 arg->claim();
750 config->unresolvedSymbols =
752 config->unresolvedSymbolsInShlib =
757 StringRef s = args.getLastArgValue(OPT_target2, "got-rel");
762 if (s == "got-rel")
764 error("unknown --target2 option: " + s);
773 error("unknown --oformat value: " + s);
782 if (arg->getOption().getID() == OPT_discard_all)
784 if (arg->getOption().getID() == OPT_discard_locals)
793 if (arg->getOption().getID() == OPT_no_dynamic_linker) {
794 // --no-dynamic-linker suppresses undefined weak symbols in .dynsym
795 config->noDynamicLinker = true;
798 return arg->getValue();
804 if (config->androidMemtagStack)
805 warn("--android-memtag-mode is unspecified, leaving "
806 "--android-memtag-stack a no-op");
807 else if (config->androidMemtagHeap)
808 warn("--android-memtag-mode is unspecified, leaving "
809 "--android-memtag-heap a no-op");
820 error("unknown --android-memtag-mode value: \"" + memtagModeArg +
827 if (!arg || arg->getOption().getID() == OPT_icf_none)
829 if (arg->getOption().getID() == OPT_icf_safe)
841 if (arg->getOption().getID() == OPT_strip_all)
861 std::tie(name, addr) = StringRef(arg->getValue()).split('=');
866 ret[".text"] = parseSectionAddress(arg->getValue(), args, *arg);
868 ret[".data"] = parseSectionAddress(arg->getValue(), args, *arg);
870 ret[".bss"] = parseSectionAddress(arg->getValue(), args, *arg);
881 error("unknown --sort-section rule: " + s);
892 error("unknown --orphan-handling mode: " + s);
896 // Parse --build-id or --build-id=<style>. We handle "tree" as a
898 // --build-id=sha1 are actually tree hashes for performance reasons.
905 StringRef s = arg->getValue();
918 error("unknown --build-id style: " + s);
932 error("unknown --pack-dyn-relocs format: " + s);
940 for (Symbol *sym : file->getSymbols())
941 map[sym->getName()] = sym;
943 auto findSection = [&](StringRef name) -> InputSectionBase * {
946 if (config->warnSymbolOrdering)
953 return dyn_cast_or_null<InputSectionBase>(dr->section);
969 config->callGraphProfile[std::make_pair(from, to)] += count;
980 if (inputObj->cgProfileSectionIndex == SHN_UNDEF)
984 inputObj->template getELFShdrs<ELFT>();
986 const ELFFile<ELFT> &obj = inputObj->getObj();
989 objSections[inputObj->cgProfileSectionIndex]));
993 if (sec.sh_info == inputObj->cgProfileSectionIndex) {
1007 symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
1014 symbolIndices.push_back(rel.getSymbol(config->isMips64EL));
1039 auto *fromSym = dyn_cast<Defined>(&obj->getSymbol(fromIndex));
1040 auto *toSym = dyn_cast<Defined>(&obj->getSymbol(toIndex));
1044 auto *from = dyn_cast_or_null<InputSectionBase>(fromSym->section);
1045 auto *to = dyn_cast_or_null<InputSectionBase>(toSym->section);
1047 config->callGraphProfile[{from, to}] += cgpe.cgp_weight;
1066 for (const Elf_Sym &s : f->template getGlobalELFSyms<ELFT>()) {
1068 StringRef name = check(s.getName(f->getStringTable()));
1076 for (const Elf_Sym &s : f->template getELFSyms<ELFT>()) {
1078 StringRef name = check(s.getName(f->getStringTable()));
1091 StringRef knownSafeName = arg->getValue();
1093 error("--lto-known-safe-vtables=: expected symbol to start with _ZTV, "
1098 error("--lto-known-safe-vtables=: " + toString(pat.takeError()));
1100 [&](StringRef s) { return pat->match(s); });
1107 "--lto-validate-all-vtables-have-type-infos: RTTI missing for vtable "
1109 s + ", --lto-whole-program-visibility disabled");
1120 error("unknown --call-graph-profile-sort= value: " + s);
1140 if (const opt::Arg *alias = arg->getAlias())
1141 return alias->getSpelling();
1142 return arg->getSpelling();
1151 StringRef s = arg->getValue();
1170 if (!names.insert(s) && config->warnSymbolOrdering)
1180 config->emachine);
1181 // If -z rel or -z rela is specified, use the last option.
1183 StringRef s(arg->getValue());
1190 arg->claim();
1199 const char *argv[] = {config->progName.data(), opt.data()};
1206 // Checks the parameter of the bti-report and cet-report options.
1211 // Process a remap pattern 'from-glob=to-file'.
1216 error(location + ": parse error, not 'from-glob=to-file'");
1220 config->remapInputs[fields[0]] = fields[1];
1222 config->remapInputsWildcards.emplace_back(std::move(*pat), fields[1]);
1230 // Initializes Config members by the command line options.
1236 config->allowMultipleDefinition =
1240 config->androidMemtagHeap =
1242 config->androidMemtagStack = args.hasFlag(OPT_android_memtag_stack,
1244 config->fatLTOObjects =
1246 config->androidMemtagMode = getMemtagMode(args);
1247 config->auxiliaryList = args::getStrings(args, OPT_auxiliary);
1248 config->armBe8 = args.hasArg(OPT_be8);
1252 if (arg->getOption().matches(OPT_Bsymbolic_non_weak_functions))
1253 config->bsymbolic = BsymbolicKind::NonWeakFunctions;
1254 else if (arg->getOption().matches(OPT_Bsymbolic_functions))
1255 config->bsymbolic = BsymbolicKind::Functions;
1256 else if (arg->getOption().matches(OPT_Bsymbolic_non_weak))
1257 config->bsymbolic = BsymbolicKind::NonWeak;
1258 else if (arg->getOption().matches(OPT_Bsymbolic))
1259 config->bsymbolic = BsymbolicKind::All;
1261 config->callGraphProfileSort = getCGProfileSortKind(args);
1262 config->checkSections =
1264 config->chroot = args.getLastArgValue(OPT_chroot);
1266 config->compressDebugSections =
1267 getCompressionType(arg->getValue(), "--compress-debug-sections");
1269 config->cref = args.hasArg(OPT_cref);
1270 config->optimizeBBJumps =
1272 config->debugNames = args.hasFlag(OPT_debug_names, OPT_no_debug_names, false);
1273 config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
1274 config->dependencyFile = args.getLastArgValue(OPT_dependency_file);
1275 config->dependentLibraries = args.hasFlag(OPT_dependent_libraries, OPT_no_dependent_libraries, true);
1276 config->disableVerify = args.hasArg(OPT_disable_verify);
1277 config->discard = getDiscard(args);
1278 config->dwoDir = args.getLastArgValue(OPT_plugin_opt_dwo_dir_eq);
1279 config->dynamicLinker = getDynamicLinker(args);
1280 config->ehFrameHdr =
1282 config->emitLLVM = args.hasArg(OPT_lto_emit_llvm);
1283 config->emitRelocs = args.hasArg(OPT_emit_relocs);
1284 config->enableNewDtags =
1286 config->enableNonContiguousRegions =
1288 config->entry = args.getLastArgValue(OPT_entry);
1293 config->executeOnly =
1295 config->exportDynamic =
1298 config->filterList = args::getStrings(args, OPT_filter);
1299 config->fini = args.getLastArgValue(OPT_fini, "_fini");
1300 config->fixCortexA53Errata843419 = args.hasArg(OPT_fix_cortex_a53_843419) &&
1302 config->cmseImplib = args.hasArg(OPT_cmse_implib);
1303 config->cmseInputLib = args.getLastArgValue(OPT_in_implib);
1304 config->cmseOutputLib = args.getLastArgValue(OPT_out_implib);
1305 config->fixCortexA8 =
1307 config->fortranCommon =
1309 config->gcSections = args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false);
1310 config->gnuUnique = args.hasFlag(OPT_gnu_unique, OPT_no_gnu_unique, true);
1311 config->gdbIndex = args.hasFlag(OPT_gdb_index, OPT_no_gdb_index, false);
1312 config->icf = getICF(args);
1313 config->ignoreDataAddressEquality =
1315 config->ignoreFunctionAddressEquality =
1317 config->init = args.getLastArgValue(OPT_init, "_init");
1318 config->ltoAAPipeline = args.getLastArgValue(OPT_lto_aa_pipeline);
1319 config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
1320 config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
1321 config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,
1323 config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);
1324 config->ltoEmitAsm = args.hasArg(OPT_lto_emit_asm);
1325 config->ltoNewPmPasses = args.getLastArgValue(OPT_lto_newpm_passes);
1326 config->ltoWholeProgramVisibility =
1329 config->ltoValidateAllVtablesHaveTypeInfos =
1332 config->ltoo = args::getInteger(args, OPT_lto_O, 2);
1333 if (config->ltoo > 3)
1334 error("invalid optimization level for LTO: " + Twine(config->ltoo));
1336 args::getInteger(args, OPT_lto_CGO, args::getCGOptLevel(config->ltoo));
1338 config->ltoCgo = *level;
1341 config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path_eq);
1342 config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
1343 config->ltoSampleProfile = args.getLastArgValue(OPT_lto_sample_profile);
1344 config->ltoBBAddrMap =
1347 config->ltoBasicBlockSections =
1349 config->ltoUniqueBasicBlockSectionNames =
1352 config->mapFile = args.getLastArgValue(OPT_Map);
1353 config->mipsGotSize = args::getInteger(args, OPT_mips_got_size, 0xfff0);
1354 config->mergeArmExidx =
1356 config->mmapOutputFile =
1358 config->nmagic = args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);
1359 config->noinhibitExec = args.hasArg(OPT_noinhibit_exec);
1360 config->nostdlib = args.hasArg(OPT_nostdlib);
1361 config->oFormatBinary = isOutputFormatBinary(args);
1362 config->omagic = args.hasFlag(OPT_omagic, OPT_no_omagic, false);
1363 config->optRemarksFilename = args.getLastArgValue(OPT_opt_remarks_filename);
1364 config->optStatsFilename = args.getLastArgValue(OPT_plugin_opt_stats_file);
1368 auto resultOrErr = remarks::parseHotnessThresholdOption(arg->getValue());
1370 error(arg->getSpelling() + ": invalid argument '" + arg->getValue() +
1373 config->optRemarksHotnessThreshold = *resultOrErr;
1376 config->optRemarksPasses = args.getLastArgValue(OPT_opt_remarks_passes);
1377 config->optRemarksWithHotness = args.hasArg(OPT_opt_remarks_with_hotness);
1378 config->optRemarksFormat = args.getLastArgValue(OPT_opt_remarks_format);
1379 config->optimize = args::getInteger(args, OPT_O, 1);
1380 config->orphanHandling = getOrphanHandling(args);
1381 config->outputFile = args.getLastArgValue(OPT_o);
1382 config->packageMetadata = args.getLastArgValue(OPT_package_metadata);
1383 config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
1384 config->printIcfSections =
1386 config->printGcSections =
1388 config->printMemoryUsage = args.hasArg(OPT_print_memory_usage);
1389 config->printArchiveStats = args.getLastArgValue(OPT_print_archive_stats);
1390 config->printSymbolOrder =
1392 config->rejectMismatch = !args.hasArg(OPT_no_warn_mismatch);
1393 config->relax = args.hasFlag(OPT_relax, OPT_no_relax, true);
1394 config->relaxGP = args.hasFlag(OPT_relax_gp, OPT_no_relax_gp, false);
1395 config->rpath = getRpath(args);
1396 config->relocatable = args.hasArg(OPT_relocatable);
1397 config->resolveGroups =
1401 // --save-temps implies saving all temps.
1403 config->saveTempsArgs.insert(s);
1406 StringRef s = arg->getValue();
1408 config->saveTempsArgs.insert(s);
1410 error("unknown --save-temps value: " + s);
1414 config->searchPaths = args::getStrings(args, OPT_library_path);
1415 config->sectionStartMap = getSectionStartMap(args);
1416 config->shared = args.hasArg(OPT_shared);
1417 config->singleRoRx = !args.hasFlag(OPT_rosegment, OPT_no_rosegment, true);
1418 config->soName = args.getLastArgValue(OPT_soname);
1419 config->sortSection = getSortSection(args);
1420 config->splitStackAdjustSize = args::getInteger(args, OPT_split_stack_adjust_size, 16384);
1421 config->strip = getStrip(args);
1422 config->sysroot = args.getLastArgValue(OPT_sysroot);
1423 config->target1Rel = args.hasFlag(OPT_target1_rel, OPT_target1_abs, false);
1424 config->target2 = getTarget2(args);
1425 config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
1426 config->thinLTOCachePolicy = CHECK(
1428 "--thinlto-cache-policy: invalid cache policy");
1429 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1430 config->thinLTOEmitIndexFiles = args.hasArg(OPT_thinlto_emit_index_files) ||
1433 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1435 config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);
1436 config->thinLTOObjectSuffixReplace =
1438 std::tie(config->thinLTOPrefixReplaceOld, config->thinLTOPrefixReplaceNew,
1439 config->thinLTOPrefixReplaceNativeObject) =
1441 if (config->thinLTOEmitIndexFiles && !config->thinLTOIndexOnly) {
1443 error("--thinlto-object-suffix-replace is not supported with "
1444 "--thinlto-emit-index-files");
1446 error("--thinlto-prefix-replace is not supported with "
1447 "--thinlto-emit-index-files");
1449 if (!config->thinLTOPrefixReplaceNativeObject.empty() &&
1450 config->thinLTOIndexOnlyArg.empty()) {
1451 error("--thinlto-prefix-replace=old_dir;new_dir;obj_dir must be used with "
1452 "--thinlto-index-only=");
1454 config->thinLTOModulesToCompile =
1456 config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq);
1457 config->timeTraceGranularity =
1459 config->trace = args.hasArg(OPT_trace);
1460 config->undefined = args::getStrings(args, OPT_undefined);
1461 config->undefinedVersion =
1463 config->unique = args.hasArg(OPT_unique);
1464 config->useAndroidRelrTags = args.hasFlag(
1466 config->warnBackrefs =
1468 config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
1469 config->warnSymbolOrdering =
1471 config->whyExtract = args.getLastArgValue(OPT_why_extract);
1472 config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);
1473 config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);
1474 config->zForceBti = hasZOption(args, "force-bti");
1475 config->zForceIbt = hasZOption(args, "force-ibt");
1476 config->zGcs = getZGcs(args);
1477 config->zGlobal = hasZOption(args, "global");
1478 config->zGnustack = getZGnuStack(args);
1479 config->zHazardplt = hasZOption(args, "hazardplt");
1480 config->zIfuncNoplt = hasZOption(args, "ifunc-noplt");
1481 config->zInitfirst = hasZOption(args, "initfirst");
1482 config->zInterpose = hasZOption(args, "interpose");
1483 config->zKeepTextSectionPrefix = getZFlag(
1484 args, "keep-text-section-prefix", "nokeep-text-section-prefix", false);
1485 config->zLrodataAfterBss =
1486 getZFlag(args, "lrodata-after-bss", "nolrodata-after-bss", false);
1487 config->zNodefaultlib = hasZOption(args, "nodefaultlib");
1488 config->zNodelete = hasZOption(args, "nodelete");
1489 config->zNodlopen = hasZOption(args, "nodlopen");
1490 config->zNow = getZFlag(args, "now", "lazy", false);
1491 config->zOrigin = hasZOption(args, "origin");
1492 config->zPacPlt = hasZOption(args, "pac-plt");
1493 config->zRelro = getZFlag(args, "relro", "norelro", true);
1494 config->zRetpolineplt = hasZOption(args, "retpolineplt");
1495 config->zRodynamic = hasZOption(args, "rodynamic");
1496 config->zSeparate = getZSeparate(args);
1497 config->zShstk = hasZOption(args, "shstk");
1498 config->zStackSize = args::getZOptionValue(args, OPT_z, "stack-size", 0);
1499 config->zStartStopGC =
1500 getZFlag(args, "start-stop-gc", "nostart-stop-gc", true);
1501 config->zStartStopVisibility = getZStartStopVisibility(args);
1502 config->zText = getZFlag(args, "text", "notext", true);
1503 config->zWxneeded = hasZOption(args, "wxneeded");
1505 config->power10Stubs = args.getLastArgValue(OPT_power10_stubs_eq) != "no";
1508 if (arg->getOption().matches(OPT_eb))
1509 config->optEB = true;
1511 config->optEL = true;
1515 StringRef value(arg->getValue());
1516 remapInputs(value, arg->getSpelling());
1519 StringRef filename(arg->getValue());
1523 // Parse 'from-glob=to-file' lines, ignoring #-led comments.
1530 constexpr StringRef errPrefix = "--shuffle-sections=: ";
1531 std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
1534 arg->getValue() + "'");
1537 // Signed so that <section_glob>=-1 is allowed.
1542 config->shuffleSections.emplace_back(std::move(*pat), uint32_t(v));
1547 auto reports = {std::make_pair("bti-report", &config->zBtiReport),
1548 std::make_pair("cet-report", &config->zCetReport),
1549 std::make_pair("gcs-report", &config->zGcsReport),
1550 std::make_pair("pauth-report", &config->zPauthReport)};
1553 StringRef(arg->getValue()).split('=');
1557 arg->claim();
1559 error(Twine("-z ") + reportArg.first + "= parameter " + option.second +
1569 StringRef(arg->getValue()).split(fields, '=');
1571 error(arg->getSpelling() +
1572 ": parse error, not 'section-glob=[none|zlib|zstd]'");
1576 auto type = getCompressionType(typeStr, arg->getSpelling());
1580 error(arg->getSpelling() +
1581 ": expected a non-negative integer compression level, but got '" +
1585 config->compressSections.emplace_back(std::move(*pat), type, level);
1587 error(arg->getSpelling() + ": " + toString(pat.takeError()));
1594 StringRef(arg->getValue()).split('=');
1595 if (option.first != "dead-reloc-in-nonalloc")
1597 arg->claim();
1598 constexpr StringRef errPrefix = "-z dead-reloc-in-nonalloc=: ";
1606 error(errPrefix + "expected a non-negative integer, but got '" +
1609 config->deadRelocInNonAlloc.emplace_back(std::move(*pat), v);
1618 parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())),
1619 arg->getSpelling());
1622 parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling());
1624 // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or
1625 // relative path. Just ignore. If not ended with "lto-wrapper" (or
1626 // "lto-wrapper.exe" for GCC cross-compiled for Windows), consider it an
1629 StringRef v(arg->getValue());
1630 if (!v.ends_with("lto-wrapper") && !v.ends_with("lto-wrapper.exe"))
1631 error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() +
1635 config->passPlugins = args::getStrings(args, OPT_load_pass_plugins);
1637 // Parse -mllvm options.
1639 parseClangOption(arg->getValue(), arg->getSpelling());
1640 config->mllvmOpts.emplace_back(arg->getValue());
1643 config->ltoKind = LtoKind::Default;
1645 StringRef s = arg->getValue();
1647 config->ltoKind = LtoKind::UnifiedThin;
1649 config->ltoKind = LtoKind::UnifiedRegular;
1651 config->ltoKind = LtoKind::Default;
1656 // --threads= takes a positive integer and provides the default value for
1657 // --thinlto-jobs=. If unspecified, cap the number of threads since
1659 // non-LTO parts.
1661 StringRef v(arg->getValue());
1664 error(arg->getSpelling() + ": expected a positive integer, but got '" +
1665 arg->getValue() + "'");
1667 config->thinLTOJobs = v;
1669 log("set maximum concurrency to 16, specify --threads= to change");
1673 config->thinLTOJobs = arg->getValue();
1674 config->threadCount = parallel::strategy.compute_thread_count();
1676 if (config->ltoPartitions == 0)
1677 error("--lto-partitions: number of threads must be > 0");
1678 if (!get_threadpool_strategy(config->thinLTOJobs))
1679 error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
1681 if (config->splitStackAdjustSize < 0)
1682 error("--split-stack-adjust-size: size must be >= 0");
1685 // the base address. However, lld places the R PT_LOAD first. -Ttext-segment
1686 // is an old-fashioned option that does not play well with lld's layout.
1687 // Suggest --image-base as a likely alternative.
1689 error("-Ttext-segment is not supported. Use --image-base if you "
1694 StringRef s = arg->getValue();
1695 std::tie(config->ekind, config->emachine, config->osabi) =
1697 config->mipsN32Abi =
1699 config->emulation = s;
1702 // Parse --hash-style={sysv,gnu,both}.
1704 StringRef s = arg->getValue();
1706 config->sysvHash = true;
1708 config->gnuHash = true;
1710 config->sysvHash = config->gnuHash = true;
1712 error("unknown --hash-style: " + s);
1716 config->mapFile = "-";
1718 // Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
1720 // it. Also disable RELRO for -r.
1721 if (config->nmagic || config->omagic || config->relocatable)
1722 config->zRelro = false;
1724 std::tie(config->buildId, config->buildIdVector) = getBuildId(args);
1726 if (getZFlag(args, "pack-relative-relocs", "nopack-relative-relocs", false)) {
1727 config->relrGlibc = true;
1728 config->relrPackDynRelocs = true;
1730 std::tie(config->androidPackDynRelocs, config->relrPackDynRelocs) =
1736 error("--symbol-ordering-file and --call-graph-order-file "
1738 if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue())) {
1739 config->symbolOrderingFile = getSymbolOrderingFile(*buffer);
1742 config->callGraphProfileSort = CGProfileSortKind::None;
1746 assert(config->versionDefinitions.empty());
1747 config->versionDefinitions.push_back(
1749 config->versionDefinitions.push_back(
1752 // If --retain-symbol-file is used, we'll keep only the symbols listed in
1755 config->versionDefinitions[VER_NDX_LOCAL].nonLocalPatterns.push_back(
1757 if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1759 config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(
1764 StringRef pattern(arg->getValue());
1766 config->warnBackrefsExclude.push_back(std::move(*pat));
1768 error(arg->getSpelling() + ": " + toString(pat.takeError()) + ": " +
1772 // For -no-pie and -pie, --export-dynamic-symbol specifies defined symbols
1773 // which should be exported. For -shared, references to matched non-local
1775 // even if other options express a symbolic intention: -Bsymbolic,
1776 // -Bsymbolic-functions (if STT_FUNC), --dynamic-list.
1778 config->dynamicList.push_back(
1779 {arg->getValue(), /*isExternCpp=*/false,
1780 /*hasWildcard=*/hasWildcard(arg->getValue())});
1782 // --export-dynamic-symbol-list specifies a list of --export-dynamic-symbol
1783 // patterns. --dynamic-list is --export-dynamic-symbol-list plus -Bsymbolic
1785 config->symbolic =
1786 config->bsymbolic == BsymbolicKind::All || args.hasArg(OPT_dynamic_list);
1789 if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue()))
1793 if (std::optional<std::string> path = searchScript(arg->getValue())) {
1797 error(Twine("cannot find version script ") + arg->getValue());
1801 // Some Config members do not directly correspond to any particular
1802 // command line options, but computed based on other Config values.
1803 // This function initialize such members. See Config.h for the details
1806 ELFKind k = config->ekind;
1807 uint16_t m = config->emachine;
1809 config->copyRelocs = (config->relocatable || config->emitRelocs);
1810 config->is64 = (k == ELF64LEKind || k == ELF64BEKind);
1811 config->isLE = (k == ELF32LEKind || k == ELF64LEKind);
1812 config->endianness = config->isLE ? endianness::little : endianness::big;
1813 config->isMips64EL = (k == ELF64LEKind && m == EM_MIPS);
1814 config->isPic = config->pie || config->shared;
1815 config->picThunk = args.hasArg(OPT_pic_veneer, config->isPic);
1816 config->wordsize = config->is64 ? 8 : 4;
1832 config->isRela = getIsRela(args);
1836 // if --apply-dynamic-relocs is used.
1839 config->writeAddends = args.hasFlag(OPT_apply_dynamic_relocs,
1841 !config->isRela;
1850 config->checkDynamicRelocs =
1853 config->tocOptimize =
1855 config->pcRelOptimize =
1859 if (config->emachine == EM_MIPS)
1860 config->sysvHash = true;
1862 config->sysvHash = config->gnuHash = true;
1867 config->warnMissingEntry =
1868 (!config->entry.empty() || (!config->shared && !config->relocatable));
1869 if (config->entry.empty() && !config->relocatable)
1870 config->entry = config->emachine == EM_MIPS ? "__start" : "_start";
1871 if (config->outputFile.empty())
1872 config->outputFile = "a.out";
1876 // find that it failed because there was a mistake in their command-line.
1879 if (auto e = tryCreateFile(config->outputFile))
1880 error("cannot open output file " + config->outputFile + ": " +
1882 if (auto e = tryCreateFile(config->mapFile))
1883 error("cannot open map file " + config->mapFile + ": " + e.message());
1884 if (auto e = tryCreateFile(config->whyExtract))
1885 error("cannot open --why-extract= file " + config->whyExtract + ": " +
1895 error("unknown --format value: " + s +
1902 // For --{push,pop}-state.
1905 // -r implies -Bstatic and has precedence over -Bdynamic.
1906 config->isStatic = config->relocatable;
1913 switch (arg->getOption().getID()) {
1915 addLibrary(arg->getValue());
1919 addFile(arg->getValue(), /*withLOption=*/false);
1925 std::tie(from, to) = StringRef(arg->getValue()).split('=');
1927 error("--defsym: syntax error: " + StringRef(arg->getValue()));
1929 readDefsym(from, MemoryBufferRef(to, "--defsym"));
1934 if (std::optional<std::string> path = searchScript(arg->getValue())) {
1936 if (arg->getOption().matches(OPT_default_script)) {
1945 error(Twine("cannot find linker script ") + arg->getValue());
1948 config->asNeeded = true;
1951 config->formatBinary = isFormatBinary(arg->getValue());
1954 config->asNeeded = false;
1959 config->isStatic = true;
1962 if (!config->relocatable)
1963 config->isStatic = false;
1972 if (std::optional<MemoryBufferRef> mb = readFile(arg->getValue())) {
1974 files.back()->justSymbols = true;
1980 else if (std::optional<MemoryBufferRef> mb = readFile(arg->getValue()))
1985 error("nested --start-group");
1990 error("stray --end-group");
1996 error("nested --start-lib");
1998 error("may not nest --start-lib in --start-group");
2004 error("stray --end-lib");
2010 stack.emplace_back(config->asNeeded, config->isStatic, inWholeArchive);
2014 error("unbalanced --push-state/--pop-state");
2017 std::tie(config->asNeeded, config->isStatic, inWholeArchive) = stack.back();
2029 // If -m <machine_type> was not given, infer it from object files.
2031 if (config->ekind != ELFNoneKind)
2036 if (f->ekind == ELFNoneKind)
2040 config->ekind = f->ekind;
2041 config->emachine = f->emachine;
2042 config->mipsN32Abi = config->emachine == EM_MIPS && isMipsN32Abi(f);
2044 config->osabi = f->osabi;
2045 if (f->osabi != ELFOSABI_NONE)
2049 error("target emulation unknown: -m or at least one .o file required");
2052 // Parse -z max-page-size=<value>. The default value is defined by
2055 uint64_t val = args::getZOptionValue(args, OPT_z, "max-page-size",
2056 target->defaultMaxPageSize);
2058 error("max-page-size: value isn't a power of 2");
2059 return target->defaultMaxPageSize;
2061 if (config->nmagic || config->omagic) {
2062 if (val != target->defaultMaxPageSize)
2063 warn("-z max-page-size set, but paging disabled by omagic or nmagic");
2069 // Parse -z common-page-size=<value>. The default value is defined by
2072 uint64_t val = args::getZOptionValue(args, OPT_z, "common-page-size",
2073 target->defaultCommonPageSize);
2075 error("common-page-size: value isn't a power of 2");
2076 return target->defaultCommonPageSize;
2078 if (config->nmagic || config->omagic) {
2079 if (val != target->defaultCommonPageSize)
2080 warn("-z common-page-size set, but paging disabled by omagic or nmagic");
2084 if (val > config->maxPageSize)
2085 val = config->maxPageSize;
2089 // Parses --image-base option.
2091 // Because we are using "Config->maxPageSize" here, this function has to be
2097 StringRef s = arg->getValue();
2100 error("--image-base: number expected, but got " + s);
2103 if ((v % config->maxPageSize) != 0)
2104 warn("--image-base: address isn't multiple of page size: " + s);
2108 // Parses `--exclude-libs=lib,lib,...`.
2113 StringRef s = arg->getValue();
2126 // Handles the --exclude-libs option. If a static library file is specified
2127 // by the --exclude-libs option, all public symbols from the archive become
2137 if (file->archiveName.empty() ||
2138 !(all || libs.count(path::filename(file->archiveName))))
2140 ArrayRef<Symbol *> symbols = file->getSymbols();
2142 symbols = cast<ELFFileBase>(file)->getGlobalSymbols();
2144 if (!sym->isUndefined() && sym->file == file)
2145 sym->versionId = VER_NDX_LOCAL;
2159 sym->isUsedInRegularObj = true;
2161 if (!sym->isLazy())
2163 sym->extract();
2164 if (!config->whyExtract.empty())
2165 ctx.whyExtractRecords.emplace_back(option, sym->file, *sym);
2168 // As an extension to GNU linkers, lld supports a variant of `-u`
2170 // pattern are handled as if they were given by `-u`.
2174 error("--undefined-glob: " + toString(pat.takeError()) + ": " + arg);
2178 // Calling sym->extract() in the loop is not safe because it may add new
2182 if (!sym->isPlaceholder() && pat->match(sym->getName()))
2186 handleUndefined(sym, "--undefined-glob");
2191 if (sym && sym->isLazy() && isa<BitcodeFile>(sym->file)) {
2192 if (!config->whyExtract.empty())
2193 ctx.whyExtractRecords.emplace_back("<libcall>", sym->file, *sym);
2194 sym->extract();
2199 if (config->printArchiveStats.empty())
2203 raw_fd_ostream os = ctx.openAuxiliaryFile(config->printArchiveStats, ec);
2205 error("--print-archive-stats=: cannot open " + config->printArchiveStats +
2215 if (file->archiveName.size())
2216 ++extracted[CachedHashStringRef(file->archiveName)];
2218 if (file->archiveName.size())
2219 ++extracted[CachedHashStringRef(file->archiveName)];
2229 if (config->whyExtract.empty())
2233 raw_fd_ostream os = ctx.openAuxiliaryFile(config->whyExtract, ec);
2235 error("cannot open --why-extract= file " + config->whyExtract + ": " +
2252 // with --warn-backrefs-exclude=. The value may look like (for --start-lib)
2255 for (const llvm::GlobPattern &pat : config->warnBackrefsExclude)
2266 // Handle --dependency-file=<path>. If that option is given, lld creates a
2269 // <output-file>: <input-file> ...
2271 // <input-file>:
2273 // where <output-file> is a pathname of an output file and <input-file>
2276 // phony targets for every <input-file> to avoid an error when that file is
2283 // executable depends on all user-generated object files. Normally, you
2287 // part of your program. By using --dependency-file option, you can make
2292 raw_fd_ostream os = ctx.openAuxiliaryFile(config->dependencyFile, ec);
2294 error("cannot open " + config->dependencyFile + ": " + ec.message());
2312 while (j > 0 && nativePath[--j] == '\\')
2321 os << config->outputFile << ":";
2322 for (StringRef path : config->dependencyFiles) {
2328 for (StringRef path : config->dependencyFiles) {
2342 if (!file->hasCommonSyms)
2344 for (Symbol *sym : file->getGlobalSymbols()) {
2349 auto *bss = make<BssSection>("COMMON", s->size, s->alignment);
2350 bss->file = s->file;
2352 Defined(s->file, StringRef(), s->binding, s->stOther, s->type,
2353 /*value=*/0, s->size, bss)
2359 // The section referred to by `s` is considered address-significant. Set the
2363 if (d->section)
2364 // We don't need to keep text sections unique under --icf=all even if they
2365 // are address-significant.
2366 if (config->icf == ICFLevel::Safe || !(d->section->flags & SHF_EXECINSTR))
2367 d->section->keepUnique = true;
2370 // Record sections that define symbols mentioned in --keep-unique <symbol>
2371 // and symbols referred to by address-significance tables. These sections are
2376 StringRef name = arg->getValue();
2378 if (!d || !d->section) {
2382 d->section->keepUnique = true;
2385 // --icf=all --ignore-data-address-equality means that we can ignore
2386 // the dynsym and address-significance tables entirely.
2387 if (config->icf == ICFLevel::All && config->ignoreDataAddressEquality)
2390 // Symbols in the dynsym could be address-significant in other executables
2391 // or DSOs, so we conservatively mark them as address-significant.
2393 if (sym->includeInDynsym())
2396 // Visit the address-significance table in each object file and mark each
2397 // referenced symbol as address-significant.
2400 ArrayRef<Symbol *> syms = obj->getSymbols();
2401 if (obj->addrsigSec) {
2403 check(obj->getObj().getSectionContents(*obj->addrsigSec));
2415 // If an object file does not have an address-significance table,
2416 // conservatively mark all of its symbols as address-significant.
2430 const RelsOrRelas<ELFT> rels = s->template relsOrRelas<ELFT>();
2432 sym = &s->file->getRelocTargetSym(rels.rels[0]);
2434 sym = &s->file->getRelocTargetSym(rels.relas[0]);
2435 if (!isa<Defined>(sym) || !sym->includeInDynsym())
2438 StringRef partName = reinterpret_cast<const char *>(s->content().data());
2441 sym->partition = part.getNumber();
2449 if (script->hasSectionsCommand)
2450 error(toString(s->file) +
2452 if (script->hasPhdrsCommands())
2453 error(toString(s->file) +
2455 if (!config->sectionStartMap.empty())
2456 error(toString(s->file) + ": partitions cannot be used with "
2457 "--section-start, -Ttext, -Tdata or -Tbss");
2458 if (config->emachine == EM_MIPS)
2459 error(toString(s->file) + ": partitions cannot be used on this target");
2470 sym->partition = newPart.getNumber();
2474 // With --thinlto-index-only, all buffers are nearly unused from now on
2487 bufs.insert(file->mb.getBufferStart());
2489 bufs.insert(file->mb.getBufferStart());
2495 // This function is where all the optimizations of link-time
2501 // the compiler at once, it can do a whole-program optimization.
2508 lto->add(*file);
2513 for (InputFile *file : lto->compile()) {
2515 obj->parse(/*ignoreComdats=*/true);
2517 // Parse '@' in symbol names for non-relocatable output.
2518 if (!config->relocatable)
2519 for (Symbol *sym : obj->getGlobalSymbols())
2520 if (sym->hasVersionSuffix)
2521 sym->parseSymbolVersion();
2526 // The --wrap option is a feature to rename symbols so that you can write
2527 // wrappers for existing functions. If you pass `--wrap=foo`, all
2533 // This data structure is instantiated for each --wrap option.
2540 // Handles --wrap option.
2550 StringRef name = arg->getValue();
2559 symtab.addUnusedUndefined(saver().save("__wrap_" + name), sym->binding);
2565 symtab.addUnusedUndefined(name, sym->binding);
2568 sym->binding = real->binding;
2576 real->scriptDefined = true;
2577 sym->scriptDefined = true;
2588 if (real->referenced || real->isDefined())
2589 sym->referencedAfterWrap = true;
2590 if (sym->referenced || sym->isDefined())
2591 wrap->referencedAfterWrap = true;
2609 const char *suffix2 = sym2->getVersionSuffix();
2614 // If both foo@v1 and foo@@v1 are defined and non-weak, report a
2617 sym2->checkDuplicate(cast<Defined>(sym));
2618 sym2->resolve(cast<Defined>(sym));
2620 sym2->resolve(cast<Undefined>(sym));
2622 sym2->resolve(cast<SharedSymbol>(sym));
2628 if (sym2->versionId > VER_NDX_GLOBAL
2629 ? config->versionDefinitions[sym2->versionId].name == suffix1 + 1
2630 : sym1->section == sym2->section && sym1->value == sym2->value) {
2638 sym2->symbolKind = Symbol::PlaceholderKind;
2639 sym2->isUsedInRegularObj = false;
2644 // Do renaming for --wrap and foo@v1 by updating pointers to symbols.
2658 // symbols with a non-default version (foo@v1) and check whether it should be
2660 if (config->versionDefinitions.size() > 2)
2662 if (sym->hasVersionSuffix)
2670 for (Symbol *&sym : file->getMutableGlobalSymbols())
2680 static void reportMissingFeature(StringRef config, const Twine &report) {
2681 if (config == "error")
2683 else if (config == "warning")
2687 static void checkAndReportMissingFeature(StringRef config, uint32_t features,
2690 reportMissingFeature(config, report);
2693 // To enable CET (x86's hardware-assisted control flow enforcement), each
2694 // source file must be compiled with -fcf-protection. Object files compiled
2702 // For AArch64 PAuth-enabled object files, the core info of all of them must
2704 // ones can be allowed (see -z pauth-report).
2706 if (config->emachine != EM_386 && config->emachine != EM_X86_64 &&
2707 config->emachine != EM_AARCH64)
2710 config->andFeatures = -1;
2713 if (config->emachine == EM_AARCH64) {
2715 return !f->aarch64PauthAbiCoreInfo.empty();
2718 ctx.aarch64PauthAbiCoreInfo = (*it)->aarch64PauthAbiCoreInfo;
2719 referenceFileName = (*it)->getName();
2724 uint32_t features = f->andFeatures;
2727 config->zBtiReport, features, GNU_PROPERTY_AARCH64_FEATURE_1_BTI,
2728 toString(f) + ": -z bti-report: file does not have "
2732 config->zGcsReport, features, GNU_PROPERTY_AARCH64_FEATURE_1_GCS,
2733 toString(f) + ": -z gcs-report: file does not have "
2737 config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_IBT,
2738 toString(f) + ": -z cet-report: file does not have "
2742 config->zCetReport, features, GNU_PROPERTY_X86_FEATURE_1_SHSTK,
2743 toString(f) + ": -z cet-report: file does not have "
2746 if (config->zForceBti && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_BTI)) {
2748 if (config->zBtiReport == "none")
2749 warn(toString(f) + ": -z force-bti: file does not have "
2751 } else if (config->zForceIbt &&
2753 if (config->zCetReport == "none")
2754 warn(toString(f) + ": -z force-ibt: file does not have "
2758 if (config->zPacPlt && !(features & GNU_PROPERTY_AARCH64_FEATURE_1_PAC)) {
2759 warn(toString(f) + ": -z pac-plt: file does not have "
2763 config->andFeatures &= features;
2768 if (f->aarch64PauthAbiCoreInfo.empty()) {
2769 reportMissingFeature(config->zPauthReport,
2771 ": -z pauth-report: file does not have AArch64 "
2777 if (ctx.aarch64PauthAbiCoreInfo != f->aarch64PauthAbiCoreInfo)
2782 toHex(f->aarch64PauthAbiCoreInfo, /*LowerCase=*/true));
2786 if (config->zShstk)
2787 config->andFeatures |= GNU_PROPERTY_X86_FEATURE_1_SHSTK;
2790 if (config->zGcs == GcsPolicy::Always)
2791 config->andFeatures |= GNU_PROPERTY_AARCH64_FEATURE_1_GCS;
2792 else if (config->zGcs == GcsPolicy::Never)
2793 config->andFeatures &= ~GNU_PROPERTY_AARCH64_FEATURE_1_GCS;
2797 switch (file->ekind) {
2799 cast<ObjFile<ELF32LE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
2802 cast<ObjFile<ELF32BE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
2805 cast<ObjFile<ELF64LE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
2808 cast<ObjFile<ELF64BE>>(file)->initSectionsAndLocalSyms(ignoreComdats);
2816 switch (file->ekind) {
2818 cast<ObjFile<ELF32LE>>(file)->postParse();
2821 cast<ObjFile<ELF32BE>>(file)->postParse();
2824 cast<ObjFile<ELF64LE>>(file)->postParse();
2827 cast<ObjFile<ELF64BE>>(file)->postParse();
2839 // Handle --trace-symbol.
2841 symtab.insert(arg->getValue())->traced = true;
2845 // Handle -u/--undefined before input files. If both a.a and b.so define foo,
2846 // -u foo a.a b.so will extract a.a.
2847 for (StringRef name : config->undefined)
2848 symtab.addUnusedUndefined(name)->referenced = true;
2853 config->hasDynSymTab = !ctx.sharedFiles.empty() || config->isPic;
2856 if (Symbol *sym = symtab.find(config->entry))
2857 handleUndefined(sym, "--entry");
2859 // Handle the `--undefined-glob <pattern>` options.
2864 // -u/--undefined-glob, check whether PROVIDE symbols should be defined (the
2866 script->addScriptReferencedSymbolsToSymTable();
2868 // Prevent LTO from removing any definition referenced by -u.
2869 for (StringRef name : config->undefined)
2871 sym->isUsedInRegularObj = true;
2873 // Mark -init and -fini symbols so that the LTO doesn't eliminate them.
2874 if (Symbol *sym = dyn_cast_or_null<Defined>(symtab.find(config->init)))
2875 sym->isUsedInRegularObj = true;
2876 if (Symbol *sym = dyn_cast_or_null<Defined>(symtab.find(config->fini)))
2877 sym->isUsedInRegularObj = true;
2887 // __sync_val_compare_and_swap_8 on 32-bit ARM pulls in an .init_array entry
2888 // that aborts the program if the Linux kernel does not support 64-bit
2890 // use 64-bit atomics.
2897 llvm::Triple TT(ctx.bitcodeFiles.front()->obj->getTargetTriple());
2912 [](BitcodeFile *file) { file->postParse(); });
2932 script->declareSymbols();
2934 // Handle --exclude-libs. This is before scanVersionScript() due to a
2937 // 'has undefined version' error in -shared --exclude-libs=ALL mode (PR36295).
2947 if (!config->relocatable)
2954 // name "foo@ver1") rather do harm, so we don't call this if -r is given.
2955 if (!config->relocatable) {
2962 // For --thinlto-index-only, index file creation is performed in
2963 // compileBitcodeFiles, so we are done afterwards. --plugin-opt=emit-llvm and
2964 // --plugin-opt=emit-asm create output files in bitcode or assembly code,
2967 const bool skipLinkedOutput = config->thinLTOIndexOnly || config->emitLLVM ||
2968 config->ltoEmitAsm ||
2969 !config->thinLTOModulesToCompile.empty();
2971 // Handle --lto-validate-all-vtables-have-type-infos.
2972 if (config->ltoValidateAllVtablesHaveTypeInfos)
2975 // Do link-time optimization if given files are LLVM bitcode files.
2979 // except a few linker-synthesized ones will be added to the symbol table.
2985 // --print-archive-stats=, and --why-extract=.
3014 oldFilenames.insert(f->getName());
3016 if (!oldFilenames.contains(newFile->getName()))
3017 errorOrWarn("input file '" + newFile->getName() + "' added after LTO");
3020 // Handle --exclude-libs again because lto.tmp may reference additional
3029 // Apply symbol renames for --wrap and combine foo@v1 and foo@@v1.
3041 for (InputSectionBase *s : f->getSections()) {
3051 for (InputSectionBase *s : f->getSections())
3059 if (s->type != SHT_LLVM_SYMPART)
3065 // We do not want to emit debug sections if --strip-all
3066 // or --strip-debug are given.
3067 if (config->strip != StripPolicy::None) {
3072 if (InputSectionBase *rel = isec->getRelocatedSection())
3083 if (!config->dependencyFile.empty())
3094 // The Target instance handles target-specific stuff, such as applying
3095 // relocations or writing a PLT section. It also contains target-dependent
3099 config->eflags = target->calcEFlags();
3104 config->maxPageSize = getMaxPageSize(args);
3110 config->commonPageSize = getCommonPageSize(args);
3112 config->imageBase = getImageBase(args);
3115 if (!config->relocatable)
3140 if (!config->relocatable)
3144 if (config->emachine == EM_RISCV)
3151 script->processSectionCommands();
3157 script->addOrphanSections();
3167 for (SectionCommand *cmd : script->sectionCommands)
3169 osd->osec.finalizeInputSections(&script.s);
3174 if (config->icf != ICFLevel::None) {
3180 if (config->callGraphProfileSort != CGProfileSortKind::None) {
3182 if (std::optional<MemoryBufferRef> buffer = readFile(arg->getValue()))