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 "CommonArgs.h"
16 #include "clang/Config/config.h"
17 #include "clang/Driver/Distro.h"
18 #include "clang/Driver/Driver.h"
19 #include "clang/Driver/Options.h"
20 #include "clang/Driver/SanitizerArgs.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 #include <system_error>
27
28 using namespace clang::driver;
29 using namespace clang::driver::toolchains;
30 using namespace clang;
31 using namespace llvm::opt;
32
33 using tools::addPathIfExists;
34
35 /// Get our best guess at the multiarch triple for a target.
36 ///
37 /// Debian-based systems are starting to use a multiarch setup where they use
38 /// a target-triple directory in the library and header search paths.
39 /// Unfortunately, this triple does not align with the vanilla target triple,
40 /// so we provide a rough mapping here.
getMultiarchTriple(const Driver & D,const llvm::Triple & TargetTriple,StringRef SysRoot) const41 std::string Linux::getMultiarchTriple(const Driver &D,
42 const llvm::Triple &TargetTriple,
43 StringRef SysRoot) const {
44 llvm::Triple::EnvironmentType TargetEnvironment =
45 TargetTriple.getEnvironment();
46 bool IsAndroid = TargetTriple.isAndroid();
47 bool IsMipsR6 = TargetTriple.getSubArch() == llvm::Triple::MipsSubArch_r6;
48 bool IsMipsN32Abi = TargetTriple.getEnvironment() == llvm::Triple::GNUABIN32;
49
50 // For most architectures, just use whatever we have rather than trying to be
51 // clever.
52 switch (TargetTriple.getArch()) {
53 default:
54 break;
55
56 // We use the existence of '/lib/<triple>' as a directory to detect some
57 // common linux triples that don't quite match the Clang triple for both
58 // 32-bit and 64-bit targets. Multiarch fixes its install triples to these
59 // regardless of what the actual target triple is.
60 case llvm::Triple::arm:
61 case llvm::Triple::thumb:
62 if (IsAndroid)
63 return "arm-linux-androideabi";
64 if (TargetEnvironment == llvm::Triple::GNUEABIHF ||
65 TargetEnvironment == llvm::Triple::MuslEABIHF ||
66 TargetEnvironment == llvm::Triple::EABIHF)
67 return "arm-linux-gnueabihf";
68 return "arm-linux-gnueabi";
69 case llvm::Triple::armeb:
70 case llvm::Triple::thumbeb:
71 if (TargetEnvironment == llvm::Triple::GNUEABIHF ||
72 TargetEnvironment == llvm::Triple::MuslEABIHF ||
73 TargetEnvironment == llvm::Triple::EABIHF)
74 return "armeb-linux-gnueabihf";
75 return "armeb-linux-gnueabi";
76 case llvm::Triple::x86:
77 if (IsAndroid)
78 return "i686-linux-android";
79 return "i386-linux-gnu";
80 case llvm::Triple::x86_64:
81 if (IsAndroid)
82 return "x86_64-linux-android";
83 if (TargetEnvironment == llvm::Triple::GNUX32)
84 return "x86_64-linux-gnux32";
85 return "x86_64-linux-gnu";
86 case llvm::Triple::aarch64:
87 if (IsAndroid)
88 return "aarch64-linux-android";
89 if (hasEffectiveTriple() &&
90 getEffectiveTriple().getEnvironment() == llvm::Triple::PAuthTest)
91 return "aarch64-linux-pauthtest";
92 return "aarch64-linux-gnu";
93 case llvm::Triple::aarch64_be:
94 return "aarch64_be-linux-gnu";
95
96 case llvm::Triple::loongarch64: {
97 const char *Libc;
98 const char *FPFlavor;
99
100 if (TargetTriple.isGNUEnvironment()) {
101 Libc = "gnu";
102 } else if (TargetTriple.isMusl()) {
103 Libc = "musl";
104 } else {
105 return TargetTriple.str();
106 }
107
108 switch (TargetEnvironment) {
109 default:
110 return TargetTriple.str();
111 case llvm::Triple::GNUSF:
112 FPFlavor = "sf";
113 break;
114 case llvm::Triple::GNUF32:
115 FPFlavor = "f32";
116 break;
117 case llvm::Triple::GNU:
118 case llvm::Triple::GNUF64:
119 // This was going to be "f64" in an earlier Toolchain Conventions
120 // revision, but starting from Feb 2023 the F64 ABI variants are
121 // unmarked in their canonical forms.
122 FPFlavor = "";
123 break;
124 }
125
126 return (Twine("loongarch64-linux-") + Libc + FPFlavor).str();
127 }
128
129 case llvm::Triple::m68k:
130 return "m68k-linux-gnu";
131
132 case llvm::Triple::mips:
133 return IsMipsR6 ? "mipsisa32r6-linux-gnu" : "mips-linux-gnu";
134 case llvm::Triple::mipsel:
135 return IsMipsR6 ? "mipsisa32r6el-linux-gnu" : "mipsel-linux-gnu";
136 case llvm::Triple::mips64: {
137 std::string MT = std::string(IsMipsR6 ? "mipsisa64r6" : "mips64") +
138 "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
139 if (D.getVFS().exists(concat(SysRoot, "/lib", MT)))
140 return MT;
141 if (D.getVFS().exists(concat(SysRoot, "/lib/mips64-linux-gnu")))
142 return "mips64-linux-gnu";
143 break;
144 }
145 case llvm::Triple::mips64el: {
146 std::string MT = std::string(IsMipsR6 ? "mipsisa64r6el" : "mips64el") +
147 "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
148 if (D.getVFS().exists(concat(SysRoot, "/lib", MT)))
149 return MT;
150 if (D.getVFS().exists(concat(SysRoot, "/lib/mips64el-linux-gnu")))
151 return "mips64el-linux-gnu";
152 break;
153 }
154 case llvm::Triple::ppc:
155 if (D.getVFS().exists(concat(SysRoot, "/lib/powerpc-linux-gnuspe")))
156 return "powerpc-linux-gnuspe";
157 return "powerpc-linux-gnu";
158 case llvm::Triple::ppcle:
159 return "powerpcle-linux-gnu";
160 case llvm::Triple::ppc64:
161 return "powerpc64-linux-gnu";
162 case llvm::Triple::ppc64le:
163 return "powerpc64le-linux-gnu";
164 case llvm::Triple::riscv64:
165 if (IsAndroid)
166 return "riscv64-linux-android";
167 return "riscv64-linux-gnu";
168 case llvm::Triple::sparc:
169 return "sparc-linux-gnu";
170 case llvm::Triple::sparcv9:
171 return "sparc64-linux-gnu";
172 case llvm::Triple::systemz:
173 return "s390x-linux-gnu";
174 }
175 return TargetTriple.str();
176 }
177
getOSLibDir(const llvm::Triple & Triple,const ArgList & Args)178 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
179 if (Triple.isMIPS()) {
180 if (Triple.isAndroid()) {
181 StringRef CPUName;
182 StringRef ABIName;
183 tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
184 if (CPUName == "mips32r6")
185 return "libr6";
186 if (CPUName == "mips32r2")
187 return "libr2";
188 }
189 // lib32 directory has a special meaning on MIPS targets.
190 // It contains N32 ABI binaries. Use this folder if produce
191 // code for N32 ABI only.
192 if (tools::mips::hasMipsAbiArg(Args, "n32"))
193 return "lib32";
194 return Triple.isArch32Bit() ? "lib" : "lib64";
195 }
196
197 // It happens that only x86, PPC and SPARC use the 'lib32' variant of
198 // oslibdir, and using that variant while targeting other architectures causes
199 // problems because the libraries are laid out in shared system roots that
200 // can't cope with a 'lib32' library search path being considered. So we only
201 // enable them when we know we may need it.
202 //
203 // FIXME: This is a bit of a hack. We should really unify this code for
204 // reasoning about oslibdir spellings with the lib dir spellings in the
205 // GCCInstallationDetector, but that is a more significant refactoring.
206 if (Triple.getArch() == llvm::Triple::x86 || Triple.isPPC32() ||
207 Triple.getArch() == llvm::Triple::sparc)
208 return "lib32";
209
210 if (Triple.getArch() == llvm::Triple::x86_64 && Triple.isX32())
211 return "libx32";
212
213 if (Triple.getArch() == llvm::Triple::riscv32)
214 return "lib32";
215
216 return Triple.isArch32Bit() ? "lib" : "lib64";
217 }
218
Linux(const Driver & D,const llvm::Triple & Triple,const ArgList & Args)219 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
220 : Generic_ELF(D, Triple, Args) {
221 GCCInstallation.init(Triple, Args);
222 Multilibs = GCCInstallation.getMultilibs();
223 SelectedMultilibs.assign({GCCInstallation.getMultilib()});
224 llvm::Triple::ArchType Arch = Triple.getArch();
225 std::string SysRoot = computeSysRoot();
226 ToolChain::path_list &PPaths = getProgramPaths();
227
228 Generic_GCC::PushPPaths(PPaths);
229
230 Distro Distro(D.getVFS(), Triple);
231
232 if (Distro.IsAlpineLinux() || Triple.isAndroid()) {
233 ExtraOpts.push_back("-z");
234 ExtraOpts.push_back("now");
235 }
236
237 if (Distro.IsOpenSUSE() || Distro.IsUbuntu() || Distro.IsAlpineLinux() ||
238 Triple.isAndroid()) {
239 ExtraOpts.push_back("-z");
240 ExtraOpts.push_back("relro");
241 }
242
243 // Note, lld from 11 onwards default max-page-size to 65536 for both ARM and
244 // AArch64.
245 if (Triple.isAndroid()) {
246 if (Triple.isARM()) {
247 // Android ARM uses max-page-size=4096 to reduce VMA usage.
248 ExtraOpts.push_back("-z");
249 ExtraOpts.push_back("max-page-size=4096");
250 } else if (Triple.isAArch64() || Triple.getArch() == llvm::Triple::x86_64) {
251 // Android AArch64 uses max-page-size=16384 to support 4k/16k page sizes.
252 // Android emulates a 16k page size for app testing on x86_64 machines.
253 ExtraOpts.push_back("-z");
254 ExtraOpts.push_back("max-page-size=16384");
255 }
256 }
257
258 if (GCCInstallation.getParentLibPath().contains("opt/rh/"))
259 // With devtoolset on RHEL, we want to add a bin directory that is relative
260 // to the detected gcc install, because if we are using devtoolset gcc then
261 // we want to use other tools from devtoolset (e.g. ld) instead of the
262 // standard system tools.
263 PPaths.push_back(Twine(GCCInstallation.getParentLibPath() +
264 "/../bin").str());
265
266 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
267 ExtraOpts.push_back("-X");
268
269 const bool IsAndroid = Triple.isAndroid();
270 const bool IsMips = Triple.isMIPS();
271 const bool IsHexagon = Arch == llvm::Triple::hexagon;
272 const bool IsRISCV = Triple.isRISCV();
273 const bool IsCSKY = Triple.isCSKY();
274
275 if (IsCSKY && !SelectedMultilibs.empty())
276 SysRoot = SysRoot + SelectedMultilibs.back().osSuffix();
277
278 if ((IsMips || IsCSKY) && !SysRoot.empty())
279 ExtraOpts.push_back("--sysroot=" + SysRoot);
280
281 // Do not use 'gnu' hash style for Mips targets because .gnu.hash
282 // and the MIPS ABI require .dynsym to be sorted in different ways.
283 // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
284 // ABI requires a mapping between the GOT and the symbol table.
285 // Android loader does not support .gnu.hash until API 23.
286 // Hexagon linker/loader does not support .gnu.hash
287 if (!IsMips && !IsHexagon) {
288 if (Distro.IsOpenSUSE() || Distro == Distro::UbuntuLucid ||
289 Distro == Distro::UbuntuJaunty || Distro == Distro::UbuntuKarmic ||
290 (IsAndroid && Triple.isAndroidVersionLT(23)))
291 ExtraOpts.push_back("--hash-style=both");
292 else
293 ExtraOpts.push_back("--hash-style=gnu");
294 }
295
296 #ifdef ENABLE_LINKER_BUILD_ID
297 ExtraOpts.push_back("--build-id");
298 #endif
299
300 // The selection of paths to try here is designed to match the patterns which
301 // the GCC driver itself uses, as this is part of the GCC-compatible driver.
302 // This was determined by running GCC in a fake filesystem, creating all
303 // possible permutations of these directories, and seeing which ones it added
304 // to the link paths.
305 path_list &Paths = getFilePaths();
306
307 const std::string OSLibDir = std::string(getOSLibDir(Triple, Args));
308 const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot);
309
310 // mips32: Debian multilib, we use /libo32, while in other case, /lib is
311 // used. We need add both libo32 and /lib.
312 if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel) {
313 Generic_GCC::AddMultilibPaths(D, SysRoot, "libo32", MultiarchTriple, Paths);
314 addPathIfExists(D, concat(SysRoot, "/libo32"), Paths);
315 addPathIfExists(D, concat(SysRoot, "/usr/libo32"), Paths);
316 }
317 Generic_GCC::AddMultilibPaths(D, SysRoot, OSLibDir, MultiarchTriple, Paths);
318
319 addPathIfExists(D, concat(SysRoot, "/lib", MultiarchTriple), Paths);
320 addPathIfExists(D, concat(SysRoot, "/lib/..", OSLibDir), Paths);
321
322 if (IsAndroid) {
323 // Android sysroots contain a library directory for each supported OS
324 // version as well as some unversioned libraries in the usual multiarch
325 // directory.
326 addPathIfExists(
327 D,
328 concat(SysRoot, "/usr/lib", MultiarchTriple,
329 llvm::to_string(Triple.getEnvironmentVersion().getMajor())),
330 Paths);
331 }
332
333 addPathIfExists(D, concat(SysRoot, "/usr/lib", MultiarchTriple), Paths);
334 // 64-bit OpenEmbedded sysroots may not have a /usr/lib dir. So they cannot
335 // find /usr/lib64 as it is referenced as /usr/lib/../lib64. So we handle
336 // this here.
337 if (Triple.getVendor() == llvm::Triple::OpenEmbedded &&
338 Triple.isArch64Bit())
339 addPathIfExists(D, concat(SysRoot, "/usr", OSLibDir), Paths);
340 else
341 addPathIfExists(D, concat(SysRoot, "/usr/lib/..", OSLibDir), Paths);
342 if (IsRISCV) {
343 StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
344 addPathIfExists(D, concat(SysRoot, "/", OSLibDir, ABIName), Paths);
345 addPathIfExists(D, concat(SysRoot, "/usr", OSLibDir, ABIName), Paths);
346 }
347
348 Generic_GCC::AddMultiarchPaths(D, SysRoot, OSLibDir, Paths);
349
350 addPathIfExists(D, concat(SysRoot, "/lib"), Paths);
351 addPathIfExists(D, concat(SysRoot, "/usr/lib"), Paths);
352 }
353
GetDefaultRuntimeLibType() const354 ToolChain::RuntimeLibType Linux::GetDefaultRuntimeLibType() const {
355 if (getTriple().isAndroid())
356 return ToolChain::RLT_CompilerRT;
357 return Generic_ELF::GetDefaultRuntimeLibType();
358 }
359
GetDefaultDwarfVersion() const360 unsigned Linux::GetDefaultDwarfVersion() const {
361 if (getTriple().isAndroid())
362 return 4;
363 return ToolChain::GetDefaultDwarfVersion();
364 }
365
GetDefaultCXXStdlibType() const366 ToolChain::CXXStdlibType Linux::GetDefaultCXXStdlibType() const {
367 if (getTriple().isAndroid())
368 return ToolChain::CST_Libcxx;
369 return ToolChain::CST_Libstdcxx;
370 }
371
HasNativeLLVMSupport() const372 bool Linux::HasNativeLLVMSupport() const { return true; }
373
buildLinker() const374 Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
375
buildStaticLibTool() const376 Tool *Linux::buildStaticLibTool() const {
377 return new tools::gnutools::StaticLibTool(*this);
378 }
379
buildAssembler() const380 Tool *Linux::buildAssembler() const {
381 return new tools::gnutools::Assembler(*this);
382 }
383
computeSysRoot() const384 std::string Linux::computeSysRoot() const {
385 if (!getDriver().SysRoot.empty())
386 return getDriver().SysRoot;
387
388 if (getTriple().isAndroid()) {
389 // Android toolchains typically include a sysroot at ../sysroot relative to
390 // the clang binary.
391 const StringRef ClangDir = getDriver().Dir;
392 std::string AndroidSysRootPath = (ClangDir + "/../sysroot").str();
393 if (getVFS().exists(AndroidSysRootPath))
394 return AndroidSysRootPath;
395 }
396
397 if (getTriple().isCSKY()) {
398 // CSKY toolchains use different names for sysroot folder.
399 if (!GCCInstallation.isValid())
400 return std::string();
401 // GCCInstallation.getInstallPath() =
402 // $GCCToolchainPath/lib/gcc/csky-linux-gnuabiv2/6.3.0
403 // Path = $GCCToolchainPath/csky-linux-gnuabiv2/libc
404 std::string Path = (GCCInstallation.getInstallPath() + "/../../../../" +
405 GCCInstallation.getTriple().str() + "/libc")
406 .str();
407 if (getVFS().exists(Path))
408 return Path;
409 return std::string();
410 }
411
412 if (!GCCInstallation.isValid() || !getTriple().isMIPS())
413 return std::string();
414
415 // Standalone MIPS toolchains use different names for sysroot folder
416 // and put it into different places. Here we try to check some known
417 // variants.
418
419 const StringRef InstallDir = GCCInstallation.getInstallPath();
420 const StringRef TripleStr = GCCInstallation.getTriple().str();
421 const Multilib &Multilib = GCCInstallation.getMultilib();
422
423 std::string Path =
424 (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
425 .str();
426
427 if (getVFS().exists(Path))
428 return Path;
429
430 Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
431
432 if (getVFS().exists(Path))
433 return Path;
434
435 return std::string();
436 }
437
getDynamicLinker(const ArgList & Args) const438 std::string Linux::getDynamicLinker(const ArgList &Args) const {
439 const llvm::Triple::ArchType Arch = getArch();
440 const llvm::Triple &Triple = getTriple();
441
442 const Distro Distro(getDriver().getVFS(), Triple);
443
444 if (Triple.isAndroid()) {
445 if (getSanitizerArgs(Args).needsHwasanRt() &&
446 !Triple.isAndroidVersionLT(34) && Triple.isArch64Bit()) {
447 // On Android 14 and newer, there is a special linker_hwasan64 that
448 // allows to run HWASan binaries on non-HWASan system images. This
449 // is also available on HWASan system images, so we can just always
450 // use that instead.
451 return "/system/bin/linker_hwasan64";
452 }
453 return Triple.isArch64Bit() ? "/system/bin/linker64" : "/system/bin/linker";
454 }
455 if (Triple.isMusl()) {
456 std::string ArchName;
457 bool IsArm = false;
458
459 switch (Arch) {
460 case llvm::Triple::arm:
461 case llvm::Triple::thumb:
462 ArchName = "arm";
463 IsArm = true;
464 break;
465 case llvm::Triple::armeb:
466 case llvm::Triple::thumbeb:
467 ArchName = "armeb";
468 IsArm = true;
469 break;
470 case llvm::Triple::x86:
471 ArchName = "i386";
472 break;
473 case llvm::Triple::x86_64:
474 ArchName = Triple.isX32() ? "x32" : Triple.getArchName().str();
475 break;
476 default:
477 ArchName = Triple.getArchName().str();
478 }
479 if (IsArm &&
480 (Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
481 tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard))
482 ArchName += "hf";
483 if (Arch == llvm::Triple::ppc &&
484 Triple.getSubArch() == llvm::Triple::PPCSubArch_spe)
485 ArchName = "powerpc-sf";
486
487 return "/lib/ld-musl-" + ArchName + ".so.1";
488 }
489
490 std::string LibDir;
491 std::string Loader;
492
493 switch (Arch) {
494 default:
495 llvm_unreachable("unsupported architecture");
496
497 case llvm::Triple::aarch64:
498 LibDir = "lib";
499 Loader = "ld-linux-aarch64.so.1";
500 break;
501 case llvm::Triple::aarch64_be:
502 LibDir = "lib";
503 Loader = "ld-linux-aarch64_be.so.1";
504 break;
505 case llvm::Triple::arm:
506 case llvm::Triple::thumb:
507 case llvm::Triple::armeb:
508 case llvm::Triple::thumbeb: {
509 const bool HF =
510 Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
511 Triple.getEnvironment() == llvm::Triple::GNUEABIHFT64 ||
512 tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard;
513
514 LibDir = "lib";
515 Loader = HF ? "ld-linux-armhf.so.3" : "ld-linux.so.3";
516 break;
517 }
518 case llvm::Triple::loongarch32: {
519 LibDir = "lib32";
520 Loader =
521 ("ld-linux-loongarch-" +
522 tools::loongarch::getLoongArchABI(getDriver(), Args, Triple) + ".so.1")
523 .str();
524 break;
525 }
526 case llvm::Triple::loongarch64: {
527 LibDir = "lib64";
528 Loader =
529 ("ld-linux-loongarch-" +
530 tools::loongarch::getLoongArchABI(getDriver(), Args, Triple) + ".so.1")
531 .str();
532 break;
533 }
534 case llvm::Triple::m68k:
535 LibDir = "lib";
536 Loader = "ld.so.1";
537 break;
538 case llvm::Triple::mips:
539 case llvm::Triple::mipsel:
540 case llvm::Triple::mips64:
541 case llvm::Triple::mips64el: {
542 bool IsNaN2008 = tools::mips::isNaN2008(getDriver(), Args, Triple);
543
544 LibDir = "lib" + tools::mips::getMipsABILibSuffix(Args, Triple);
545
546 if (tools::mips::isUCLibc(Args))
547 Loader = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
548 else if (!Triple.hasEnvironment() &&
549 Triple.getVendor() == llvm::Triple::VendorType::MipsTechnologies)
550 Loader =
551 Triple.isLittleEndian() ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
552 else
553 Loader = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
554
555 break;
556 }
557 case llvm::Triple::ppc:
558 LibDir = "lib";
559 Loader = "ld.so.1";
560 break;
561 case llvm::Triple::ppcle:
562 LibDir = "lib";
563 Loader = "ld.so.1";
564 break;
565 case llvm::Triple::ppc64:
566 LibDir = "lib64";
567 Loader =
568 (tools::ppc::hasPPCAbiArg(Args, "elfv2")) ? "ld64.so.2" : "ld64.so.1";
569 break;
570 case llvm::Triple::ppc64le:
571 LibDir = "lib64";
572 Loader =
573 (tools::ppc::hasPPCAbiArg(Args, "elfv1")) ? "ld64.so.1" : "ld64.so.2";
574 break;
575 case llvm::Triple::riscv32:
576 case llvm::Triple::riscv64: {
577 StringRef ArchName = llvm::Triple::getArchTypeName(Arch);
578 StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
579 LibDir = "lib";
580 Loader = ("ld-linux-" + ArchName + "-" + ABIName + ".so.1").str();
581 break;
582 }
583 case llvm::Triple::sparc:
584 case llvm::Triple::sparcel:
585 LibDir = "lib";
586 Loader = "ld-linux.so.2";
587 break;
588 case llvm::Triple::sparcv9:
589 LibDir = "lib64";
590 Loader = "ld-linux.so.2";
591 break;
592 case llvm::Triple::systemz:
593 LibDir = "lib";
594 Loader = "ld64.so.1";
595 break;
596 case llvm::Triple::x86:
597 LibDir = "lib";
598 Loader = "ld-linux.so.2";
599 break;
600 case llvm::Triple::x86_64: {
601 bool X32 = Triple.isX32();
602
603 LibDir = X32 ? "libx32" : "lib64";
604 Loader = X32 ? "ld-linux-x32.so.2" : "ld-linux-x86-64.so.2";
605 break;
606 }
607 case llvm::Triple::ve:
608 return "/opt/nec/ve/lib/ld-linux-ve.so.1";
609 case llvm::Triple::csky: {
610 LibDir = "lib";
611 Loader = "ld.so.1";
612 break;
613 }
614 }
615
616 if (Distro == Distro::Exherbo &&
617 (Triple.getVendor() == llvm::Triple::UnknownVendor ||
618 Triple.getVendor() == llvm::Triple::PC))
619 return "/usr/" + Triple.str() + "/lib/" + Loader;
620 return "/" + LibDir + "/" + Loader;
621 }
622
AddClangSystemIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const623 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
624 ArgStringList &CC1Args) const {
625 const Driver &D = getDriver();
626 std::string SysRoot = computeSysRoot();
627
628 if (DriverArgs.hasArg(clang::driver::options::OPT_nostdinc))
629 return;
630
631 // Add 'include' in the resource directory, which is similar to
632 // GCC_INCLUDE_DIR (private headers) in GCC. Note: the include directory
633 // contains some files conflicting with system /usr/include. musl systems
634 // prefer the /usr/include copies which are more relevant.
635 SmallString<128> ResourceDirInclude(D.ResourceDir);
636 llvm::sys::path::append(ResourceDirInclude, "include");
637 if (!DriverArgs.hasArg(options::OPT_nobuiltininc) &&
638 (!getTriple().isMusl() || DriverArgs.hasArg(options::OPT_nostdlibinc)))
639 addSystemInclude(DriverArgs, CC1Args, ResourceDirInclude);
640
641 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
642 return;
643
644 // LOCAL_INCLUDE_DIR
645 addSystemInclude(DriverArgs, CC1Args, concat(SysRoot, "/usr/local/include"));
646 // TOOL_INCLUDE_DIR
647 AddMultilibIncludeArgs(DriverArgs, CC1Args);
648
649 // Check for configure-time C include directories.
650 StringRef CIncludeDirs(C_INCLUDE_DIRS);
651 if (CIncludeDirs != "") {
652 SmallVector<StringRef, 5> dirs;
653 CIncludeDirs.split(dirs, ":");
654 for (StringRef dir : dirs) {
655 StringRef Prefix =
656 llvm::sys::path::is_absolute(dir) ? "" : StringRef(SysRoot);
657 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
658 }
659 return;
660 }
661
662 // On systems using multiarch and Android, add /usr/include/$triple before
663 // /usr/include.
664 std::string MultiarchIncludeDir = getMultiarchTriple(D, getTriple(), SysRoot);
665 if (!MultiarchIncludeDir.empty() &&
666 D.getVFS().exists(concat(SysRoot, "/usr/include", MultiarchIncludeDir)))
667 addExternCSystemInclude(
668 DriverArgs, CC1Args,
669 concat(SysRoot, "/usr/include", MultiarchIncludeDir));
670
671 if (getTriple().getOS() == llvm::Triple::RTEMS)
672 return;
673
674 // Add an include of '/include' directly. This isn't provided by default by
675 // system GCCs, but is often used with cross-compiling GCCs, and harmless to
676 // add even when Clang is acting as-if it were a system compiler.
677 addExternCSystemInclude(DriverArgs, CC1Args, concat(SysRoot, "/include"));
678
679 addExternCSystemInclude(DriverArgs, CC1Args, concat(SysRoot, "/usr/include"));
680
681 if (!DriverArgs.hasArg(options::OPT_nobuiltininc) && getTriple().isMusl())
682 addSystemInclude(DriverArgs, CC1Args, ResourceDirInclude);
683 }
684
addLibStdCxxIncludePaths(const llvm::opt::ArgList & DriverArgs,llvm::opt::ArgStringList & CC1Args) const685 void Linux::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
686 llvm::opt::ArgStringList &CC1Args) const {
687 // We need a detected GCC installation on Linux to provide libstdc++'s
688 // headers in odd Linuxish places.
689 if (!GCCInstallation.isValid())
690 return;
691
692 // Detect Debian g++-multiarch-incdir.diff.
693 StringRef TripleStr = GCCInstallation.getTriple().str();
694 StringRef DebianMultiarch =
695 GCCInstallation.getTriple().getArch() == llvm::Triple::x86
696 ? "i386-linux-gnu"
697 : TripleStr;
698
699 // Try generic GCC detection first.
700 if (Generic_GCC::addGCCLibStdCxxIncludePaths(DriverArgs, CC1Args,
701 DebianMultiarch))
702 return;
703
704 StringRef LibDir = GCCInstallation.getParentLibPath();
705 const Multilib &Multilib = GCCInstallation.getMultilib();
706 const GCCVersion &Version = GCCInstallation.getVersion();
707
708 const std::string LibStdCXXIncludePathCandidates[] = {
709 // Android standalone toolchain has C++ headers in yet another place.
710 LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
711 // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
712 // without a subdirectory corresponding to the gcc version.
713 LibDir.str() + "/../include/c++",
714 // Cray's gcc installation puts headers under "g++" without a
715 // version suffix.
716 LibDir.str() + "/../include/g++",
717 };
718
719 for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
720 if (addLibStdCXXIncludePaths(IncludePath, TripleStr,
721 Multilib.includeSuffix(), DriverArgs, CC1Args))
722 break;
723 }
724 }
725
AddCudaIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const726 void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs,
727 ArgStringList &CC1Args) const {
728 CudaInstallation->AddCudaIncludeArgs(DriverArgs, CC1Args);
729 }
730
AddHIPIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const731 void Linux::AddHIPIncludeArgs(const ArgList &DriverArgs,
732 ArgStringList &CC1Args) const {
733 RocmInstallation->AddHIPIncludeArgs(DriverArgs, CC1Args);
734 }
735
AddHIPRuntimeLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const736 void Linux::AddHIPRuntimeLibArgs(const ArgList &Args,
737 ArgStringList &CmdArgs) const {
738 CmdArgs.push_back(
739 Args.MakeArgString(StringRef("-L") + RocmInstallation->getLibPath()));
740
741 if (Args.hasFlag(options::OPT_frtlib_add_rpath,
742 options::OPT_fno_rtlib_add_rpath, false))
743 CmdArgs.append(
744 {"-rpath", Args.MakeArgString(RocmInstallation->getLibPath())});
745
746 CmdArgs.push_back("-lamdhip64");
747 }
748
AddIAMCUIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const749 void Linux::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
750 ArgStringList &CC1Args) const {
751 if (GCCInstallation.isValid()) {
752 CC1Args.push_back("-isystem");
753 CC1Args.push_back(DriverArgs.MakeArgString(
754 GCCInstallation.getParentLibPath() + "/../" +
755 GCCInstallation.getTriple().str() + "/include"));
756 }
757 }
758
isPIEDefault(const llvm::opt::ArgList & Args) const759 bool Linux::isPIEDefault(const llvm::opt::ArgList &Args) const {
760 return CLANG_DEFAULT_PIE_ON_LINUX || getTriple().isAndroid() ||
761 getTriple().isMusl() || getSanitizerArgs(Args).requiresPIE();
762 }
763
IsAArch64OutlineAtomicsDefault(const ArgList & Args) const764 bool Linux::IsAArch64OutlineAtomicsDefault(const ArgList &Args) const {
765 // Outline atomics for AArch64 are supported by compiler-rt
766 // and libgcc since 9.3.1
767 assert(getTriple().isAArch64() && "expected AArch64 target!");
768 ToolChain::RuntimeLibType RtLib = GetRuntimeLibType(Args);
769 if (RtLib == ToolChain::RLT_CompilerRT)
770 return true;
771 assert(RtLib == ToolChain::RLT_Libgcc && "unexpected runtime library type!");
772 if (GCCInstallation.getVersion().isOlderThan(9, 3, 1))
773 return false;
774 return true;
775 }
776
IsMathErrnoDefault() const777 bool Linux::IsMathErrnoDefault() const {
778 if (getTriple().isAndroid() || getTriple().isMusl())
779 return false;
780 return Generic_ELF::IsMathErrnoDefault();
781 }
782
getSupportedSanitizers() const783 SanitizerMask Linux::getSupportedSanitizers() const {
784 const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
785 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
786 const bool IsMIPS = getTriple().isMIPS32();
787 const bool IsMIPS64 = getTriple().isMIPS64();
788 const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
789 getTriple().getArch() == llvm::Triple::ppc64le;
790 const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
791 getTriple().getArch() == llvm::Triple::aarch64_be;
792 const bool IsArmArch = getTriple().getArch() == llvm::Triple::arm ||
793 getTriple().getArch() == llvm::Triple::thumb ||
794 getTriple().getArch() == llvm::Triple::armeb ||
795 getTriple().getArch() == llvm::Triple::thumbeb;
796 const bool IsLoongArch64 = getTriple().getArch() == llvm::Triple::loongarch64;
797 const bool IsRISCV64 = getTriple().getArch() == llvm::Triple::riscv64;
798 const bool IsSystemZ = getTriple().getArch() == llvm::Triple::systemz;
799 const bool IsHexagon = getTriple().getArch() == llvm::Triple::hexagon;
800 SanitizerMask Res = ToolChain::getSupportedSanitizers();
801 Res |= SanitizerKind::Address;
802 Res |= SanitizerKind::PointerCompare;
803 Res |= SanitizerKind::PointerSubtract;
804 Res |= SanitizerKind::Fuzzer;
805 Res |= SanitizerKind::FuzzerNoLink;
806 Res |= SanitizerKind::KernelAddress;
807 Res |= SanitizerKind::Memory;
808 Res |= SanitizerKind::Vptr;
809 Res |= SanitizerKind::SafeStack;
810 if (IsX86_64 || IsMIPS64 || IsAArch64 || IsLoongArch64)
811 Res |= SanitizerKind::DataFlow;
812 if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsArmArch || IsPowerPC64 ||
813 IsRISCV64 || IsSystemZ || IsHexagon || IsLoongArch64)
814 Res |= SanitizerKind::Leak;
815 if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64 || IsSystemZ ||
816 IsLoongArch64 || IsRISCV64)
817 Res |= SanitizerKind::Thread;
818 if (IsX86_64 || IsSystemZ || IsPowerPC64)
819 Res |= SanitizerKind::KernelMemory;
820 if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsMIPS || IsArmArch ||
821 IsPowerPC64 || IsHexagon || IsLoongArch64 || IsRISCV64)
822 Res |= SanitizerKind::Scudo;
823 if (IsX86_64 || IsAArch64 || IsRISCV64) {
824 Res |= SanitizerKind::HWAddress;
825 }
826 if (IsX86_64 || IsAArch64) {
827 Res |= SanitizerKind::KernelHWAddress;
828 }
829 if (IsX86_64)
830 Res |= SanitizerKind::NumericalStability;
831
832 // Work around "Cannot represent a difference across sections".
833 if (getTriple().getArch() == llvm::Triple::ppc64)
834 Res &= ~SanitizerKind::Function;
835 return Res;
836 }
837
addProfileRTLibs(const llvm::opt::ArgList & Args,llvm::opt::ArgStringList & CmdArgs) const838 void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args,
839 llvm::opt::ArgStringList &CmdArgs) const {
840 // Add linker option -u__llvm_profile_runtime to cause runtime
841 // initialization module to be linked in.
842 if (needsProfileRT(Args))
843 CmdArgs.push_back(Args.MakeArgString(
844 Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
845 ToolChain::addProfileRTLibs(Args, CmdArgs);
846 }
847
addExtraOpts(llvm::opt::ArgStringList & CmdArgs) const848 void Linux::addExtraOpts(llvm::opt::ArgStringList &CmdArgs) const {
849 for (const auto &Opt : ExtraOpts)
850 CmdArgs.push_back(Opt.c_str());
851 }
852
getDefaultLinker() const853 const char *Linux::getDefaultLinker() const {
854 if (getTriple().isAndroid())
855 return "ld.lld";
856 return Generic_ELF::getDefaultLinker();
857 }
858