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