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 llvm::Triple::ArchType Arch = Triple.getArch();
238 std::string SysRoot = computeSysRoot();
239 ToolChain::path_list &PPaths = getProgramPaths();
240
241 Generic_GCC::PushPPaths(PPaths);
242
243 Distro Distro(D.getVFS(), Triple);
244
245 if (Distro.IsAlpineLinux() || Triple.isAndroid()) {
246 ExtraOpts.push_back(x: "-z");
247 ExtraOpts.push_back(x: "now");
248 }
249
250 if (Distro.IsOpenSUSE() || Distro.IsUbuntu() || Distro.IsAlpineLinux() ||
251 Triple.isAndroid()) {
252 ExtraOpts.push_back(x: "-z");
253 ExtraOpts.push_back(x: "relro");
254 }
255
256 // Note, lld from 11 onwards default max-page-size to 65536 for both ARM and
257 // AArch64.
258 if (Triple.isAndroid()) {
259 if (Triple.isARM()) {
260 // Android ARM uses max-page-size=4096 to reduce VMA usage.
261 ExtraOpts.push_back(x: "-z");
262 ExtraOpts.push_back(x: "max-page-size=4096");
263 } else if (Triple.isAArch64() || Triple.getArch() == llvm::Triple::x86_64) {
264 // Android AArch64 uses max-page-size=16384 to support 4k/16k page sizes.
265 // Android emulates a 16k page size for app testing on x86_64 machines.
266 ExtraOpts.push_back(x: "-z");
267 ExtraOpts.push_back(x: "max-page-size=16384");
268 }
269 if (Triple.isAndroidVersionLT(Major: 29)) {
270 // https://github.com/android/ndk/issues/1196
271 // The unwinder used by the crash handler on versions of Android prior to
272 // API 29 did not correctly handle binaries built with rosegment, which is
273 // enabled by default for LLD. Android only supports LLD, so it's not an
274 // issue that this flag is not accepted by other linkers.
275 ExtraOpts.push_back(x: "--no-rosegment");
276 }
277 // SHT_RELR relocations are only supported at API level >= 30.
278 // ANDROID_RELR relocations were supported at API level >= 28.
279 // Relocation packer was supported at API level >= 23.
280 if (!Triple.isAndroidVersionLT(Major: 30)) {
281 ExtraOpts.push_back(x: "--pack-dyn-relocs=android+relr");
282 } else if (!Triple.isAndroidVersionLT(Major: 28)) {
283 ExtraOpts.push_back(x: "--pack-dyn-relocs=android+relr");
284 ExtraOpts.push_back(x: "--use-android-relr-tags");
285 } else if (!Triple.isAndroidVersionLT(Major: 23)) {
286 ExtraOpts.push_back(x: "--pack-dyn-relocs=android");
287 }
288 }
289
290 if (GCCInstallation.getParentLibPath().contains(Other: "opt/rh/"))
291 // With devtoolset on RHEL, we want to add a bin directory that is relative
292 // to the detected gcc install, because if we are using devtoolset gcc then
293 // we want to use other tools from devtoolset (e.g. ld) instead of the
294 // standard system tools.
295 PPaths.push_back(Elt: Twine(GCCInstallation.getParentLibPath() +
296 "/../bin").str());
297
298 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
299 ExtraOpts.push_back(x: "-X");
300
301 const bool IsAndroid = Triple.isAndroid();
302 const bool IsMips = Triple.isMIPS();
303 const bool IsHexagon = Arch == llvm::Triple::hexagon;
304 const bool IsRISCV = Triple.isRISCV();
305 const bool IsCSKY = Triple.isCSKY();
306
307 if (IsCSKY && !SelectedMultilibs.empty())
308 SysRoot = SysRoot + SelectedMultilibs.back().osSuffix();
309
310 if ((IsMips || IsCSKY) && !SysRoot.empty())
311 ExtraOpts.push_back(x: "--sysroot=" + SysRoot);
312
313 // Do not use 'gnu' hash style for Mips targets because .gnu.hash
314 // and the MIPS ABI require .dynsym to be sorted in different ways.
315 // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
316 // ABI requires a mapping between the GOT and the symbol table.
317 // Android loader does not support .gnu.hash until API 23.
318 // Hexagon linker/loader does not support .gnu.hash.
319 // SUSE SLES 11 will stop being supported Mar 2028.
320 if (!IsMips && !IsHexagon) {
321 if (Distro.IsOpenSUSE() || (IsAndroid && Triple.isAndroidVersionLT(Major: 23)))
322 ExtraOpts.push_back(x: "--hash-style=both");
323 else
324 ExtraOpts.push_back(x: "--hash-style=gnu");
325 }
326
327#ifdef ENABLE_LINKER_BUILD_ID
328 ExtraOpts.push_back("--build-id");
329#endif
330
331 // The selection of paths to try here is designed to match the patterns which
332 // the GCC driver itself uses, as this is part of the GCC-compatible driver.
333 // This was determined by running GCC in a fake filesystem, creating all
334 // possible permutations of these directories, and seeing which ones it added
335 // to the link paths.
336 path_list &Paths = getFilePaths();
337
338 const std::string OSLibDir = std::string(getOSLibDir(Triple, Args));
339 const std::string MultiarchTriple = getMultiarchTriple(D, TargetTriple: Triple, SysRoot);
340
341 // mips32: Debian multilib, we use /libo32, while in other case, /lib is
342 // used. We need add both libo32 and /lib.
343 if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel) {
344 Generic_GCC::AddMultilibPaths(D, SysRoot, OSLibDir: "libo32", MultiarchTriple, Paths);
345 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/libo32"), Paths);
346 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/usr/libo32"), Paths);
347 }
348 Generic_GCC::AddMultilibPaths(D, SysRoot, OSLibDir, MultiarchTriple, Paths);
349
350 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/lib", B: MultiarchTriple), Paths);
351 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/lib/..", B: OSLibDir), Paths);
352
353 if (IsAndroid) {
354 // Android sysroots contain a library directory for each supported OS
355 // version as well as some unversioned libraries in the usual multiarch
356 // directory.
357 addPathIfExists(
358 D,
359 Path: concat(Path: SysRoot, A: "/usr/lib", B: MultiarchTriple,
360 C: llvm::to_string(Value: Triple.getEnvironmentVersion().getMajor())),
361 Paths);
362 }
363
364 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/usr/lib", B: MultiarchTriple), Paths);
365 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/usr", B: OSLibDir), Paths);
366 if (IsRISCV) {
367 StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
368 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/", B: OSLibDir, C: ABIName), Paths);
369 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/usr", B: OSLibDir, C: ABIName), Paths);
370 }
371
372 Generic_GCC::AddMultiarchPaths(D, SysRoot, OSLibDir, Paths);
373
374 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/lib"), Paths);
375 addPathIfExists(D, Path: concat(Path: SysRoot, A: "/usr/lib"), Paths);
376}
377
378ToolChain::RuntimeLibType Linux::GetDefaultRuntimeLibType() const {
379 if (getTriple().isAndroid())
380 return ToolChain::RLT_CompilerRT;
381 return Generic_ELF::GetDefaultRuntimeLibType();
382}
383
384unsigned Linux::GetDefaultDwarfVersion() const {
385 if (getTriple().isAndroid())
386 return 4;
387 return ToolChain::GetDefaultDwarfVersion();
388}
389
390ToolChain::CXXStdlibType Linux::GetDefaultCXXStdlibType() const {
391 if (getTriple().isAndroid())
392 return ToolChain::CST_Libcxx;
393 return ToolChain::CST_Libstdcxx;
394}
395
396bool Linux::HasNativeLLVMSupport() const { return true; }
397
398Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
399
400Tool *Linux::buildStaticLibTool() const {
401 return new tools::gnutools::StaticLibTool(*this);
402}
403
404Tool *Linux::buildAssembler() const {
405 return new tools::gnutools::Assembler(*this);
406}
407
408std::string Linux::computeSysRoot() const {
409 if (!getDriver().SysRoot.empty())
410 return getDriver().SysRoot;
411
412 if (getTriple().isAndroid()) {
413 // Android toolchains typically include a sysroot at ../sysroot relative to
414 // the clang binary.
415 const StringRef ClangDir = getDriver().Dir;
416 std::string AndroidSysRootPath = (ClangDir + "/../sysroot").str();
417 if (getVFS().exists(Path: AndroidSysRootPath))
418 return AndroidSysRootPath;
419 }
420
421 if (getTriple().isCSKY()) {
422 // CSKY toolchains use different names for sysroot folder.
423 if (!GCCInstallation.isValid())
424 return std::string();
425 // GCCInstallation.getInstallPath() =
426 // $GCCToolchainPath/lib/gcc/csky-linux-gnuabiv2/6.3.0
427 // Path = $GCCToolchainPath/csky-linux-gnuabiv2/libc
428 std::string Path = (GCCInstallation.getInstallPath() + "/../../../../" +
429 GCCInstallation.getTriple().str() + "/libc")
430 .str();
431 if (getVFS().exists(Path))
432 return Path;
433 return std::string();
434 }
435
436 if (!GCCInstallation.isValid() || !getTriple().isMIPS())
437 return std::string();
438
439 // Standalone MIPS toolchains use different names for sysroot folder
440 // and put it into different places. Here we try to check some known
441 // variants.
442
443 const StringRef InstallDir = GCCInstallation.getInstallPath();
444 const StringRef TripleStr = GCCInstallation.getTriple().str();
445 const Multilib &Multilib = GCCInstallation.getMultilib();
446
447 std::string Path =
448 (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
449 .str();
450
451 if (getVFS().exists(Path))
452 return Path;
453
454 Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
455
456 if (getVFS().exists(Path))
457 return Path;
458
459 return std::string();
460}
461
462static void setPAuthABIInTriple(const Driver &D, const ArgList &Args,
463 llvm::Triple &Triple) {
464 Arg *ABIArg = Args.getLastArg(Ids: options::OPT_mabi_EQ);
465 bool HasPAuthABI =
466 ABIArg ? (StringRef(ABIArg->getValue()) == "pauthtest") : false;
467
468 switch (Triple.getEnvironment()) {
469 case llvm::Triple::UnknownEnvironment:
470 if (HasPAuthABI)
471 Triple.setEnvironment(llvm::Triple::PAuthTest);
472 break;
473 case llvm::Triple::PAuthTest:
474 break;
475 default:
476 if (HasPAuthABI)
477 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
478 << ABIArg->getAsString(Args) << Triple.getTriple();
479 break;
480 }
481}
482
483std::string Linux::ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args,
484 types::ID InputType) const {
485 std::string TripleString =
486 Generic_ELF::ComputeEffectiveClangTriple(Args, InputType);
487 if (getTriple().isAArch64()) {
488 llvm::Triple Triple(TripleString);
489 setPAuthABIInTriple(D: getDriver(), Args, Triple);
490 return Triple.getTriple();
491 }
492 return TripleString;
493}
494
495// Each combination of options here forms a signing schema, and in most cases
496// each signing schema is its own incompatible ABI. The default values of the
497// options represent the default signing schema.
498static void handlePAuthABI(const Driver &D, const ArgList &DriverArgs,
499 ArgStringList &CC1Args) {
500 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_intrinsics,
501 Ids: options::OPT_fno_ptrauth_intrinsics))
502 CC1Args.push_back(Elt: "-fptrauth-intrinsics");
503
504 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_calls,
505 Ids: options::OPT_fno_ptrauth_calls))
506 CC1Args.push_back(Elt: "-fptrauth-calls");
507
508 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_returns,
509 Ids: options::OPT_fno_ptrauth_returns))
510 CC1Args.push_back(Elt: "-fptrauth-returns");
511
512 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_auth_traps,
513 Ids: options::OPT_fno_ptrauth_auth_traps))
514 CC1Args.push_back(Elt: "-fptrauth-auth-traps");
515
516 if (!DriverArgs.hasArg(
517 Ids: options::OPT_fptrauth_vtable_pointer_address_discrimination,
518 Ids: options::OPT_fno_ptrauth_vtable_pointer_address_discrimination))
519 CC1Args.push_back(Elt: "-fptrauth-vtable-pointer-address-discrimination");
520
521 if (!DriverArgs.hasArg(
522 Ids: options::OPT_fptrauth_vtable_pointer_type_discrimination,
523 Ids: options::OPT_fno_ptrauth_vtable_pointer_type_discrimination))
524 CC1Args.push_back(Elt: "-fptrauth-vtable-pointer-type-discrimination");
525
526 if (!DriverArgs.hasArg(
527 Ids: options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
528 Ids: options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination))
529 CC1Args.push_back(Elt: "-fptrauth-type-info-vtable-pointer-discrimination");
530
531 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_indirect_gotos,
532 Ids: options::OPT_fno_ptrauth_indirect_gotos))
533 CC1Args.push_back(Elt: "-fptrauth-indirect-gotos");
534
535 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_init_fini,
536 Ids: options::OPT_fno_ptrauth_init_fini))
537 CC1Args.push_back(Elt: "-fptrauth-init-fini");
538
539 if (!DriverArgs.hasArg(
540 Ids: options::OPT_fptrauth_init_fini_address_discrimination,
541 Ids: options::OPT_fno_ptrauth_init_fini_address_discrimination))
542 CC1Args.push_back(Elt: "-fptrauth-init-fini-address-discrimination");
543
544 if (!DriverArgs.hasArg(Ids: options::OPT_faarch64_jump_table_hardening,
545 Ids: options::OPT_fno_aarch64_jump_table_hardening))
546 CC1Args.push_back(Elt: "-faarch64-jump-table-hardening");
547}
548
549void Linux::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
550 llvm::opt::ArgStringList &CC1Args,
551 Action::OffloadKind DeviceOffloadKind) const {
552 llvm::Triple Triple(ComputeEffectiveClangTriple(Args: DriverArgs));
553 if (Triple.isAArch64() && Triple.getEnvironment() == llvm::Triple::PAuthTest)
554 handlePAuthABI(D: getDriver(), DriverArgs, CC1Args);
555 Generic_ELF::addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadKind);
556}
557
558std::string Linux::getDynamicLinker(const ArgList &Args) const {
559 const llvm::Triple::ArchType Arch = getArch();
560 const llvm::Triple &Triple = getTriple();
561
562 const Distro Distro(getDriver().getVFS(), Triple);
563
564 if (Triple.isAndroid()) {
565 if (getSanitizerArgs(JobArgs: Args).needsHwasanRt() &&
566 !Triple.isAndroidVersionLT(Major: 34) && Triple.isArch64Bit()) {
567 // On Android 14 and newer, there is a special linker_hwasan64 that
568 // allows to run HWASan binaries on non-HWASan system images. This
569 // is also available on HWASan system images, so we can just always
570 // use that instead.
571 return "/system/bin/linker_hwasan64";
572 }
573 return Triple.isArch64Bit() ? "/system/bin/linker64" : "/system/bin/linker";
574 }
575 if (Triple.isMusl()) {
576 std::string ArchName;
577 bool IsArm = false;
578
579 switch (Arch) {
580 case llvm::Triple::arm:
581 case llvm::Triple::thumb:
582 ArchName = "arm";
583 IsArm = true;
584 break;
585 case llvm::Triple::armeb:
586 case llvm::Triple::thumbeb:
587 ArchName = "armeb";
588 IsArm = true;
589 break;
590 case llvm::Triple::x86:
591 ArchName = "i386";
592 break;
593 case llvm::Triple::x86_64:
594 ArchName = Triple.isX32() ? "x32" : Triple.getArchName().str();
595 break;
596 default:
597 ArchName = Triple.getArchName().str();
598 }
599 if (IsArm &&
600 (Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
601 tools::arm::getARMFloatABI(TC: *this, Args) == tools::arm::FloatABI::Hard))
602 ArchName += "hf";
603 if (Arch == llvm::Triple::ppc &&
604 Triple.getSubArch() == llvm::Triple::PPCSubArch_spe)
605 ArchName = "powerpc-sf";
606
607 return "/lib/ld-musl-" + ArchName + ".so.1";
608 }
609
610 std::string LibDir;
611 std::string Loader;
612
613 switch (Arch) {
614 default:
615 llvm_unreachable("unsupported architecture");
616
617 case llvm::Triple::aarch64:
618 LibDir = "lib";
619 Loader = "ld-linux-aarch64.so.1";
620 break;
621 case llvm::Triple::aarch64_be:
622 LibDir = "lib";
623 Loader = "ld-linux-aarch64_be.so.1";
624 break;
625 case llvm::Triple::arm:
626 case llvm::Triple::thumb:
627 case llvm::Triple::armeb:
628 case llvm::Triple::thumbeb: {
629 const bool HF =
630 Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
631 Triple.getEnvironment() == llvm::Triple::GNUEABIHFT64 ||
632 tools::arm::getARMFloatABI(TC: *this, Args) == tools::arm::FloatABI::Hard;
633
634 LibDir = "lib";
635 Loader = HF ? "ld-linux-armhf.so.3" : "ld-linux.so.3";
636 break;
637 }
638 case llvm::Triple::loongarch32: {
639 LibDir = "lib32";
640 Loader =
641 ("ld-linux-loongarch-" +
642 tools::loongarch::getLoongArchABI(D: getDriver(), Args, Triple) + ".so.1")
643 .str();
644 break;
645 }
646 case llvm::Triple::loongarch64: {
647 LibDir = "lib64";
648 Loader =
649 ("ld-linux-loongarch-" +
650 tools::loongarch::getLoongArchABI(D: getDriver(), Args, Triple) + ".so.1")
651 .str();
652 break;
653 }
654 case llvm::Triple::m68k:
655 LibDir = "lib";
656 Loader = "ld.so.1";
657 break;
658 case llvm::Triple::mips:
659 case llvm::Triple::mipsel:
660 case llvm::Triple::mips64:
661 case llvm::Triple::mips64el: {
662 bool IsNaN2008 = tools::mips::isNaN2008(D: getDriver(), Args, Triple);
663
664 LibDir = "lib" + tools::mips::getMipsABILibSuffix(Args, Triple);
665
666 if (tools::mips::isUCLibc(Args))
667 Loader = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
668 else if (!Triple.hasEnvironment() &&
669 Triple.getVendor() == llvm::Triple::VendorType::MipsTechnologies)
670 Loader =
671 Triple.isLittleEndian() ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
672 else
673 Loader = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
674
675 break;
676 }
677 case llvm::Triple::ppc:
678 LibDir = "lib";
679 Loader = "ld.so.1";
680 break;
681 case llvm::Triple::ppcle:
682 LibDir = "lib";
683 Loader = "ld.so.1";
684 break;
685 case llvm::Triple::ppc64:
686 LibDir = "lib64";
687 Loader =
688 (tools::ppc::hasPPCAbiArg(Args, Value: "elfv2")) ? "ld64.so.2" : "ld64.so.1";
689 break;
690 case llvm::Triple::ppc64le:
691 LibDir = "lib64";
692 Loader =
693 (tools::ppc::hasPPCAbiArg(Args, Value: "elfv1")) ? "ld64.so.1" : "ld64.so.2";
694 break;
695 case llvm::Triple::riscv32:
696 case llvm::Triple::riscv64:
697 case llvm::Triple::riscv32be:
698 case llvm::Triple::riscv64be: {
699 StringRef ArchName = llvm::Triple::getArchTypeName(Kind: Arch);
700 StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
701 LibDir = "lib";
702 Loader = ("ld-linux-" + ArchName + "-" + ABIName + ".so.1").str();
703 break;
704 }
705 case llvm::Triple::sparc:
706 case llvm::Triple::sparcel:
707 LibDir = "lib";
708 Loader = "ld-linux.so.2";
709 break;
710 case llvm::Triple::sparcv9:
711 LibDir = "lib64";
712 Loader = "ld-linux.so.2";
713 break;
714 case llvm::Triple::systemz:
715 LibDir = "lib";
716 Loader = "ld64.so.1";
717 break;
718 case llvm::Triple::x86:
719 LibDir = "lib";
720 Loader = "ld-linux.so.2";
721 break;
722 case llvm::Triple::x86_64: {
723 bool X32 = Triple.isX32();
724
725 LibDir = X32 ? "libx32" : "lib64";
726 Loader = X32 ? "ld-linux-x32.so.2" : "ld-linux-x86-64.so.2";
727 break;
728 }
729 case llvm::Triple::ve:
730 return "/opt/nec/ve/lib/ld-linux-ve.so.1";
731 case llvm::Triple::csky: {
732 LibDir = "lib";
733 Loader = "ld.so.1";
734 break;
735 }
736 }
737
738 if (Distro == Distro::Exherbo &&
739 (Triple.getVendor() == llvm::Triple::UnknownVendor ||
740 Triple.getVendor() == llvm::Triple::PC))
741 return "/usr/" + Triple.str() + "/lib/" + Loader;
742 return "/" + LibDir + "/" + Loader;
743}
744
745void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
746 ArgStringList &CC1Args) const {
747 const Driver &D = getDriver();
748 std::string SysRoot = computeSysRoot();
749
750 if (DriverArgs.hasArg(Ids: options::OPT_nostdinc))
751 return;
752
753 // Add 'include' in the resource directory, which is similar to
754 // GCC_INCLUDE_DIR (private headers) in GCC. Note: the include directory
755 // contains some files conflicting with system /usr/include. musl systems
756 // prefer the /usr/include copies which are more relevant.
757 SmallString<128> ResourceDirInclude(D.ResourceDir);
758 llvm::sys::path::append(path&: ResourceDirInclude, a: "include");
759 if (!DriverArgs.hasArg(Ids: options::OPT_nobuiltininc) &&
760 (!getTriple().isMusl() || DriverArgs.hasArg(Ids: options::OPT_nostdlibinc)))
761 addSystemInclude(DriverArgs, CC1Args, Path: ResourceDirInclude);
762
763 if (DriverArgs.hasArg(Ids: options::OPT_nostdlibinc))
764 return;
765
766 // After the resource directory, we prioritize the standard clang include
767 // directory.
768 if (std::optional<std::string> Path = getStdlibIncludePath())
769 addSystemInclude(DriverArgs, CC1Args, Path: *Path);
770
771 // LOCAL_INCLUDE_DIR
772 addSystemInclude(DriverArgs, CC1Args, Path: concat(Path: SysRoot, A: "/usr/local/include"));
773 // TOOL_INCLUDE_DIR
774 AddMultilibIncludeArgs(DriverArgs, CC1Args);
775
776 // Check for configure-time C include directories.
777 StringRef CIncludeDirs(C_INCLUDE_DIRS);
778 if (CIncludeDirs != "") {
779 SmallVector<StringRef, 5> dirs;
780 CIncludeDirs.split(A&: dirs, Separator: ":");
781 for (StringRef dir : dirs) {
782 StringRef Prefix =
783 llvm::sys::path::is_absolute(path: dir) ? "" : StringRef(SysRoot);
784 addExternCSystemInclude(DriverArgs, CC1Args, Path: Prefix + dir);
785 }
786 return;
787 }
788
789 // On systems using multiarch and Android, add /usr/include/$triple before
790 // /usr/include.
791 std::string MultiarchIncludeDir = getMultiarchTriple(D, TargetTriple: getTriple(), SysRoot);
792 if (!MultiarchIncludeDir.empty() &&
793 D.getVFS().exists(Path: concat(Path: SysRoot, A: "/usr/include", B: MultiarchIncludeDir)))
794 addExternCSystemInclude(
795 DriverArgs, CC1Args,
796 Path: concat(Path: SysRoot, A: "/usr/include", B: MultiarchIncludeDir));
797
798 if (getTriple().getOS() == llvm::Triple::RTEMS)
799 return;
800
801 // Add an include of '/include' directly. This isn't provided by default by
802 // system GCCs, but is often used with cross-compiling GCCs, and harmless to
803 // add even when Clang is acting as-if it were a system compiler.
804 addExternCSystemInclude(DriverArgs, CC1Args, Path: concat(Path: SysRoot, A: "/include"));
805
806 addExternCSystemInclude(DriverArgs, CC1Args, Path: concat(Path: SysRoot, A: "/usr/include"));
807
808 if (!DriverArgs.hasArg(Ids: options::OPT_nobuiltininc) && getTriple().isMusl())
809 addSystemInclude(DriverArgs, CC1Args, Path: ResourceDirInclude);
810}
811
812void Linux::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
813 llvm::opt::ArgStringList &CC1Args) const {
814 // We need a detected GCC installation on Linux to provide libstdc++'s
815 // headers in odd Linuxish places.
816 if (!GCCInstallation.isValid())
817 return;
818
819 // Try generic GCC detection first.
820 if (Generic_GCC::addGCCLibStdCxxIncludePaths(DriverArgs, CC&: CC1Args))
821 return;
822
823 StringRef LibDir = GCCInstallation.getParentLibPath();
824 const Multilib &Multilib = GCCInstallation.getMultilib();
825 const GCCVersion &Version = GCCInstallation.getVersion();
826
827 StringRef TripleStr = GCCInstallation.getTriple().str();
828 const std::string LibStdCXXIncludePathCandidates[] = {
829 // Android standalone toolchain has C++ headers in yet another place.
830 LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
831 // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
832 // without a subdirectory corresponding to the gcc version.
833 LibDir.str() + "/../include/c++",
834 // Cray's gcc installation puts headers under "g++" without a
835 // version suffix.
836 LibDir.str() + "/../include/g++",
837 };
838
839 for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
840 if (addLibStdCXXIncludePaths(IncludeDir: IncludePath, Triple: TripleStr,
841 IncludeSuffix: Multilib.includeSuffix(), DriverArgs, CC1Args))
842 break;
843 }
844}
845
846void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs,
847 ArgStringList &CC1Args) const {
848 CudaInstallation->AddCudaIncludeArgs(DriverArgs, CC1Args);
849}
850
851void Linux::AddHIPIncludeArgs(const ArgList &DriverArgs,
852 ArgStringList &CC1Args) const {
853 RocmInstallation->AddHIPIncludeArgs(DriverArgs, CC1Args);
854}
855
856void Linux::addOffloadRTLibs(unsigned ActiveKinds, const ArgList &Args,
857 ArgStringList &CmdArgs) const {
858 if (!Args.hasFlag(Pos: options::OPT_offloadlib, Neg: options::OPT_no_offloadlib,
859 Default: true) ||
860 Args.hasArg(Ids: options::OPT_nostdlib) ||
861 Args.hasArg(Ids: options::OPT_no_hip_rt) || Args.hasArg(Ids: options::OPT_r))
862 return;
863
864 llvm::SmallVector<std::pair<StringRef, StringRef>> Libraries;
865 if (ActiveKinds & Action::OFK_HIP)
866 Libraries.emplace_back(Args: RocmInstallation->getLibPath(), Args: "libamdhip64.so");
867 else if (ActiveKinds & Action::OFK_SYCL)
868 Libraries.emplace_back(Args: SYCLInstallation->getSYCLRTLibPath(),
869 Args: "libLLVMSYCL.so");
870
871 for (auto [Path, Library] : Libraries) {
872 if (Args.hasFlag(Pos: options::OPT_frtlib_add_rpath,
873 Neg: options::OPT_fno_rtlib_add_rpath, Default: false)) {
874 SmallString<0> p = Path;
875 llvm::sys::path::remove_dots(path&: p, remove_dot_dot: true);
876 CmdArgs.append(IL: {"-rpath", Args.MakeArgString(Str: p)});
877 }
878
879 SmallString<0> p = Path;
880 llvm::sys::path::append(path&: p, a: Library);
881 CmdArgs.push_back(Elt: Args.MakeArgString(Str: p));
882 }
883
884 // FIXME: The ROCm builds implicitly depends on this being present.
885 if (ActiveKinds & Action::OFK_HIP)
886 CmdArgs.push_back(
887 Elt: Args.MakeArgString(Str: StringRef("-L") + RocmInstallation->getLibPath()));
888}
889
890void Linux::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
891 ArgStringList &CC1Args) const {
892 if (GCCInstallation.isValid()) {
893 CC1Args.push_back(Elt: "-isystem");
894 CC1Args.push_back(Elt: DriverArgs.MakeArgString(
895 Str: GCCInstallation.getParentLibPath() + "/../" +
896 GCCInstallation.getTriple().str() + "/include"));
897 }
898}
899
900void Linux::addSYCLIncludeArgs(const ArgList &DriverArgs,
901 ArgStringList &CC1Args) const {
902 SYCLInstallation->addSYCLIncludeArgs(DriverArgs, CC1Args);
903}
904
905bool Linux::isPIEDefault(const llvm::opt::ArgList &Args) const {
906 return CLANG_DEFAULT_PIE_ON_LINUX || getTriple().isAndroid() ||
907 getTriple().isMusl() || getSanitizerArgs(JobArgs: Args).requiresPIE();
908}
909
910bool Linux::IsAArch64OutlineAtomicsDefault(const ArgList &Args) const {
911 // Outline atomics for AArch64 are supported by compiler-rt
912 // and libgcc since 9.3.1
913 assert(getTriple().isAArch64() && "expected AArch64 target!");
914 ToolChain::RuntimeLibType RtLib = GetRuntimeLibType(Args);
915 if (RtLib == ToolChain::RLT_CompilerRT)
916 return true;
917 assert(RtLib == ToolChain::RLT_Libgcc && "unexpected runtime library type!");
918 if (GCCInstallation.getVersion().isOlderThan(RHSMajor: 9, RHSMinor: 3, RHSPatch: 1))
919 return false;
920 return true;
921}
922
923bool Linux::IsMathErrnoDefault() const {
924 if (getTriple().isAndroid() || getTriple().isMusl())
925 return false;
926 return Generic_ELF::IsMathErrnoDefault();
927}
928
929SanitizerMask Linux::getSupportedSanitizers() const {
930 const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
931 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
932 const bool IsMIPS = getTriple().isMIPS32();
933 const bool IsMIPS64 = getTriple().isMIPS64();
934 const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
935 getTriple().getArch() == llvm::Triple::ppc64le;
936 const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
937 getTriple().getArch() == llvm::Triple::aarch64_be;
938 const bool IsArmArch = getTriple().getArch() == llvm::Triple::arm ||
939 getTriple().getArch() == llvm::Triple::thumb ||
940 getTriple().getArch() == llvm::Triple::armeb ||
941 getTriple().getArch() == llvm::Triple::thumbeb;
942 const bool IsLoongArch64 = getTriple().getArch() == llvm::Triple::loongarch64;
943 const bool IsRISCV64 = getTriple().isRISCV64();
944 const bool IsSystemZ = getTriple().getArch() == llvm::Triple::systemz;
945 const bool IsHexagon = getTriple().getArch() == llvm::Triple::hexagon;
946 const bool IsAndroid = getTriple().isAndroid();
947 SanitizerMask Res = ToolChain::getSupportedSanitizers();
948 Res |= SanitizerKind::Address;
949 Res |= SanitizerKind::PointerCompare;
950 Res |= SanitizerKind::PointerSubtract;
951 Res |= SanitizerKind::Realtime;
952 Res |= SanitizerKind::Fuzzer;
953 Res |= SanitizerKind::FuzzerNoLink;
954 Res |= SanitizerKind::KernelAddress;
955 Res |= SanitizerKind::Vptr;
956 Res |= SanitizerKind::SafeStack;
957 if (IsX86_64 || IsMIPS64 || IsAArch64 || IsLoongArch64 || IsSystemZ)
958 Res |= SanitizerKind::DataFlow;
959 if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsArmArch || IsPowerPC64 ||
960 IsRISCV64 || IsSystemZ || IsHexagon || IsLoongArch64)
961 Res |= SanitizerKind::Leak;
962 if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64 || IsSystemZ ||
963 IsLoongArch64 || IsRISCV64)
964 Res |= SanitizerKind::Thread;
965 if (IsX86_64 || IsAArch64 || IsSystemZ)
966 Res |= SanitizerKind::Type;
967 if (IsX86_64 || IsSystemZ || IsPowerPC64)
968 Res |= SanitizerKind::KernelMemory;
969 if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsMIPS || IsArmArch ||
970 IsPowerPC64 || IsHexagon || IsLoongArch64 || IsRISCV64 || IsSystemZ)
971 Res |= SanitizerKind::Scudo;
972 if (IsX86_64 || IsAArch64 || IsRISCV64) {
973 Res |= SanitizerKind::HWAddress;
974 }
975 if (IsX86_64 || IsAArch64) {
976 Res |= SanitizerKind::KernelHWAddress;
977 }
978 if (IsX86_64)
979 Res |= SanitizerKind::NumericalStability;
980 if (!IsAndroid)
981 Res |= SanitizerKind::Memory;
982
983 // Work around "Cannot represent a difference across sections".
984 if (getTriple().getArch() == llvm::Triple::ppc64)
985 Res &= ~SanitizerKind::Function;
986 return Res;
987}
988
989void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args,
990 llvm::opt::ArgStringList &CmdArgs) const {
991 // Add linker option -u__llvm_profile_runtime to cause runtime
992 // initialization module to be linked in.
993 if (needsProfileRT(Args))
994 CmdArgs.push_back(Elt: Args.MakeArgString(
995 Str: Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
996 ToolChain::addProfileRTLibs(Args, CmdArgs);
997}
998
999void Linux::addExtraOpts(llvm::opt::ArgStringList &CmdArgs) const {
1000 for (const auto &Opt : ExtraOpts)
1001 CmdArgs.push_back(Elt: Opt.c_str());
1002}
1003
1004const char *Linux::getDefaultLinker() const {
1005 if (getTriple().isAndroid())
1006 return "ld.lld";
1007 return Generic_ELF::getDefaultLinker();
1008}
1009