1//===--- Linux.h - Linux ToolChain Implementations --------------*- C++ -*-===//
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 "Linux.h"
10#include "Arch/ARM.h"
11#include "Arch/LoongArch.h"
12#include "Arch/Mips.h"
13#include "Arch/PPC.h"
14#include "Arch/RISCV.h"
15#include "clang/Config/config.h"
16#include "clang/Driver/CommonArgs.h"
17#include "clang/Driver/Distro.h"
18#include "clang/Driver/Driver.h"
19#include "clang/Driver/SanitizerArgs.h"
20#include "clang/Options/Options.h"
21#include "llvm/Option/ArgList.h"
22#include "llvm/ProfileData/InstrProf.h"
23#include "llvm/Support/Path.h"
24#include "llvm/Support/ScopedPrinter.h"
25#include "llvm/Support/VirtualFileSystem.h"
26
27using namespace clang::driver;
28using namespace clang::driver::toolchains;
29using namespace clang;
30using namespace llvm::opt;
31
32using tools::addPathIfExists;
33
34/// Get our best guess at the multiarch triple for a target.
35///
36/// Debian-based systems are starting to use a multiarch setup where they use
37/// a target-triple directory in the library and header search paths.
38/// Unfortunately, this triple does not align with the vanilla target triple,
39/// so we provide a rough mapping here.
40std::string Linux::getMultiarchTriple(const Driver &D,
41 const llvm::Triple &TargetTriple,
42 StringRef SysRoot) const {
43 llvm::Triple::EnvironmentType TargetEnvironment =
44 TargetTriple.getEnvironment();
45 bool IsAndroid = TargetTriple.isAndroid();
46 bool IsMipsR6 = TargetTriple.getSubArch() == llvm::Triple::MipsSubArch_r6;
47 bool IsMipsN32Abi = TargetTriple.getEnvironment() == llvm::Triple::GNUABIN32;
48
49 // For most architectures, just use whatever we have rather than trying to be
50 // clever.
51 switch (TargetTriple.getArch()) {
52 default:
53 break;
54
55 // We use the existence of '/lib/<triple>' as a directory to detect some
56 // common linux triples that don't quite match the Clang triple for both
57 // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
58 // regardless of what the actual target triple is.
59 case llvm::Triple::arm:
60 case llvm::Triple::thumb:
61 if (IsAndroid)
62 return "arm-linux-androideabi";
63 if (TargetEnvironment == llvm::Triple::GNUEABIHF ||
64 TargetEnvironment == llvm::Triple::MuslEABIHF ||
65 TargetEnvironment == llvm::Triple::EABIHF)
66 return "arm-linux-gnueabihf";
67 return "arm-linux-gnueabi";
68 case llvm::Triple::armeb:
69 case llvm::Triple::thumbeb:
70 if (TargetEnvironment == llvm::Triple::GNUEABIHF ||
71 TargetEnvironment == llvm::Triple::MuslEABIHF ||
72 TargetEnvironment == llvm::Triple::EABIHF)
73 return "armeb-linux-gnueabihf";
74 return "armeb-linux-gnueabi";
75 case llvm::Triple::x86:
76 if (IsAndroid)
77 return "i686-linux-android";
78 return "i386-linux-gnu";
79 case llvm::Triple::x86_64:
80 if (IsAndroid)
81 return "x86_64-linux-android";
82 if (TargetEnvironment == llvm::Triple::GNUX32)
83 return "x86_64-linux-gnux32";
84 return "x86_64-linux-gnu";
85 case llvm::Triple::aarch64:
86 if (IsAndroid)
87 return "aarch64-linux-android";
88 if (hasEffectiveTriple() &&
89 getEffectiveTriple().getEnvironment() == llvm::Triple::PAuthTest)
90 return "aarch64-linux-pauthtest";
91 return "aarch64-linux-gnu";
92 case llvm::Triple::aarch64_be:
93 return "aarch64_be-linux-gnu";
94
95 case llvm::Triple::loongarch64: {
96 const char *Libc;
97 const char *FPFlavor;
98
99 if (TargetTriple.isGNUEnvironment()) {
100 Libc = "gnu";
101 } else if (TargetTriple.isMusl()) {
102 Libc = "musl";
103 } else {
104 return TargetTriple.str();
105 }
106
107 switch (TargetEnvironment) {
108 default:
109 return TargetTriple.str();
110 case llvm::Triple::GNUSF:
111 case llvm::Triple::MuslSF:
112 FPFlavor = "sf";
113 break;
114 case llvm::Triple::GNUF32:
115 case llvm::Triple::MuslF32:
116 FPFlavor = "f32";
117 break;
118 case llvm::Triple::GNU:
119 case llvm::Triple::GNUF64:
120 case llvm::Triple::Musl:
121 // This was going to be "f64" in an earlier Toolchain Conventions
122 // revision, but starting from Feb 2023 the F64 ABI variants are
123 // unmarked in their canonical forms.
124 FPFlavor = "";
125 break;
126 }
127
128 return (Twine("loongarch64-linux-") + Libc + FPFlavor).str();
129 }
130
131 case llvm::Triple::m68k:
132 return "m68k-linux-gnu";
133
134 case llvm::Triple::mips:
135 return IsMipsR6 ? "mipsisa32r6-linux-gnu" : "mips-linux-gnu";
136 case llvm::Triple::mipsel:
137 return IsMipsR6 ? "mipsisa32r6el-linux-gnu" : "mipsel-linux-gnu";
138 case llvm::Triple::mips64: {
139 std::string MT = std::string(IsMipsR6 ? "mipsisa64r6" : "mips64") +
140 "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
141 if (D.getVFS().exists(Path: concat(Path: SysRoot, A: "/lib", B: MT)))
142 return MT;
143 if (D.getVFS().exists(Path: concat(Path: SysRoot, A: "/lib/mips64-linux-gnu")))
144 return "mips64-linux-gnu";
145 break;
146 }
147 case llvm::Triple::mips64el: {
148 std::string MT = std::string(IsMipsR6 ? "mipsisa64r6el" : "mips64el") +
149 "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
150 if (D.getVFS().exists(Path: concat(Path: SysRoot, A: "/lib", B: MT)))
151 return MT;
152 if (D.getVFS().exists(Path: concat(Path: SysRoot, A: "/lib/mips64el-linux-gnu")))
153 return "mips64el-linux-gnu";
154 break;
155 }
156 case llvm::Triple::ppc:
157 if (D.getVFS().exists(Path: concat(Path: SysRoot, A: "/lib/powerpc-linux-gnuspe")))
158 return "powerpc-linux-gnuspe";
159 return "powerpc-linux-gnu";
160 case llvm::Triple::ppcle:
161 return "powerpcle-linux-gnu";
162 case llvm::Triple::ppc64:
163 return "powerpc64-linux-gnu";
164 case llvm::Triple::ppc64le:
165 return "powerpc64le-linux-gnu";
166 case llvm::Triple::riscv64:
167 if (IsAndroid)
168 return "riscv64-linux-android";
169 return "riscv64-linux-gnu";
170 case llvm::Triple::sparc:
171 return "sparc-linux-gnu";
172 case llvm::Triple::sparcv9:
173 return "sparc64-linux-gnu";
174 case llvm::Triple::systemz:
175 return "s390x-linux-gnu";
176 }
177 return TargetTriple.str();
178}
179
180static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
181 if (Triple.isMIPS()) {
182 // lib32 directory has a special meaning on MIPS targets.
183 // It contains N32 ABI binaries. Use this folder if produce
184 // code for N32 ABI only.
185 if (tools::mips::hasMipsAbiArg(Args, Value: "n32"))
186 return "lib32";
187 return Triple.isArch32Bit() ? "lib" : "lib64";
188 }
189
190 // It happens that only x86, PPC and SPARC use the 'lib32' variant of
191 // oslibdir, and using that variant while targeting other architectures causes
192 // problems because the libraries are laid out in shared system roots that
193 // can't cope with a 'lib32' library search path being considered. So we only
194 // enable them when we know we may need it.
195 //
196 // FIXME: This is a bit of a hack. We should really unify this code for
197 // reasoning about oslibdir spellings with the lib dir spellings in the
198 // GCCInstallationDetector, but that is a more significant refactoring.
199 if (Triple.getArch() == llvm::Triple::x86 || Triple.isPPC32() ||
200 Triple.getArch() == llvm::Triple::sparc)
201 return "lib32";
202
203 if (Triple.getArch() == llvm::Triple::x86_64 && Triple.isX32())
204 return "libx32";
205
206 if (Triple.isRISCV32())
207 return "lib32";
208
209 if (Triple.getArch() == llvm::Triple::loongarch32) {
210 switch (Triple.getEnvironment()) {
211 default:
212 return "lib32";
213 case llvm::Triple::GNUSF:
214 case llvm::Triple::MuslSF:
215 return "lib32/sf";
216 case llvm::Triple::GNUF32:
217 case llvm::Triple::MuslF32:
218 return "lib32/f32";
219 }
220 }
221
222 return Triple.isArch32Bit() ? "lib" : "lib64";
223}
224
225Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
226 : Generic_ELF(D, Triple, Args) {
227 GCCInstallation.TripleToDebianMultiarch = [](const llvm::Triple &T) {
228 StringRef TripleStr = T.str();
229 StringRef DebianMultiarch =
230 T.getArch() == llvm::Triple::x86 ? "i386-linux-gnu" : TripleStr;
231 return DebianMultiarch;
232 };
233
234 GCCInstallation.init(TargetTriple: Triple, Args);
235 Multilibs = GCCInstallation.getMultilibs();
236 SelectedMultilibs.assign(IL: {GCCInstallation.getMultilib()});
237
238 loadMultilibsFromYAML(Args, D);
239
240 llvm::Triple::ArchType Arch = Triple.getArch();
241 std::string SysRoot = computeSysRoot();
242 ToolChain::path_list &PPaths = getProgramPaths();
243
244 Generic_GCC::PushPPaths(PPaths);
245
246 Distro Distro(D.getVFS(), Triple);
247
248 if (Distro.IsAlpineLinux() || Triple.isAndroid()) {
249 ExtraOpts.push_back(x: "-z");
250 ExtraOpts.push_back(x: "now");
251 }
252
253 if (Distro.IsOpenSUSE() || Distro.IsUbuntu() || Distro.IsAlpineLinux() ||
254 Triple.isAndroid()) {
255 ExtraOpts.push_back(x: "-z");
256 ExtraOpts.push_back(x: "relro");
257 }
258
259 // Note, lld from 11 onwards default max-page-size to 65536 for both ARM and
260 // AArch64.
261 if (Triple.isAndroid()) {
262 if (Triple.isARM()) {
263 // Android ARM uses max-page-size=4096 to reduce VMA usage.
264 ExtraOpts.push_back(x: "-z");
265 ExtraOpts.push_back(x: "max-page-size=4096");
266 } else if (Triple.isAArch64() || Triple.getArch() == llvm::Triple::x86_64) {
267 // Android AArch64 uses max-page-size=16384 to support 4k/16k page sizes.
268 // Android emulates a 16k page size for app testing on x86_64 machines.
269 ExtraOpts.push_back(x: "-z");
270 ExtraOpts.push_back(x: "max-page-size=16384");
271 }
272 if (Triple.isAndroidVersionLT(Major: 29)) {
273 // https://github.com/android/ndk/issues/1196
274 // The unwinder used by the crash handler on versions of Android prior to
275 // API 29 did not correctly handle binaries built with rosegment, which is
276 // enabled by default for LLD. Android only supports LLD, so it's not an
277 // issue that this flag is not accepted by other linkers.
278 ExtraOpts.push_back(x: "--no-rosegment");
279 }
280 // SHT_RELR relocations are only supported at API level >= 30.
281 // ANDROID_RELR relocations were supported at API level >= 28.
282 if (!Triple.isAndroidVersionLT(Major: 30)) {
283 ExtraOpts.push_back(x: "--pack-dyn-relocs=android+relr");
284 } else if (!Triple.isAndroidVersionLT(Major: 28)) {
285 ExtraOpts.push_back(x: "--pack-dyn-relocs=android+relr");
286 ExtraOpts.push_back(x: "--use-android-relr-tags");
287 } else {
288 ExtraOpts.push_back(x: "--pack-dyn-relocs=android");
289 }
290 }
291
292 if (GCCInstallation.getParentLibPath().contains(Other: "opt/rh/"))
293 // With devtoolset on RHEL, we want to add a bin directory that is relative
294 // to the detected gcc install, because if we are using devtoolset gcc then
295 // we want to use other tools from devtoolset (e.g. ld) instead of the
296 // standard system tools.
297 PPaths.push_back(Elt: Twine(GCCInstallation.getParentLibPath() +
298 "/../bin").str());
299
300 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
301 ExtraOpts.push_back(x: "-X");
302
303 const bool IsAndroid = Triple.isAndroid();
304 const bool IsMips = Triple.isMIPS();
305 const bool IsHexagon = Arch == llvm::Triple::hexagon;
306 const bool IsRISCV = Triple.isRISCV();
307 const bool IsCSKY = Triple.isCSKY();
308
309 if (IsCSKY && !SelectedMultilibs.empty())
310 SysRoot = SysRoot + SelectedMultilibs.back().osSuffix();
311
312 if ((IsMips || IsCSKY) && !SysRoot.empty())
313 ExtraOpts.push_back(x: "--sysroot=" + SysRoot);
314
315 // Do not use 'gnu' hash style for Mips targets because .gnu.hash
316 // and the MIPS ABI require .dynsym to be sorted in different ways.
317 // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
318 // ABI requires a mapping between the GOT and the symbol table.
319 // Hexagon linker/loader does not support .gnu.hash.
320 if (!IsMips && !IsHexagon)
321 ExtraOpts.push_back(x: "--hash-style=gnu");
322
323#ifdef ENABLE_LINKER_BUILD_ID
324 ExtraOpts.push_back("--build-id");
325#endif
326
327 // The selection of paths to try here is designed to match the patterns which
328 // the GCC driver itself uses, as this is part of the GCC-compatible driver.
329 // This was determined by running GCC in a fake filesystem, creating all
330 // possible permutations of these directories, and seeing which ones it added
331 // to the link paths.
332 path_list &Paths = getFilePaths();
333
334 const std::string OSLibDir = std::string(getOSLibDir(Triple, Args));
335 const std::string MultiarchTriple = getMultiarchTriple(D, TargetTriple: Triple, SysRoot);
336
337 // mips32: Debian multilib, we use /libo32, while in other case, /lib is
338 // used. We need add both libo32 and /lib.
339 if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel) {
340 Generic_GCC::AddMultilibPaths(D, SysRoot, OSLibDir: "libo32", MultiarchTriple, Paths);
341 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/libo32"), Paths);
342 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/usr/libo32"), Paths);
343 }
344 Generic_GCC::AddMultilibPaths(D, SysRoot, OSLibDir, MultiarchTriple, Paths);
345
346 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/lib", B: MultiarchTriple), Paths);
347 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/lib/..", B: OSLibDir), Paths);
348
349 if (IsAndroid) {
350 // Android sysroots contain a library directory for each supported OS
351 // version as well as some unversioned libraries in the usual multiarch
352 // directory.
353 addPathIfExists(
354 D,
355 Path: concat(Path: SysRoot, A: "/usr/lib", B: MultiarchTriple,
356 C: llvm::to_string(Value: Triple.getEnvironmentVersion().getMajor())),
357 Paths);
358 }
359
360 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/usr/lib", B: MultiarchTriple), Paths);
361 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/usr", B: OSLibDir), Paths);
362 if (IsRISCV) {
363 StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
364 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/", B: OSLibDir, C: ABIName), Paths);
365 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/usr", B: OSLibDir, C: ABIName), Paths);
366 }
367
368 Generic_GCC::AddMultiarchPaths(D, SysRoot, OSLibDir, Paths);
369
370 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/lib"), Paths);
371 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/usr/lib"), Paths);
372}
373
374ToolChain::RuntimeLibType Linux::GetDefaultRuntimeLibType() const {
375 if (getTriple().isAndroid())
376 return ToolChain::RLT_CompilerRT;
377 return Generic_ELF::GetDefaultRuntimeLibType();
378}
379
380unsigned Linux::GetDefaultDwarfVersion() const {
381 if (getTriple().isAndroid())
382 return 4;
383 return ToolChain::GetDefaultDwarfVersion();
384}
385
386ToolChain::CXXStdlibType Linux::GetDefaultCXXStdlibType() const {
387 if (getTriple().isAndroid())
388 return ToolChain::CST_Libcxx;
389 return ToolChain::CST_Libstdcxx;
390}
391
392bool Linux::HasNativeLLVMSupport() const { return true; }
393
394Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
395
396Tool *Linux::buildStaticLibTool() const {
397 return new tools::gnutools::StaticLibTool(*this);
398}
399
400Tool *Linux::buildAssembler() const {
401 return new tools::gnutools::Assembler(*this);
402}
403
404std::string Linux::computeSysRoot() const {
405 if (!getDriver().SysRoot.empty())
406 return getDriver().SysRoot;
407
408 if (getTriple().isAndroid()) {
409 // Android toolchains typically include a sysroot at ../sysroot relative to
410 // the clang binary.
411 const StringRef ClangDir = getDriver().Dir;
412 std::string AndroidSysRootPath = (ClangDir + "/../sysroot").str();
413 if (getVFS().exists(Path: AndroidSysRootPath))
414 return AndroidSysRootPath;
415 }
416
417 if (getTriple().isCSKY()) {
418 // CSKY toolchains use different names for sysroot folder.
419 if (!GCCInstallation.isValid())
420 return std::string();
421 // GCCInstallation.getInstallPath() =
422 // $GCCToolchainPath/lib/gcc/csky-linux-gnuabiv2/6.3.0
423 // Path = $GCCToolchainPath/csky-linux-gnuabiv2/libc
424 std::string Path = (GCCInstallation.getInstallPath() + "/../../../../" +
425 GCCInstallation.getTriple().str() + "/libc")
426 .str();
427 if (getVFS().exists(Path))
428 return Path;
429 return std::string();
430 }
431
432 if (!GCCInstallation.isValid() || !getTriple().isMIPS())
433 return std::string();
434
435 // Standalone MIPS toolchains use different names for sysroot folder
436 // and put it into different places. Here we try to check some known
437 // variants.
438
439 const StringRef InstallDir = GCCInstallation.getInstallPath();
440 const StringRef TripleStr = GCCInstallation.getTriple().str();
441 const Multilib &Multilib = GCCInstallation.getMultilib();
442
443 std::string Path =
444 (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
445 .str();
446
447 if (getVFS().exists(Path))
448 return Path;
449
450 Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
451
452 if (getVFS().exists(Path))
453 return Path;
454
455 return std::string();
456}
457
458static void setPAuthABIInTriple(const Driver &D, const ArgList &Args,
459 llvm::Triple &Triple) {
460 Arg *ABIArg = Args.getLastArg(Ids: options::OPT_mabi_EQ);
461 bool HasPAuthABI =
462 ABIArg ? (StringRef(ABIArg->getValue()) == "pauthtest") : false;
463
464 switch (Triple.getEnvironment()) {
465 case llvm::Triple::UnknownEnvironment:
466 if (HasPAuthABI)
467 Triple.setEnvironment(llvm::Triple::PAuthTest);
468 break;
469 case llvm::Triple::PAuthTest:
470 break;
471 default:
472 if (HasPAuthABI)
473 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
474 << ABIArg->getAsString(Args) << Triple.getTriple();
475 break;
476 }
477}
478
479std::string Linux::ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args,
480 BoundArch BA,
481 types::ID InputType) const {
482 std::string TripleString =
483 Generic_ELF::ComputeEffectiveClangTriple(Args, BA, InputType);
484 if (getTriple().isAArch64()) {
485 llvm::Triple Triple(TripleString);
486 setPAuthABIInTriple(D: getDriver(), Args, Triple);
487 return Triple.getTriple();
488 }
489 return TripleString;
490}
491
492// Each combination of options here forms a signing schema, and in most cases
493// each signing schema is its own incompatible ABI. The default values of the
494// options represent the default signing schema.
495static void handlePAuthABI(const Driver &D, const ArgList &DriverArgs,
496 ArgStringList &CC1Args) {
497 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_intrinsics,
498 Ids: options::OPT_fno_ptrauth_intrinsics))
499 CC1Args.push_back(Elt: "-fptrauth-intrinsics");
500
501 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_calls,
502 Ids: options::OPT_fno_ptrauth_calls))
503 CC1Args.push_back(Elt: "-fptrauth-calls");
504
505 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_returns,
506 Ids: options::OPT_fno_ptrauth_returns))
507 CC1Args.push_back(Elt: "-fptrauth-returns");
508
509 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_auth_traps,
510 Ids: options::OPT_fno_ptrauth_auth_traps))
511 CC1Args.push_back(Elt: "-fptrauth-auth-traps");
512
513 if (!DriverArgs.hasArg(
514 Ids: options::OPT_fptrauth_vtable_pointer_address_discrimination,
515 Ids: options::OPT_fno_ptrauth_vtable_pointer_address_discrimination))
516 CC1Args.push_back(Elt: "-fptrauth-vtable-pointer-address-discrimination");
517
518 if (!DriverArgs.hasArg(
519 Ids: options::OPT_fptrauth_vtable_pointer_type_discrimination,
520 Ids: options::OPT_fno_ptrauth_vtable_pointer_type_discrimination))
521 CC1Args.push_back(Elt: "-fptrauth-vtable-pointer-type-discrimination");
522
523 if (!DriverArgs.hasArg(
524 Ids: options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
525 Ids: options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination))
526 CC1Args.push_back(Elt: "-fptrauth-type-info-vtable-pointer-discrimination");
527
528 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_indirect_gotos,
529 Ids: options::OPT_fno_ptrauth_indirect_gotos))
530 CC1Args.push_back(Elt: "-fptrauth-indirect-gotos");
531
532 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_init_fini,
533 Ids: options::OPT_fno_ptrauth_init_fini))
534 CC1Args.push_back(Elt: "-fptrauth-init-fini");
535
536 if (!DriverArgs.hasArg(
537 Ids: options::OPT_fptrauth_init_fini_address_discrimination,
538 Ids: options::OPT_fno_ptrauth_init_fini_address_discrimination))
539 CC1Args.push_back(Elt: "-fptrauth-init-fini-address-discrimination");
540
541 if (!DriverArgs.hasArg(Ids: options::OPT_faarch64_jump_table_hardening,
542 Ids: options::OPT_fno_aarch64_jump_table_hardening))
543 CC1Args.push_back(Elt: "-faarch64-jump-table-hardening");
544}
545
546void Linux::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
547 llvm::opt::ArgStringList &CC1Args,
548 BoundArch BA,
549 Action::OffloadKind DeviceOffloadKind) const {
550 llvm::Triple Triple(ComputeEffectiveClangTriple(Args: DriverArgs));
551 if (Triple.isAArch64() && Triple.getEnvironment() == llvm::Triple::PAuthTest)
552 handlePAuthABI(D: getDriver(), DriverArgs, CC1Args);
553 Generic_ELF::addClangTargetOptions(DriverArgs, CC1Args, BA,
554 DeviceOffloadKind);
555}
556
557std::string Linux::getDynamicLinker(const ArgList &Args) const {
558 const llvm::Triple::ArchType Arch = getArch();
559 const llvm::Triple &Triple = getTriple();
560
561 const Distro Distro(getDriver().getVFS(), Triple);
562
563 if (Triple.isAndroid()) {
564 if (getSanitizerArgs(JobArgs: Args).needsHwasanRt() &&
565 !Triple.isAndroidVersionLT(Major: 34) && Triple.isArch64Bit()) {
566 // On Android 14 and newer, there is a special linker_hwasan64 that
567 // allows to run HWASan binaries on non-HWASan system images. This
568 // is also available on HWASan system images, so we can just always
569 // use that instead.
570 return "/system/bin/linker_hwasan64";
571 }
572 return Triple.isArch64Bit() ? "/system/bin/linker64" : "/system/bin/linker";
573 }
574 if (Triple.isMusl()) {
575 std::string ArchName;
576 bool IsArm = false;
577
578 switch (Arch) {
579 case llvm::Triple::arm:
580 case llvm::Triple::thumb:
581 ArchName = "arm";
582 IsArm = true;
583 break;
584 case llvm::Triple::armeb:
585 case llvm::Triple::thumbeb:
586 ArchName = "armeb";
587 IsArm = true;
588 break;
589 case llvm::Triple::x86:
590 ArchName = "i386";
591 break;
592 case llvm::Triple::x86_64:
593 ArchName = Triple.isX32() ? "x32" : Triple.getArchName().str();
594 break;
595 default:
596 ArchName = Triple.getArchName().str();
597 }
598 if (IsArm &&
599 (Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
600 tools::arm::getARMFloatABI(TC: *this, Args) == tools::arm::FloatABI::Hard))
601 ArchName += "hf";
602 if (Arch == llvm::Triple::ppc &&
603 Triple.getSubArch() == llvm::Triple::PPCSubArch_spe)
604 ArchName = "powerpc-sf";
605 if (Triple.isRISCV()) {
606 StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
607 if (ABIName == "ilp32" || ABIName == "lp64") {
608 ArchName += "-sf";
609 } else if (ABIName == "ilp32f" || ABIName == "lp64f") {
610 ArchName += "-sp";
611 }
612 }
613
614 return "/lib/ld-musl-" + ArchName + ".so.1";
615 }
616
617 std::string LibDir;
618 std::string Loader;
619
620 switch (Arch) {
621 default:
622 llvm_unreachable("unsupported architecture");
623
624 case llvm::Triple::aarch64:
625 LibDir = "lib";
626 Loader = "ld-linux-aarch64.so.1";
627 break;
628 case llvm::Triple::aarch64_be:
629 LibDir = "lib";
630 Loader = "ld-linux-aarch64_be.so.1";
631 break;
632 case llvm::Triple::arm:
633 case llvm::Triple::thumb:
634 case llvm::Triple::armeb:
635 case llvm::Triple::thumbeb: {
636 const bool HF =
637 Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
638 Triple.getEnvironment() == llvm::Triple::GNUEABIHFT64 ||
639 tools::arm::getARMFloatABI(TC: *this, Args) == tools::arm::FloatABI::Hard;
640
641 LibDir = "lib";
642 Loader = HF ? "ld-linux-armhf.so.3" : "ld-linux.so.3";
643 break;
644 }
645 case llvm::Triple::loongarch32: {
646 LibDir = "lib32";
647 Loader =
648 ("ld-linux-loongarch-" +
649 tools::loongarch::getLoongArchABI(D: getDriver(), Args, Triple) + ".so.1")
650 .str();
651 break;
652 }
653 case llvm::Triple::loongarch64: {
654 LibDir = "lib64";
655 Loader =
656 ("ld-linux-loongarch-" +
657 tools::loongarch::getLoongArchABI(D: getDriver(), Args, Triple) + ".so.1")
658 .str();
659 break;
660 }
661 case llvm::Triple::m68k:
662 LibDir = "lib";
663 Loader = "ld.so.1";
664 break;
665 case llvm::Triple::mips:
666 case llvm::Triple::mipsel:
667 case llvm::Triple::mips64:
668 case llvm::Triple::mips64el: {
669 bool IsNaN2008 = tools::mips::isNaN2008(D: getDriver(), Args, Triple);
670
671 LibDir = "lib" + tools::mips::getMipsABILibSuffix(Args, Triple);
672
673 if (tools::mips::isUCLibc(Args))
674 Loader = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
675 else if (!Triple.hasEnvironment() &&
676 Triple.getVendor() == llvm::Triple::VendorType::MipsTechnologies)
677 Loader =
678 Triple.isLittleEndian() ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
679 else
680 Loader = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
681
682 break;
683 }
684 case llvm::Triple::ppc:
685 LibDir = "lib";
686 Loader = "ld.so.1";
687 break;
688 case llvm::Triple::ppcle:
689 LibDir = "lib";
690 Loader = "ld.so.1";
691 break;
692 case llvm::Triple::ppc64:
693 LibDir = "lib64";
694 Loader =
695 (tools::ppc::hasPPCAbiArg(Args, Value: "elfv2")) ? "ld64.so.2" : "ld64.so.1";
696 break;
697 case llvm::Triple::ppc64le:
698 LibDir = "lib64";
699 Loader =
700 (tools::ppc::hasPPCAbiArg(Args, Value: "elfv1")) ? "ld64.so.1" : "ld64.so.2";
701 break;
702 case llvm::Triple::riscv32:
703 case llvm::Triple::riscv64:
704 case llvm::Triple::riscv32be:
705 case llvm::Triple::riscv64be: {
706 StringRef ArchName = llvm::Triple::getArchTypeName(Kind: Arch);
707 StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
708 LibDir = "lib";
709 Loader = ("ld-linux-" + ArchName + "-" + ABIName + ".so.1").str();
710 break;
711 }
712 case llvm::Triple::sparc:
713 case llvm::Triple::sparcel:
714 LibDir = "lib";
715 Loader = "ld-linux.so.2";
716 break;
717 case llvm::Triple::sparcv9:
718 LibDir = "lib64";
719 Loader = "ld-linux.so.2";
720 break;
721 case llvm::Triple::systemz:
722 LibDir = "lib";
723 Loader = "ld64.so.1";
724 break;
725 case llvm::Triple::x86:
726 LibDir = "lib";
727 Loader = "ld-linux.so.2";
728 break;
729 case llvm::Triple::x86_64: {
730 bool X32 = Triple.isX32();
731
732 LibDir = X32 ? "libx32" : "lib64";
733 Loader = X32 ? "ld-linux-x32.so.2" : "ld-linux-x86-64.so.2";
734 break;
735 }
736 case llvm::Triple::ve:
737 return "/opt/nec/ve/lib/ld-linux-ve.so.1";
738 case llvm::Triple::csky: {
739 LibDir = "lib";
740 Loader = "ld.so.1";
741 break;
742 }
743 }
744
745 if (Distro == Distro::Exherbo &&
746 (Triple.getVendor() == llvm::Triple::UnknownVendor ||
747 Triple.getVendor() == llvm::Triple::PC))
748 return "/usr/" + Triple.str() + "/lib/" + Loader;
749 return "/" + LibDir + "/" + Loader;
750}
751
752void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
753 ArgStringList &CC1Args) const {
754 const Driver &D = getDriver();
755 std::string SysRoot = computeSysRoot();
756
757 if (DriverArgs.hasArg(Ids: options::OPT_nostdinc))
758 return;
759
760 // Add 'include' in the resource directory, which is similar to
761 // GCC_INCLUDE_DIR (private headers) in GCC. Note: the include directory
762 // contains some files conflicting with system /usr/include. musl systems
763 // prefer the /usr/include copies which are more relevant.
764 SmallString<128> ResourceDirInclude(D.ResourceDir);
765 llvm::sys::path::append(path&: ResourceDirInclude, a: "include");
766 if (!DriverArgs.hasArg(Ids: options::OPT_nobuiltininc) &&
767 (!getTriple().isMusl() || DriverArgs.hasArg(Ids: options::OPT_nostdlibinc)))
768 addSystemInclude(DriverArgs, CC1Args, Path: ResourceDirInclude);
769
770 if (DriverArgs.hasArg(Ids: options::OPT_nostdlibinc))
771 return;
772
773 // Add multilib variant include paths in priority order.
774 for (const Multilib &M : getOrderedMultilibs()) {
775 if (M.isDefault())
776 continue;
777 if (std::optional<std::string> StdlibIncDir = getStdlibIncludePath()) {
778 SmallString<128> Dir(*StdlibIncDir);
779 llvm::sys::path::append(path&: Dir, a: M.includeSuffix());
780 if (D.getVFS().exists(Path: Dir))
781 addSystemInclude(DriverArgs, CC1Args, Path: Dir);
782 }
783 }
784
785 // After the resource directory, we prioritize the standard clang include
786 // directory.
787 if (std::optional<std::string> Path = getStdlibIncludePath())
788 addSystemInclude(DriverArgs, CC1Args, Path: *Path);
789
790 // LOCAL_INCLUDE_DIR
791 addSystemInclude(DriverArgs, CC1Args, Path: concat(Path: SysRoot, A: "/usr/local/include"));
792 // TOOL_INCLUDE_DIR
793 AddMultilibIncludeArgs(DriverArgs, CC1Args);
794
795 // Check for configure-time C include directories.
796 StringRef CIncludeDirs(C_INCLUDE_DIRS);
797 if (CIncludeDirs != "") {
798 SmallVector<StringRef, 5> dirs;
799 CIncludeDirs.split(A&: dirs, Separator: ":");
800 for (StringRef dir : dirs) {
801 StringRef Prefix =
802 llvm::sys::path::is_absolute(path: dir) ? "" : StringRef(SysRoot);
803 addExternCSystemInclude(DriverArgs, CC1Args, Path: Prefix + dir);
804 }
805 return;
806 }
807
808 // On systems using multiarch and Android, add /usr/include/$triple before
809 // /usr/include.
810 std::string MultiarchIncludeDir = getMultiarchTriple(D, TargetTriple: getTriple(), SysRoot);
811 if (!MultiarchIncludeDir.empty() &&
812 D.getVFS().exists(Path: concat(Path: SysRoot, A: "/usr/include", B: MultiarchIncludeDir)))
813 addExternCSystemInclude(
814 DriverArgs, CC1Args,
815 Path: concat(Path: SysRoot, A: "/usr/include", B: MultiarchIncludeDir));
816
817 if (getTriple().getOS() == llvm::Triple::RTEMS)
818 return;
819
820 // Add an include of '/include' directly. This isn't provided by default by
821 // system GCCs, but is often used with cross-compiling GCCs, and harmless to
822 // add even when Clang is acting as-if it were a system compiler.
823 addExternCSystemInclude(DriverArgs, CC1Args, Path: concat(Path: SysRoot, A: "/include"));
824
825 addExternCSystemInclude(DriverArgs, CC1Args, Path: concat(Path: SysRoot, A: "/usr/include"));
826
827 if (!DriverArgs.hasArg(Ids: options::OPT_nobuiltininc) && getTriple().isMusl())
828 addSystemInclude(DriverArgs, CC1Args, Path: ResourceDirInclude);
829}
830
831void Linux::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
832 llvm::opt::ArgStringList &CC1Args) const {
833 // We need a detected GCC installation on Linux to provide libstdc++'s
834 // headers in odd Linuxish places.
835 if (!GCCInstallation.isValid())
836 return;
837
838 // Try generic GCC detection first.
839 if (Generic_GCC::addGCCLibStdCxxIncludePaths(DriverArgs, CC&: CC1Args))
840 return;
841
842 StringRef LibDir = GCCInstallation.getParentLibPath();
843 const Multilib &Multilib = GCCInstallation.getMultilib();
844 const GCCVersion &Version = GCCInstallation.getVersion();
845
846 StringRef TripleStr = GCCInstallation.getTriple().str();
847 const std::string LibStdCXXIncludePathCandidates[] = {
848 // Android standalone toolchain has C++ headers in yet another place.
849 LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
850 // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
851 // without a subdirectory corresponding to the gcc version.
852 LibDir.str() + "/../include/c++",
853 // Cray's gcc installation puts headers under "g++" without a
854 // version suffix.
855 LibDir.str() + "/../include/g++",
856 };
857
858 for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
859 if (addLibStdCXXIncludePaths(IncludeDir: IncludePath, Triple: TripleStr,
860 IncludeSuffix: Multilib.includeSuffix(), DriverArgs, CC1Args))
861 break;
862 }
863}
864
865void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs,
866 ArgStringList &CC1Args) const {
867 CudaInstallation->AddCudaIncludeArgs(DriverArgs, CC1Args);
868}
869
870void Linux::AddHIPIncludeArgs(const ArgList &DriverArgs,
871 ArgStringList &CC1Args) const {
872 RocmInstallation->AddHIPIncludeArgs(DriverArgs, CC1Args);
873}
874
875void Linux::addOffloadRTLibs(unsigned ActiveKinds, const ArgList &Args,
876 ArgStringList &CmdArgs) const {
877 if (!Args.hasFlag(Pos: options::OPT_offloadlib, Neg: options::OPT_no_offloadlib,
878 Default: true) ||
879 Args.hasArg(Ids: options::OPT_nostdlib) ||
880 Args.hasArg(Ids: options::OPT_no_hip_rt) || Args.hasArg(Ids: options::OPT_r))
881 return;
882
883 llvm::SmallVector<std::pair<StringRef, StringRef>> Libraries;
884 if (ActiveKinds & Action::OFK_HIP)
885 Libraries.emplace_back(Args: RocmInstallation->getLibPath(), Args: "libamdhip64.so");
886 else if ((ActiveKinds & Action::OFK_SYCL) &&
887 !Args.hasArg(Ids: options::OPT_nolibsycl))
888 Libraries.emplace_back(Args: SYCLInstallation->getSYCLRTLibPath(),
889 Args: "libLLVMSYCL.so");
890
891 for (auto [Path, Library] : Libraries) {
892 if (Args.hasFlag(Pos: options::OPT_frtlib_add_rpath,
893 Neg: options::OPT_fno_rtlib_add_rpath, Default: false)) {
894 SmallString<0> p = Path;
895 llvm::sys::path::remove_dots(path&: p, remove_dot_dot: true);
896 CmdArgs.append(IL: {"-rpath", Args.MakeArgString(Str: p)});
897 }
898
899 SmallString<0> p = Path;
900 llvm::sys::path::append(path&: p, a: Library);
901 CmdArgs.push_back(Elt: Args.MakeArgString(Str: p));
902 }
903
904 // FIXME: The ROCm builds implicitly depends on this being present.
905 if (ActiveKinds & Action::OFK_HIP)
906 CmdArgs.push_back(
907 Elt: Args.MakeArgString(Str: StringRef("-L") + RocmInstallation->getLibPath()));
908
909 // For HIP device PGO, link clang_rt.profile_rocm when available. It is a
910 // self-contained superset of clang_rt.profile, emitted first so the base
911 // archive stays inert.
912 if ((ActiveKinds & Action::OFK_HIP) && needsProfileRT(Args) &&
913 getVFS().exists(Path: getCompilerRT(Args, Component: "profile_rocm", Type: FT_Static))) {
914 CmdArgs.push_back(Elt: getCompilerRTArgString(Args, Component: "profile_rocm"));
915 // Force-retain the constructor-only hipModuleLoad* interceptor object; its
916 // constructor self-skips when the program does not use hipModuleLoad.
917 CmdArgs.push_back(Elt: "-u");
918 CmdArgs.push_back(Elt: "__llvm_profile_offload_register_dynamic_module");
919 }
920}
921
922void Linux::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
923 ArgStringList &CC1Args) const {
924 if (GCCInstallation.isValid()) {
925 CC1Args.push_back(Elt: "-isystem");
926 CC1Args.push_back(Elt: DriverArgs.MakeArgString(
927 Str: GCCInstallation.getParentLibPath() + "/../" +
928 GCCInstallation.getTriple().str() + "/include"));
929 }
930}
931
932void Linux::addSYCLIncludeArgs(const ArgList &DriverArgs,
933 ArgStringList &CC1Args) const {
934 SYCLInstallation->addSYCLIncludeArgs(DriverArgs, CC1Args);
935}
936
937bool Linux::isPIEDefault(const llvm::opt::ArgList &Args) const {
938 return CLANG_DEFAULT_PIE_ON_LINUX || getTriple().isAndroid() ||
939 getTriple().isMusl() || getSanitizerArgs(JobArgs: Args).requiresPIE();
940}
941
942bool Linux::IsAArch64OutlineAtomicsDefault(const ArgList &Args) const {
943 // Outline atomics for AArch64 are supported by compiler-rt
944 // and libgcc since 9.3.1
945 assert(getTriple().isAArch64() && "expected AArch64 target!");
946 ToolChain::RuntimeLibType RtLib = GetRuntimeLibType(Args);
947 if (RtLib == ToolChain::RLT_CompilerRT)
948 return true;
949 assert(RtLib == ToolChain::RLT_Libgcc && "unexpected runtime library type!");
950 if (GCCInstallation.getVersion().isOlderThan(RHSMajor: 9, RHSMinor: 3, RHSPatch: 1))
951 return false;
952 return true;
953}
954
955bool Linux::IsMathErrnoDefault() const {
956 if (getTriple().isAndroid() || getTriple().isMusl())
957 return false;
958 return Generic_ELF::IsMathErrnoDefault();
959}
960
961SanitizerMask
962Linux::getSupportedSanitizers(BoundArch BA,
963 Action::OffloadKind DeviceOffloadKind) const {
964 const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
965 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
966 const bool IsMIPS = getTriple().isMIPS32();
967 const bool IsMIPS64 = getTriple().isMIPS64();
968 const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
969 getTriple().getArch() == llvm::Triple::ppc64le;
970 const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
971 getTriple().getArch() == llvm::Triple::aarch64_be;
972 const bool IsArmArch = getTriple().getArch() == llvm::Triple::arm ||
973 getTriple().getArch() == llvm::Triple::thumb ||
974 getTriple().getArch() == llvm::Triple::armeb ||
975 getTriple().getArch() == llvm::Triple::thumbeb;
976 const bool IsLoongArch64 = getTriple().getArch() == llvm::Triple::loongarch64;
977 const bool IsRISCV64 = getTriple().isRISCV64();
978 const bool IsSystemZ = getTriple().getArch() == llvm::Triple::systemz;
979 const bool IsHexagon = getTriple().getArch() == llvm::Triple::hexagon;
980 const bool IsAndroid = getTriple().isAndroid();
981 SanitizerMask Res = ToolChain::getSupportedSanitizers(BA, DeviceOffloadKind);
982 Res |= SanitizerKind::Address;
983 Res |= SanitizerKind::PointerCompare;
984 Res |= SanitizerKind::PointerSubtract;
985 Res |= SanitizerKind::Realtime;
986 Res |= SanitizerKind::Fuzzer;
987 Res |= SanitizerKind::FuzzerNoLink;
988 Res |= SanitizerKind::KernelAddress;
989 Res |= SanitizerKind::Vptr;
990 Res |= SanitizerKind::SafeStack;
991 if (IsX86_64 || IsMIPS64 || IsAArch64 || IsLoongArch64 || IsSystemZ)
992 Res |= SanitizerKind::DataFlow;
993 if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsArmArch || IsPowerPC64 ||
994 IsRISCV64 || IsSystemZ || IsHexagon || IsLoongArch64)
995 Res |= SanitizerKind::Leak;
996 if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64 || IsSystemZ ||
997 IsLoongArch64 || IsRISCV64)
998 Res |= SanitizerKind::Thread;
999 if (IsX86_64 || IsAArch64 || IsSystemZ || IsHexagon)
1000 Res |= SanitizerKind::Type;
1001 if (IsX86_64 || IsSystemZ || IsPowerPC64)
1002 Res |= SanitizerKind::KernelMemory;
1003 if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsMIPS || IsArmArch ||
1004 IsPowerPC64 || IsHexagon || IsLoongArch64 || IsRISCV64 || IsSystemZ)
1005 Res |= SanitizerKind::Scudo;
1006 if (IsX86_64 || IsAArch64 || IsRISCV64) {
1007 Res |= SanitizerKind::HWAddress;
1008 }
1009 if (IsHexagon)
1010 Res |= SanitizerKind::ShadowCallStack;
1011 if (IsX86_64 || IsAArch64) {
1012 Res |= SanitizerKind::KernelHWAddress;
1013 }
1014 if (IsX86_64)
1015 Res |= SanitizerKind::NumericalStability;
1016 if (!IsAndroid)
1017 Res |= SanitizerKind::Memory;
1018
1019 // Work around "Cannot represent a difference across sections".
1020 if (getTriple().getArch() == llvm::Triple::ppc64)
1021 Res &= ~SanitizerKind::Function;
1022 return Res;
1023}
1024
1025void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args,
1026 llvm::opt::ArgStringList &CmdArgs) const {
1027 // Add linker option -u__llvm_profile_runtime to cause runtime
1028 // initialization module to be linked in.
1029 if (needsProfileRT(Args))
1030 CmdArgs.push_back(Elt: Args.MakeArgString(
1031 Str: Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
1032 ToolChain::addProfileRTLibs(Args, CmdArgs);
1033}
1034
1035void Linux::addExtraOpts(llvm::opt::ArgStringList &CmdArgs) const {
1036 for (const auto &Opt : ExtraOpts)
1037 CmdArgs.push_back(Elt: Opt.c_str());
1038}
1039
1040const char *Linux::getDefaultLinker() const {
1041 if (getTriple().isAndroid())
1042 return "ld.lld";
1043 return Generic_ELF::getDefaultLinker();
1044}
1045