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/Mips.h"
12 #include "Arch/PPC.h"
13 #include "Arch/RISCV.h"
14 #include "CommonArgs.h"
15 #include "clang/Config/config.h"
16 #include "clang/Driver/Distro.h"
17 #include "clang/Driver/Driver.h"
18 #include "clang/Driver/Options.h"
19 #include "clang/Driver/SanitizerArgs.h"
20 #include "llvm/Option/ArgList.h"
21 #include "llvm/ProfileData/InstrProf.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/ScopedPrinter.h"
24 #include "llvm/Support/VirtualFileSystem.h"
25 #include <system_error>
26 
27 using namespace clang::driver;
28 using namespace clang::driver::toolchains;
29 using namespace clang;
30 using namespace llvm::opt;
31 
32 using 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.
40 std::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     } else if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
64       if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabihf"))
65         return "arm-linux-gnueabihf";
66     } else {
67       if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabi"))
68         return "arm-linux-gnueabi";
69     }
70     break;
71   case llvm::Triple::armeb:
72   case llvm::Triple::thumbeb:
73     if (TargetEnvironment == llvm::Triple::GNUEABIHF) {
74       if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabihf"))
75         return "armeb-linux-gnueabihf";
76     } else {
77       if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabi"))
78         return "armeb-linux-gnueabi";
79     }
80     break;
81   case llvm::Triple::x86:
82     if (IsAndroid)
83       return "i686-linux-android";
84     if (D.getVFS().exists(SysRoot + "/lib/i386-linux-gnu"))
85       return "i386-linux-gnu";
86     break;
87   case llvm::Triple::x86_64:
88     if (IsAndroid)
89       return "x86_64-linux-android";
90     // We don't want this for x32, otherwise it will match x86_64 libs
91     if (TargetEnvironment != llvm::Triple::GNUX32 &&
92         D.getVFS().exists(SysRoot + "/lib/x86_64-linux-gnu"))
93       return "x86_64-linux-gnu";
94     break;
95   case llvm::Triple::aarch64:
96     if (IsAndroid)
97       return "aarch64-linux-android";
98     if (D.getVFS().exists(SysRoot + "/lib/aarch64-linux-gnu"))
99       return "aarch64-linux-gnu";
100     break;
101   case llvm::Triple::aarch64_be:
102     if (D.getVFS().exists(SysRoot + "/lib/aarch64_be-linux-gnu"))
103       return "aarch64_be-linux-gnu";
104     break;
105 
106   case llvm::Triple::m68k:
107     if (D.getVFS().exists(SysRoot + "/lib/m68k-linux-gnu"))
108       return "m68k-linux-gnu";
109     break;
110 
111   case llvm::Triple::mips: {
112     std::string MT = IsMipsR6 ? "mipsisa32r6-linux-gnu" : "mips-linux-gnu";
113     if (D.getVFS().exists(SysRoot + "/lib/" + MT))
114       return MT;
115     break;
116   }
117   case llvm::Triple::mipsel: {
118     if (IsAndroid)
119       return "mipsel-linux-android";
120     std::string MT = IsMipsR6 ? "mipsisa32r6el-linux-gnu" : "mipsel-linux-gnu";
121     if (D.getVFS().exists(SysRoot + "/lib/" + MT))
122       return MT;
123     break;
124   }
125   case llvm::Triple::mips64: {
126     std::string MT = std::string(IsMipsR6 ? "mipsisa64r6" : "mips64") +
127                      "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
128     if (D.getVFS().exists(SysRoot + "/lib/" + MT))
129       return MT;
130     if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnu"))
131       return "mips64-linux-gnu";
132     break;
133   }
134   case llvm::Triple::mips64el: {
135     if (IsAndroid)
136       return "mips64el-linux-android";
137     std::string MT = std::string(IsMipsR6 ? "mipsisa64r6el" : "mips64el") +
138                      "-linux-" + (IsMipsN32Abi ? "gnuabin32" : "gnuabi64");
139     if (D.getVFS().exists(SysRoot + "/lib/" + MT))
140       return MT;
141     if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnu"))
142       return "mips64el-linux-gnu";
143     break;
144   }
145   case llvm::Triple::ppc:
146     if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnuspe"))
147       return "powerpc-linux-gnuspe";
148     if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnu"))
149       return "powerpc-linux-gnu";
150     break;
151   case llvm::Triple::ppcle:
152     if (D.getVFS().exists(SysRoot + "/lib/powerpcle-linux-gnu"))
153       return "powerpcle-linux-gnu";
154     break;
155   case llvm::Triple::ppc64:
156     if (D.getVFS().exists(SysRoot + "/lib/powerpc64-linux-gnu"))
157       return "powerpc64-linux-gnu";
158     break;
159   case llvm::Triple::ppc64le:
160     if (D.getVFS().exists(SysRoot + "/lib/powerpc64le-linux-gnu"))
161       return "powerpc64le-linux-gnu";
162     break;
163   case llvm::Triple::sparc:
164     if (D.getVFS().exists(SysRoot + "/lib/sparc-linux-gnu"))
165       return "sparc-linux-gnu";
166     break;
167   case llvm::Triple::sparcv9:
168     if (D.getVFS().exists(SysRoot + "/lib/sparc64-linux-gnu"))
169       return "sparc64-linux-gnu";
170     break;
171   case llvm::Triple::systemz:
172     if (D.getVFS().exists(SysRoot + "/lib/s390x-linux-gnu"))
173       return "s390x-linux-gnu";
174     break;
175   }
176   return TargetTriple.str();
177 }
178 
179 static StringRef getOSLibDir(const llvm::Triple &Triple, const ArgList &Args) {
180   if (Triple.isMIPS()) {
181     if (Triple.isAndroid()) {
182       StringRef CPUName;
183       StringRef ABIName;
184       tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
185       if (CPUName == "mips32r6")
186         return "libr6";
187       if (CPUName == "mips32r2")
188         return "libr2";
189     }
190     // lib32 directory has a special meaning on MIPS targets.
191     // It contains N32 ABI binaries. Use this folder if produce
192     // code for N32 ABI only.
193     if (tools::mips::hasMipsAbiArg(Args, "n32"))
194       return "lib32";
195     return Triple.isArch32Bit() ? "lib" : "lib64";
196   }
197 
198   // It happens that only x86, PPC and SPARC use the 'lib32' variant of
199   // oslibdir, and using that variant while targeting other architectures causes
200   // problems because the libraries are laid out in shared system roots that
201   // can't cope with a 'lib32' library search path being considered. So we only
202   // enable them when we know we may need it.
203   //
204   // FIXME: This is a bit of a hack. We should really unify this code for
205   // reasoning about oslibdir spellings with the lib dir spellings in the
206   // GCCInstallationDetector, but that is a more significant refactoring.
207   if (Triple.getArch() == llvm::Triple::x86 || Triple.isPPC32() ||
208       Triple.getArch() == llvm::Triple::sparc)
209     return "lib32";
210 
211   if (Triple.getArch() == llvm::Triple::x86_64 &&
212       Triple.getEnvironment() == llvm::Triple::GNUX32)
213     return "libx32";
214 
215   if (Triple.getArch() == llvm::Triple::riscv32)
216     return "lib32";
217 
218   return Triple.isArch32Bit() ? "lib" : "lib64";
219 }
220 
221 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
222     : Generic_ELF(D, Triple, Args) {
223   GCCInstallation.init(Triple, Args);
224   Multilibs = GCCInstallation.getMultilibs();
225   SelectedMultilib = GCCInstallation.getMultilib();
226   llvm::Triple::ArchType Arch = Triple.getArch();
227   std::string SysRoot = computeSysRoot();
228   ToolChain::path_list &PPaths = getProgramPaths();
229 
230   Generic_GCC::PushPPaths(PPaths);
231 
232   Distro Distro(D.getVFS(), Triple);
233 
234   if (Distro.IsAlpineLinux() || Triple.isAndroid()) {
235     ExtraOpts.push_back("-z");
236     ExtraOpts.push_back("now");
237   }
238 
239   if (Distro.IsOpenSUSE() || Distro.IsUbuntu() || Distro.IsAlpineLinux() ||
240       Triple.isAndroid()) {
241     ExtraOpts.push_back("-z");
242     ExtraOpts.push_back("relro");
243   }
244 
245   // Android ARM/AArch64 use max-page-size=4096 to reduce VMA usage. Note, lld
246   // from 11 onwards default max-page-size to 65536 for both ARM and AArch64.
247   if ((Triple.isARM() || Triple.isAArch64()) && Triple.isAndroid()) {
248     ExtraOpts.push_back("-z");
249     ExtraOpts.push_back("max-page-size=4096");
250   }
251 
252   if (GCCInstallation.getParentLibPath().find("opt/rh/devtoolset") !=
253       StringRef::npos)
254     // With devtoolset on RHEL, we want to add a bin directory that is relative
255     // to the detected gcc install, because if we are using devtoolset gcc then
256     // we want to use other tools from devtoolset (e.g. ld) instead of the
257     // standard system tools.
258     PPaths.push_back(Twine(GCCInstallation.getParentLibPath() +
259                      "/../bin").str());
260 
261   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
262     ExtraOpts.push_back("-X");
263 
264   const bool IsAndroid = Triple.isAndroid();
265   const bool IsMips = Triple.isMIPS();
266   const bool IsHexagon = Arch == llvm::Triple::hexagon;
267   const bool IsRISCV = Triple.isRISCV();
268 
269   if (IsMips && !SysRoot.empty())
270     ExtraOpts.push_back("--sysroot=" + SysRoot);
271 
272   // Do not use 'gnu' hash style for Mips targets because .gnu.hash
273   // and the MIPS ABI require .dynsym to be sorted in different ways.
274   // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
275   // ABI requires a mapping between the GOT and the symbol table.
276   // Android loader does not support .gnu.hash until API 23.
277   // Hexagon linker/loader does not support .gnu.hash
278   if (!IsMips && !IsHexagon) {
279     if (Distro.IsRedhat() || Distro.IsOpenSUSE() || Distro.IsAlpineLinux() ||
280         (Distro.IsUbuntu() && Distro >= Distro::UbuntuMaverick) ||
281         (IsAndroid && !Triple.isAndroidVersionLT(23)))
282       ExtraOpts.push_back("--hash-style=gnu");
283 
284     if (Distro.IsDebian() || Distro.IsOpenSUSE() ||
285         Distro == Distro::UbuntuLucid || Distro == Distro::UbuntuJaunty ||
286         Distro == Distro::UbuntuKarmic ||
287         (IsAndroid && Triple.isAndroidVersionLT(23)))
288       ExtraOpts.push_back("--hash-style=both");
289   }
290 
291 #ifdef ENABLE_LINKER_BUILD_ID
292   ExtraOpts.push_back("--build-id");
293 #endif
294 
295   if (IsAndroid || Distro.IsOpenSUSE())
296     ExtraOpts.push_back("--enable-new-dtags");
297 
298   // The selection of paths to try here is designed to match the patterns which
299   // the GCC driver itself uses, as this is part of the GCC-compatible driver.
300   // This was determined by running GCC in a fake filesystem, creating all
301   // possible permutations of these directories, and seeing which ones it added
302   // to the link paths.
303   path_list &Paths = getFilePaths();
304 
305   const std::string OSLibDir = std::string(getOSLibDir(Triple, Args));
306   const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot);
307 
308   Generic_GCC::AddMultilibPaths(D, SysRoot, OSLibDir, MultiarchTriple, Paths);
309 
310   // Similar to the logic for GCC above, if we currently running Clang inside
311   // of the requested system root, add its parent library paths to
312   // those searched.
313   // FIXME: It's not clear whether we should use the driver's installed
314   // directory ('Dir' below) or the ResourceDir.
315   if (StringRef(D.Dir).startswith(SysRoot)) {
316     addPathIfExists(D, D.Dir + "/../lib/" + MultiarchTriple, Paths);
317     addPathIfExists(D, D.Dir + "/../" + OSLibDir, Paths);
318   }
319 
320   addPathIfExists(D, SysRoot + "/lib/" + MultiarchTriple, Paths);
321   addPathIfExists(D, SysRoot + "/lib/../" + OSLibDir, Paths);
322 
323   if (IsAndroid) {
324     // Android sysroots contain a library directory for each supported OS
325     // version as well as some unversioned libraries in the usual multiarch
326     // directory.
327     unsigned Major;
328     unsigned Minor;
329     unsigned Micro;
330     Triple.getEnvironmentVersion(Major, Minor, Micro);
331     addPathIfExists(D,
332                     SysRoot + "/usr/lib/" + MultiarchTriple + "/" +
333                         llvm::to_string(Major),
334                     Paths);
335   }
336 
337   addPathIfExists(D, SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
338   // 64-bit OpenEmbedded sysroots may not have a /usr/lib dir. So they cannot
339   // find /usr/lib64 as it is referenced as /usr/lib/../lib64. So we handle
340   // this here.
341   if (Triple.getVendor() == llvm::Triple::OpenEmbedded &&
342       Triple.isArch64Bit())
343     addPathIfExists(D, SysRoot + "/usr/" + OSLibDir, Paths);
344   else
345     addPathIfExists(D, SysRoot + "/usr/lib/../" + OSLibDir, Paths);
346   if (IsRISCV) {
347     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
348     addPathIfExists(D, SysRoot + "/" + OSLibDir + "/" + ABIName, Paths);
349     addPathIfExists(D, SysRoot + "/usr/" + OSLibDir + "/" + ABIName, Paths);
350   }
351 
352   Generic_GCC::AddMultiarchPaths(D, SysRoot, OSLibDir, Paths);
353 
354   // Similar to the logic for GCC above, if we are currently running Clang
355   // inside of the requested system root, add its parent library path to those
356   // searched.
357   // FIXME: It's not clear whether we should use the driver's installed
358   // directory ('Dir' below) or the ResourceDir.
359   if (StringRef(D.Dir).startswith(SysRoot))
360     addPathIfExists(D, D.Dir + "/../lib", Paths);
361 
362   addPathIfExists(D, SysRoot + "/lib", Paths);
363   addPathIfExists(D, SysRoot + "/usr/lib", Paths);
364 }
365 
366 ToolChain::CXXStdlibType Linux::GetDefaultCXXStdlibType() const {
367   if (getTriple().isAndroid())
368     return ToolChain::CST_Libcxx;
369   return ToolChain::CST_Libstdcxx;
370 }
371 
372 bool Linux::HasNativeLLVMSupport() const { return true; }
373 
374 Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
375 
376 Tool *Linux::buildStaticLibTool() const {
377   return new tools::gnutools::StaticLibTool(*this);
378 }
379 
380 Tool *Linux::buildAssembler() const {
381   return new tools::gnutools::Assembler(*this);
382 }
383 
384 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().getInstalledDir();
392     std::string AndroidSysRootPath = (ClangDir + "/../sysroot").str();
393     if (getVFS().exists(AndroidSysRootPath))
394       return AndroidSysRootPath;
395   }
396 
397   if (!GCCInstallation.isValid() || !getTriple().isMIPS())
398     return std::string();
399 
400   // Standalone MIPS toolchains use different names for sysroot folder
401   // and put it into different places. Here we try to check some known
402   // variants.
403 
404   const StringRef InstallDir = GCCInstallation.getInstallPath();
405   const StringRef TripleStr = GCCInstallation.getTriple().str();
406   const Multilib &Multilib = GCCInstallation.getMultilib();
407 
408   std::string Path =
409       (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
410           .str();
411 
412   if (getVFS().exists(Path))
413     return Path;
414 
415   Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
416 
417   if (getVFS().exists(Path))
418     return Path;
419 
420   return std::string();
421 }
422 
423 std::string Linux::getDynamicLinker(const ArgList &Args) const {
424   const llvm::Triple::ArchType Arch = getArch();
425   const llvm::Triple &Triple = getTriple();
426 
427   const Distro Distro(getDriver().getVFS(), Triple);
428 
429   if (Triple.isAndroid())
430     return Triple.isArch64Bit() ? "/system/bin/linker64" : "/system/bin/linker";
431 
432   if (Triple.isMusl()) {
433     std::string ArchName;
434     bool IsArm = false;
435 
436     switch (Arch) {
437     case llvm::Triple::arm:
438     case llvm::Triple::thumb:
439       ArchName = "arm";
440       IsArm = true;
441       break;
442     case llvm::Triple::armeb:
443     case llvm::Triple::thumbeb:
444       ArchName = "armeb";
445       IsArm = true;
446       break;
447     default:
448       ArchName = Triple.getArchName().str();
449     }
450     if (IsArm &&
451         (Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
452          tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard))
453       ArchName += "hf";
454 
455     return "/lib/ld-musl-" + ArchName + ".so.1";
456   }
457 
458   std::string LibDir;
459   std::string Loader;
460 
461   switch (Arch) {
462   default:
463     llvm_unreachable("unsupported architecture");
464 
465   case llvm::Triple::aarch64:
466     LibDir = "lib";
467     Loader = "ld-linux-aarch64.so.1";
468     break;
469   case llvm::Triple::aarch64_be:
470     LibDir = "lib";
471     Loader = "ld-linux-aarch64_be.so.1";
472     break;
473   case llvm::Triple::arm:
474   case llvm::Triple::thumb:
475   case llvm::Triple::armeb:
476   case llvm::Triple::thumbeb: {
477     const bool HF =
478         Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
479         tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard;
480 
481     LibDir = "lib";
482     Loader = HF ? "ld-linux-armhf.so.3" : "ld-linux.so.3";
483     break;
484   }
485   case llvm::Triple::m68k:
486     LibDir = "lib";
487     Loader = "ld.so.1";
488     break;
489   case llvm::Triple::mips:
490   case llvm::Triple::mipsel:
491   case llvm::Triple::mips64:
492   case llvm::Triple::mips64el: {
493     bool IsNaN2008 = tools::mips::isNaN2008(Args, Triple);
494 
495     LibDir = "lib" + tools::mips::getMipsABILibSuffix(Args, Triple);
496 
497     if (tools::mips::isUCLibc(Args))
498       Loader = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
499     else if (!Triple.hasEnvironment() &&
500              Triple.getVendor() == llvm::Triple::VendorType::MipsTechnologies)
501       Loader =
502           Triple.isLittleEndian() ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
503     else
504       Loader = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
505 
506     break;
507   }
508   case llvm::Triple::ppc:
509     LibDir = "lib";
510     Loader = "ld.so.1";
511     break;
512   case llvm::Triple::ppcle:
513     LibDir = "lib";
514     Loader = "ld.so.1";
515     break;
516   case llvm::Triple::ppc64:
517     LibDir = "lib64";
518     Loader =
519         (tools::ppc::hasPPCAbiArg(Args, "elfv2")) ? "ld64.so.2" : "ld64.so.1";
520     break;
521   case llvm::Triple::ppc64le:
522     LibDir = "lib64";
523     Loader =
524         (tools::ppc::hasPPCAbiArg(Args, "elfv1")) ? "ld64.so.1" : "ld64.so.2";
525     break;
526   case llvm::Triple::riscv32: {
527     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
528     LibDir = "lib";
529     Loader = ("ld-linux-riscv32-" + ABIName + ".so.1").str();
530     break;
531   }
532   case llvm::Triple::riscv64: {
533     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
534     LibDir = "lib";
535     Loader = ("ld-linux-riscv64-" + ABIName + ".so.1").str();
536     break;
537   }
538   case llvm::Triple::sparc:
539   case llvm::Triple::sparcel:
540     LibDir = "lib";
541     Loader = "ld-linux.so.2";
542     break;
543   case llvm::Triple::sparcv9:
544     LibDir = "lib64";
545     Loader = "ld-linux.so.2";
546     break;
547   case llvm::Triple::systemz:
548     LibDir = "lib";
549     Loader = "ld64.so.1";
550     break;
551   case llvm::Triple::x86:
552     LibDir = "lib";
553     Loader = "ld-linux.so.2";
554     break;
555   case llvm::Triple::x86_64: {
556     bool X32 = Triple.getEnvironment() == llvm::Triple::GNUX32;
557 
558     LibDir = X32 ? "libx32" : "lib64";
559     Loader = X32 ? "ld-linux-x32.so.2" : "ld-linux-x86-64.so.2";
560     break;
561   }
562   case llvm::Triple::ve:
563     return "/opt/nec/ve/lib/ld-linux-ve.so.1";
564   }
565 
566   if (Distro == Distro::Exherbo &&
567       (Triple.getVendor() == llvm::Triple::UnknownVendor ||
568        Triple.getVendor() == llvm::Triple::PC))
569     return "/usr/" + Triple.str() + "/lib/" + Loader;
570   return "/" + LibDir + "/" + Loader;
571 }
572 
573 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
574                                       ArgStringList &CC1Args) const {
575   const Driver &D = getDriver();
576   std::string SysRoot = computeSysRoot();
577 
578   if (DriverArgs.hasArg(clang::driver::options::OPT_nostdinc))
579     return;
580 
581   if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
582     addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
583 
584   SmallString<128> ResourceDirInclude(D.ResourceDir);
585   llvm::sys::path::append(ResourceDirInclude, "include");
586   if (!DriverArgs.hasArg(options::OPT_nobuiltininc) &&
587       (!getTriple().isMusl() || DriverArgs.hasArg(options::OPT_nostdlibinc)))
588     addSystemInclude(DriverArgs, CC1Args, ResourceDirInclude);
589 
590   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
591     return;
592 
593   // Check for configure-time C include directories.
594   StringRef CIncludeDirs(C_INCLUDE_DIRS);
595   if (CIncludeDirs != "") {
596     SmallVector<StringRef, 5> dirs;
597     CIncludeDirs.split(dirs, ":");
598     for (StringRef dir : dirs) {
599       StringRef Prefix =
600           llvm::sys::path::is_absolute(dir) ? "" : StringRef(SysRoot);
601       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
602     }
603     return;
604   }
605 
606   // Lacking those, try to detect the correct set of system includes for the
607   // target triple.
608 
609   AddMultilibIncludeArgs(DriverArgs, CC1Args);
610 
611   // Implement generic Debian multiarch support.
612   const StringRef X86_64MultiarchIncludeDirs[] = {
613       "/usr/include/x86_64-linux-gnu",
614 
615       // FIXME: These are older forms of multiarch. It's not clear that they're
616       // in use in any released version of Debian, so we should consider
617       // removing them.
618       "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"};
619   const StringRef X86MultiarchIncludeDirs[] = {
620       "/usr/include/i386-linux-gnu",
621 
622       // FIXME: These are older forms of multiarch. It's not clear that they're
623       // in use in any released version of Debian, so we should consider
624       // removing them.
625       "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
626       "/usr/include/i486-linux-gnu"};
627   const StringRef AArch64MultiarchIncludeDirs[] = {
628       "/usr/include/aarch64-linux-gnu"};
629   const StringRef ARMMultiarchIncludeDirs[] = {
630       "/usr/include/arm-linux-gnueabi"};
631   const StringRef ARMHFMultiarchIncludeDirs[] = {
632       "/usr/include/arm-linux-gnueabihf"};
633   const StringRef ARMEBMultiarchIncludeDirs[] = {
634       "/usr/include/armeb-linux-gnueabi"};
635   const StringRef ARMEBHFMultiarchIncludeDirs[] = {
636       "/usr/include/armeb-linux-gnueabihf"};
637   const StringRef M68kMultiarchIncludeDirs[] = {"/usr/include/m68k-linux-gnu"};
638   const StringRef MIPSMultiarchIncludeDirs[] = {"/usr/include/mips-linux-gnu"};
639   const StringRef MIPSELMultiarchIncludeDirs[] = {
640       "/usr/include/mipsel-linux-gnu"};
641   const StringRef MIPS64MultiarchIncludeDirs[] = {
642       "/usr/include/mips64-linux-gnuabi64"};
643   const StringRef MIPS64ELMultiarchIncludeDirs[] = {
644       "/usr/include/mips64el-linux-gnuabi64"};
645   const StringRef MIPSN32MultiarchIncludeDirs[] = {
646       "/usr/include/mips64-linux-gnuabin32"};
647   const StringRef MIPSN32ELMultiarchIncludeDirs[] = {
648       "/usr/include/mips64el-linux-gnuabin32"};
649   const StringRef MIPSR6MultiarchIncludeDirs[] = {
650       "/usr/include/mipsisa32-linux-gnu"};
651   const StringRef MIPSR6ELMultiarchIncludeDirs[] = {
652       "/usr/include/mipsisa32r6el-linux-gnu"};
653   const StringRef MIPS64R6MultiarchIncludeDirs[] = {
654       "/usr/include/mipsisa64r6-linux-gnuabi64"};
655   const StringRef MIPS64R6ELMultiarchIncludeDirs[] = {
656       "/usr/include/mipsisa64r6el-linux-gnuabi64"};
657   const StringRef MIPSN32R6MultiarchIncludeDirs[] = {
658       "/usr/include/mipsisa64r6-linux-gnuabin32"};
659   const StringRef MIPSN32R6ELMultiarchIncludeDirs[] = {
660       "/usr/include/mipsisa64r6el-linux-gnuabin32"};
661   const StringRef PPCMultiarchIncludeDirs[] = {
662       "/usr/include/powerpc-linux-gnu",
663       "/usr/include/powerpc-linux-gnuspe"};
664   const StringRef PPCLEMultiarchIncludeDirs[] = {
665       "/usr/include/powerpcle-linux-gnu"};
666   const StringRef PPC64MultiarchIncludeDirs[] = {
667       "/usr/include/powerpc64-linux-gnu"};
668   const StringRef PPC64LEMultiarchIncludeDirs[] = {
669       "/usr/include/powerpc64le-linux-gnu"};
670   const StringRef SparcMultiarchIncludeDirs[] = {
671       "/usr/include/sparc-linux-gnu"};
672   const StringRef Sparc64MultiarchIncludeDirs[] = {
673       "/usr/include/sparc64-linux-gnu"};
674   const StringRef SYSTEMZMultiarchIncludeDirs[] = {
675       "/usr/include/s390x-linux-gnu"};
676   ArrayRef<StringRef> MultiarchIncludeDirs;
677   switch (getTriple().getArch()) {
678   case llvm::Triple::x86_64:
679     MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
680     break;
681   case llvm::Triple::x86:
682     MultiarchIncludeDirs = X86MultiarchIncludeDirs;
683     break;
684   case llvm::Triple::aarch64:
685   case llvm::Triple::aarch64_be:
686     MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
687     break;
688   case llvm::Triple::arm:
689   case llvm::Triple::thumb:
690     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
691       MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
692     else
693       MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
694     break;
695   case llvm::Triple::armeb:
696   case llvm::Triple::thumbeb:
697     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
698       MultiarchIncludeDirs = ARMEBHFMultiarchIncludeDirs;
699     else
700       MultiarchIncludeDirs = ARMEBMultiarchIncludeDirs;
701     break;
702   case llvm::Triple::m68k:
703     MultiarchIncludeDirs = M68kMultiarchIncludeDirs;
704     break;
705   case llvm::Triple::mips:
706     if (getTriple().getSubArch() == llvm::Triple::MipsSubArch_r6)
707       MultiarchIncludeDirs = MIPSR6MultiarchIncludeDirs;
708     else
709       MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
710     break;
711   case llvm::Triple::mipsel:
712     if (getTriple().getSubArch() == llvm::Triple::MipsSubArch_r6)
713       MultiarchIncludeDirs = MIPSR6ELMultiarchIncludeDirs;
714     else
715       MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
716     break;
717   case llvm::Triple::mips64:
718     if (getTriple().getSubArch() == llvm::Triple::MipsSubArch_r6)
719       if (getTriple().getEnvironment() == llvm::Triple::GNUABIN32)
720         MultiarchIncludeDirs = MIPSN32R6MultiarchIncludeDirs;
721       else
722         MultiarchIncludeDirs = MIPS64R6MultiarchIncludeDirs;
723     else if (getTriple().getEnvironment() == llvm::Triple::GNUABIN32)
724       MultiarchIncludeDirs = MIPSN32MultiarchIncludeDirs;
725     else
726       MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs;
727     break;
728   case llvm::Triple::mips64el:
729     if (getTriple().getSubArch() == llvm::Triple::MipsSubArch_r6)
730       if (getTriple().getEnvironment() == llvm::Triple::GNUABIN32)
731         MultiarchIncludeDirs = MIPSN32R6ELMultiarchIncludeDirs;
732       else
733         MultiarchIncludeDirs = MIPS64R6ELMultiarchIncludeDirs;
734     else if (getTriple().getEnvironment() == llvm::Triple::GNUABIN32)
735       MultiarchIncludeDirs = MIPSN32ELMultiarchIncludeDirs;
736     else
737       MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs;
738     break;
739   case llvm::Triple::ppc:
740     MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
741     break;
742   case llvm::Triple::ppcle:
743     MultiarchIncludeDirs = PPCLEMultiarchIncludeDirs;
744     break;
745   case llvm::Triple::ppc64:
746     MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
747     break;
748   case llvm::Triple::ppc64le:
749     MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs;
750     break;
751   case llvm::Triple::sparc:
752     MultiarchIncludeDirs = SparcMultiarchIncludeDirs;
753     break;
754   case llvm::Triple::sparcv9:
755     MultiarchIncludeDirs = Sparc64MultiarchIncludeDirs;
756     break;
757   case llvm::Triple::systemz:
758     MultiarchIncludeDirs = SYSTEMZMultiarchIncludeDirs;
759     break;
760   default:
761     break;
762   }
763 
764   const std::string AndroidMultiarchIncludeDir =
765       std::string("/usr/include/") +
766       getMultiarchTriple(D, getTriple(), SysRoot);
767   const StringRef AndroidMultiarchIncludeDirs[] = {AndroidMultiarchIncludeDir};
768   if (getTriple().isAndroid())
769     MultiarchIncludeDirs = AndroidMultiarchIncludeDirs;
770 
771   for (StringRef Dir : MultiarchIncludeDirs) {
772     if (D.getVFS().exists(SysRoot + Dir)) {
773       addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir);
774       break;
775     }
776   }
777 
778   if (getTriple().getOS() == llvm::Triple::RTEMS)
779     return;
780 
781   // Add an include of '/include' directly. This isn't provided by default by
782   // system GCCs, but is often used with cross-compiling GCCs, and harmless to
783   // add even when Clang is acting as-if it were a system compiler.
784   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
785 
786   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
787 
788   if (!DriverArgs.hasArg(options::OPT_nobuiltininc) && getTriple().isMusl())
789     addSystemInclude(DriverArgs, CC1Args, ResourceDirInclude);
790 }
791 
792 void Linux::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
793                                      llvm::opt::ArgStringList &CC1Args) const {
794   // Try generic GCC detection first.
795   if (Generic_GCC::addGCCLibStdCxxIncludePaths(DriverArgs, CC1Args))
796     return;
797 
798   // We need a detected GCC installation on Linux to provide libstdc++'s
799   // headers in odd Linuxish places.
800   if (!GCCInstallation.isValid())
801     return;
802 
803   StringRef LibDir = GCCInstallation.getParentLibPath();
804   StringRef TripleStr = GCCInstallation.getTriple().str();
805   const Multilib &Multilib = GCCInstallation.getMultilib();
806   const GCCVersion &Version = GCCInstallation.getVersion();
807 
808   const std::string LibStdCXXIncludePathCandidates[] = {
809       // Android standalone toolchain has C++ headers in yet another place.
810       LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
811       // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
812       // without a subdirectory corresponding to the gcc version.
813       LibDir.str() + "/../include/c++",
814       // Cray's gcc installation puts headers under "g++" without a
815       // version suffix.
816       LibDir.str() + "/../include/g++",
817   };
818 
819   for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
820     if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
821                                  /*GCCMultiarchTriple*/ "",
822                                  /*TargetMultiarchTriple*/ "",
823                                  Multilib.includeSuffix(), DriverArgs, CC1Args))
824       break;
825   }
826 }
827 
828 void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs,
829                                ArgStringList &CC1Args) const {
830   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
831 }
832 
833 void Linux::AddHIPIncludeArgs(const ArgList &DriverArgs,
834                               ArgStringList &CC1Args) const {
835   RocmInstallation.AddHIPIncludeArgs(DriverArgs, CC1Args);
836 }
837 
838 void Linux::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
839                                 ArgStringList &CC1Args) const {
840   if (GCCInstallation.isValid()) {
841     CC1Args.push_back("-isystem");
842     CC1Args.push_back(DriverArgs.MakeArgString(
843         GCCInstallation.getParentLibPath() + "/../" +
844         GCCInstallation.getTriple().str() + "/include"));
845   }
846 }
847 
848 bool Linux::isPIEDefault() const {
849   return (getTriple().isAndroid() && !getTriple().isAndroidVersionLT(16)) ||
850           getTriple().isMusl() || getSanitizerArgs().requiresPIE();
851 }
852 
853 bool Linux::IsAArch64OutlineAtomicsDefault(const ArgList &Args) const {
854   // Outline atomics for AArch64 are supported by compiler-rt
855   // and libgcc since 9.3.1
856   assert(getTriple().isAArch64() && "expected AArch64 target!");
857   ToolChain::RuntimeLibType RtLib = GetRuntimeLibType(Args);
858   if (RtLib == ToolChain::RLT_CompilerRT)
859     return true;
860   assert(RtLib == ToolChain::RLT_Libgcc && "unexpected runtime library type!");
861   if (GCCInstallation.getVersion().isOlderThan(9, 3, 1))
862     return false;
863   return true;
864 }
865 
866 bool Linux::isNoExecStackDefault() const {
867     return getTriple().isAndroid();
868 }
869 
870 bool Linux::IsMathErrnoDefault() const {
871   if (getTriple().isAndroid())
872     return false;
873   return Generic_ELF::IsMathErrnoDefault();
874 }
875 
876 SanitizerMask Linux::getSupportedSanitizers() const {
877   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
878   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
879   const bool IsMIPS = getTriple().isMIPS32();
880   const bool IsMIPS64 = getTriple().isMIPS64();
881   const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
882                            getTriple().getArch() == llvm::Triple::ppc64le;
883   const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
884                          getTriple().getArch() == llvm::Triple::aarch64_be;
885   const bool IsArmArch = getTriple().getArch() == llvm::Triple::arm ||
886                          getTriple().getArch() == llvm::Triple::thumb ||
887                          getTriple().getArch() == llvm::Triple::armeb ||
888                          getTriple().getArch() == llvm::Triple::thumbeb;
889   const bool IsRISCV64 = getTriple().getArch() == llvm::Triple::riscv64;
890   const bool IsSystemZ = getTriple().getArch() == llvm::Triple::systemz;
891   SanitizerMask Res = ToolChain::getSupportedSanitizers();
892   Res |= SanitizerKind::Address;
893   Res |= SanitizerKind::PointerCompare;
894   Res |= SanitizerKind::PointerSubtract;
895   Res |= SanitizerKind::Fuzzer;
896   Res |= SanitizerKind::FuzzerNoLink;
897   Res |= SanitizerKind::KernelAddress;
898   Res |= SanitizerKind::Memory;
899   Res |= SanitizerKind::Vptr;
900   Res |= SanitizerKind::SafeStack;
901   if (IsX86_64 || IsMIPS64 || IsAArch64)
902     Res |= SanitizerKind::DataFlow;
903   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsArmArch || IsPowerPC64 ||
904       IsRISCV64 || IsSystemZ)
905     Res |= SanitizerKind::Leak;
906   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64)
907     Res |= SanitizerKind::Thread;
908   if (IsX86_64)
909     Res |= SanitizerKind::KernelMemory;
910   if (IsX86 || IsX86_64)
911     Res |= SanitizerKind::Function;
912   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsMIPS || IsArmArch ||
913       IsPowerPC64)
914     Res |= SanitizerKind::Scudo;
915   if (IsX86_64 || IsAArch64) {
916     Res |= SanitizerKind::HWAddress;
917     Res |= SanitizerKind::KernelHWAddress;
918   }
919   return Res;
920 }
921 
922 void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args,
923                              llvm::opt::ArgStringList &CmdArgs) const {
924   // Add linker option -u__llvm_profile_runtime to cause runtime
925   // initialization module to be linked in.
926   if (needsProfileRT(Args))
927     CmdArgs.push_back(Args.MakeArgString(
928         Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
929   ToolChain::addProfileRTLibs(Args, CmdArgs);
930 }
931 
932 llvm::DenormalMode
933 Linux::getDefaultDenormalModeForType(const llvm::opt::ArgList &DriverArgs,
934                                      const JobAction &JA,
935                                      const llvm::fltSemantics *FPType) const {
936   switch (getTriple().getArch()) {
937   case llvm::Triple::x86:
938   case llvm::Triple::x86_64: {
939     std::string Unused;
940     // DAZ and FTZ are turned on in crtfastmath.o
941     if (!DriverArgs.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
942         isFastMathRuntimeAvailable(DriverArgs, Unused))
943       return llvm::DenormalMode::getPreserveSign();
944     return llvm::DenormalMode::getIEEE();
945   }
946   default:
947     return llvm::DenormalMode::getIEEE();
948   }
949 }
950 
951 void Linux::addExtraOpts(llvm::opt::ArgStringList &CmdArgs) const {
952   for (const auto &Opt : ExtraOpts)
953     CmdArgs.push_back(Opt.c_str());
954 }
955