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 static std::string getMultiarchTriple(const Driver &D,
41                                       const llvm::Triple &TargetTriple,
42                                       StringRef SysRoot) {
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 static void addMultilibsFilePaths(const Driver &D, const MultilibSet &Multilibs,
212                                   const Multilib &Multilib,
213                                   StringRef InstallPath,
214                                   ToolChain::path_list &Paths) {
215   if (const auto &PathsCallback = Multilibs.filePathsCallback())
216     for (const auto &Path : PathsCallback(Multilib))
217       addPathIfExists(D, InstallPath + Path, Paths);
218 }
219 
220 Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
221     : Generic_ELF(D, Triple, Args) {
222   GCCInstallation.init(Triple, Args);
223   Multilibs = GCCInstallation.getMultilibs();
224   SelectedMultilib = GCCInstallation.getMultilib();
225   llvm::Triple::ArchType Arch = Triple.getArch();
226   std::string SysRoot = computeSysRoot();
227 
228   // Cross-compiling binutils and GCC installations (vanilla and openSUSE at
229   // least) put various tools in a triple-prefixed directory off of the parent
230   // of the GCC installation. We use the GCC triple here to ensure that we end
231   // up with tools that support the same amount of cross compiling as the
232   // detected GCC installation. For example, if we find a GCC installation
233   // targeting x86_64, but it is a bi-arch GCC installation, it can also be
234   // used to target i386.
235   // FIXME: This seems unlikely to be Linux-specific.
236   ToolChain::path_list &PPaths = getProgramPaths();
237   PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" +
238                          GCCInstallation.getTriple().str() + "/bin")
239                        .str());
240 
241   Distro Distro(D.getVFS());
242 
243   if (Distro.IsAlpineLinux() || Triple.isAndroid()) {
244     ExtraOpts.push_back("-z");
245     ExtraOpts.push_back("now");
246   }
247 
248   if (Distro.IsOpenSUSE() || Distro.IsUbuntu() || Distro.IsAlpineLinux() ||
249       Triple.isAndroid()) {
250     ExtraOpts.push_back("-z");
251     ExtraOpts.push_back("relro");
252   }
253 
254   // The lld default page size is too large for Aarch64, which produces much
255   // larger .so files and images for arm64 device targets. Use 4KB page size
256   // for Android arm64 targets instead.
257   if (Triple.isAArch64() && Triple.isAndroid()) {
258     ExtraOpts.push_back("-z");
259     ExtraOpts.push_back("max-page-size=4096");
260   }
261 
262   if (GCCInstallation.getParentLibPath().find("opt/rh/devtoolset") !=
263       StringRef::npos)
264     // With devtoolset on RHEL, we want to add a bin directory that is relative
265     // to the detected gcc install, because if we are using devtoolset gcc then
266     // we want to use other tools from devtoolset (e.g. ld) instead of the
267     // standard system tools.
268     PPaths.push_back(Twine(GCCInstallation.getParentLibPath() +
269                      "/../bin").str());
270 
271   if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)
272     ExtraOpts.push_back("-X");
273 
274   const bool IsAndroid = Triple.isAndroid();
275   const bool IsMips = Triple.isMIPS();
276   const bool IsHexagon = Arch == llvm::Triple::hexagon;
277   const bool IsRISCV =
278       Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64;
279 
280   if (IsMips && !SysRoot.empty())
281     ExtraOpts.push_back("--sysroot=" + SysRoot);
282 
283   // Do not use 'gnu' hash style for Mips targets because .gnu.hash
284   // and the MIPS ABI require .dynsym to be sorted in different ways.
285   // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
286   // ABI requires a mapping between the GOT and the symbol table.
287   // Android loader does not support .gnu.hash until API 23.
288   // Hexagon linker/loader does not support .gnu.hash
289   if (!IsMips && !IsHexagon) {
290     if (Distro.IsRedhat() || Distro.IsOpenSUSE() || Distro.IsAlpineLinux() ||
291         (Distro.IsUbuntu() && Distro >= Distro::UbuntuMaverick) ||
292         (IsAndroid && !Triple.isAndroidVersionLT(23)))
293       ExtraOpts.push_back("--hash-style=gnu");
294 
295     if (Distro.IsDebian() || Distro.IsOpenSUSE() ||
296         Distro == Distro::UbuntuLucid || Distro == Distro::UbuntuJaunty ||
297         Distro == Distro::UbuntuKarmic ||
298         (IsAndroid && Triple.isAndroidVersionLT(23)))
299       ExtraOpts.push_back("--hash-style=both");
300   }
301 
302   if (Distro.IsRedhat() && Distro != Distro::RHEL5 && Distro != Distro::RHEL6)
303     ExtraOpts.push_back("--no-add-needed");
304 
305 #ifdef ENABLE_LINKER_BUILD_ID
306   ExtraOpts.push_back("--build-id");
307 #endif
308 
309   if (IsAndroid || Distro.IsOpenSUSE())
310     ExtraOpts.push_back("--enable-new-dtags");
311 
312   // The selection of paths to try here is designed to match the patterns which
313   // the GCC driver itself uses, as this is part of the GCC-compatible driver.
314   // This was determined by running GCC in a fake filesystem, creating all
315   // possible permutations of these directories, and seeing which ones it added
316   // to the link paths.
317   path_list &Paths = getFilePaths();
318 
319   const std::string OSLibDir = getOSLibDir(Triple, Args);
320   const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot);
321 
322   // Add the multilib suffixed paths where they are available.
323   if (GCCInstallation.isValid()) {
324     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
325     const std::string &LibPath = GCCInstallation.getParentLibPath();
326 
327     // Add toolchain / multilib specific file paths.
328     addMultilibsFilePaths(D, Multilibs, SelectedMultilib,
329                           GCCInstallation.getInstallPath(), Paths);
330 
331     // Sourcery CodeBench MIPS toolchain holds some libraries under
332     // a biarch-like suffix of the GCC installation.
333     addPathIfExists(
334         D, GCCInstallation.getInstallPath() + SelectedMultilib.gccSuffix(),
335         Paths);
336 
337     // GCC cross compiling toolchains will install target libraries which ship
338     // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as
339     // any part of the GCC installation in
340     // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat
341     // debatable, but is the reality today. We need to search this tree even
342     // when we have a sysroot somewhere else. It is the responsibility of
343     // whomever is doing the cross build targeting a sysroot using a GCC
344     // installation that is *not* within the system root to ensure two things:
345     //
346     //  1) Any DSOs that are linked in from this tree or from the install path
347     //     above must be present on the system root and found via an
348     //     appropriate rpath.
349     //  2) There must not be libraries installed into
350     //     <prefix>/<triple>/<libdir> unless they should be preferred over
351     //     those within the system root.
352     //
353     // Note that this matches the GCC behavior. See the below comment for where
354     // Clang diverges from GCC's behavior.
355     addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib/../" +
356                            OSLibDir + SelectedMultilib.osSuffix(),
357                     Paths);
358 
359     // If the GCC installation we found is inside of the sysroot, we want to
360     // prefer libraries installed in the parent prefix of the GCC installation.
361     // It is important to *not* use these paths when the GCC installation is
362     // outside of the system root as that can pick up unintended libraries.
363     // This usually happens when there is an external cross compiler on the
364     // host system, and a more minimal sysroot available that is the target of
365     // the cross. Note that GCC does include some of these directories in some
366     // configurations but this seems somewhere between questionable and simply
367     // a bug.
368     if (StringRef(LibPath).startswith(SysRoot)) {
369       addPathIfExists(D, LibPath + "/" + MultiarchTriple, Paths);
370       addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths);
371     }
372   }
373 
374   // Similar to the logic for GCC above, if we currently running Clang inside
375   // of the requested system root, add its parent library paths to
376   // those searched.
377   // FIXME: It's not clear whether we should use the driver's installed
378   // directory ('Dir' below) or the ResourceDir.
379   if (StringRef(D.Dir).startswith(SysRoot)) {
380     addPathIfExists(D, D.Dir + "/../lib/" + MultiarchTriple, Paths);
381     addPathIfExists(D, D.Dir + "/../" + OSLibDir, Paths);
382   }
383 
384   addPathIfExists(D, SysRoot + "/lib/" + MultiarchTriple, Paths);
385   addPathIfExists(D, SysRoot + "/lib/../" + OSLibDir, Paths);
386 
387   if (IsAndroid) {
388     // Android sysroots contain a library directory for each supported OS
389     // version as well as some unversioned libraries in the usual multiarch
390     // directory.
391     unsigned Major;
392     unsigned Minor;
393     unsigned Micro;
394     Triple.getEnvironmentVersion(Major, Minor, Micro);
395     addPathIfExists(D,
396                     SysRoot + "/usr/lib/" + MultiarchTriple + "/" +
397                         llvm::to_string(Major),
398                     Paths);
399   }
400 
401   addPathIfExists(D, SysRoot + "/usr/lib/" + MultiarchTriple, Paths);
402   // 64-bit OpenEmbedded sysroots may not have a /usr/lib dir. So they cannot
403   // find /usr/lib64 as it is referenced as /usr/lib/../lib64. So we handle
404   // this here.
405   if (Triple.getVendor() == llvm::Triple::OpenEmbedded &&
406       Triple.isArch64Bit())
407     addPathIfExists(D, SysRoot + "/usr/" + OSLibDir, Paths);
408   else
409     addPathIfExists(D, SysRoot + "/usr/lib/../" + OSLibDir, Paths);
410   if (IsRISCV) {
411     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
412     addPathIfExists(D, SysRoot + "/" + OSLibDir + "/" + ABIName, Paths);
413     addPathIfExists(D, SysRoot + "/usr/" + OSLibDir + "/" + ABIName, Paths);
414   }
415 
416   // Try walking via the GCC triple path in case of biarch or multiarch GCC
417   // installations with strange symlinks.
418   if (GCCInstallation.isValid()) {
419     addPathIfExists(D,
420                     SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() +
421                         "/../../" + OSLibDir,
422                     Paths);
423 
424     // Add the 'other' biarch variant path
425     Multilib BiarchSibling;
426     if (GCCInstallation.getBiarchSibling(BiarchSibling)) {
427       addPathIfExists(D, GCCInstallation.getInstallPath() +
428                              BiarchSibling.gccSuffix(),
429                       Paths);
430     }
431 
432     // See comments above on the multilib variant for details of why this is
433     // included even from outside the sysroot.
434     const std::string &LibPath = GCCInstallation.getParentLibPath();
435     const llvm::Triple &GCCTriple = GCCInstallation.getTriple();
436     const Multilib &Multilib = GCCInstallation.getMultilib();
437     addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib" +
438                            Multilib.osSuffix(),
439                     Paths);
440 
441     // See comments above on the multilib variant for details of why this is
442     // only included from within the sysroot.
443     if (StringRef(LibPath).startswith(SysRoot))
444       addPathIfExists(D, LibPath, Paths);
445   }
446 
447   // Similar to the logic for GCC above, if we are currently running Clang
448   // inside of the requested system root, add its parent library path to those
449   // searched.
450   // FIXME: It's not clear whether we should use the driver's installed
451   // directory ('Dir' below) or the ResourceDir.
452   if (StringRef(D.Dir).startswith(SysRoot))
453     addPathIfExists(D, D.Dir + "/../lib", Paths);
454 
455   addPathIfExists(D, SysRoot + "/lib", Paths);
456   addPathIfExists(D, SysRoot + "/usr/lib", Paths);
457 }
458 
459 ToolChain::CXXStdlibType Linux::GetDefaultCXXStdlibType() const {
460   if (getTriple().isAndroid())
461     return ToolChain::CST_Libcxx;
462   return ToolChain::CST_Libstdcxx;
463 }
464 
465 bool Linux::HasNativeLLVMSupport() const { return true; }
466 
467 Tool *Linux::buildLinker() const { return new tools::gnutools::Linker(*this); }
468 
469 Tool *Linux::buildAssembler() const {
470   return new tools::gnutools::Assembler(*this);
471 }
472 
473 std::string Linux::computeSysRoot() const {
474   if (!getDriver().SysRoot.empty())
475     return getDriver().SysRoot;
476 
477   if (getTriple().isAndroid()) {
478     // Android toolchains typically include a sysroot at ../sysroot relative to
479     // the clang binary.
480     const StringRef ClangDir = getDriver().getInstalledDir();
481     std::string AndroidSysRootPath = (ClangDir + "/../sysroot").str();
482     if (getVFS().exists(AndroidSysRootPath))
483       return AndroidSysRootPath;
484   }
485 
486   if (!GCCInstallation.isValid() || !getTriple().isMIPS())
487     return std::string();
488 
489   // Standalone MIPS toolchains use different names for sysroot folder
490   // and put it into different places. Here we try to check some known
491   // variants.
492 
493   const StringRef InstallDir = GCCInstallation.getInstallPath();
494   const StringRef TripleStr = GCCInstallation.getTriple().str();
495   const Multilib &Multilib = GCCInstallation.getMultilib();
496 
497   std::string Path =
498       (InstallDir + "/../../../../" + TripleStr + "/libc" + Multilib.osSuffix())
499           .str();
500 
501   if (getVFS().exists(Path))
502     return Path;
503 
504   Path = (InstallDir + "/../../../../sysroot" + Multilib.osSuffix()).str();
505 
506   if (getVFS().exists(Path))
507     return Path;
508 
509   return std::string();
510 }
511 
512 std::string Linux::getDynamicLinker(const ArgList &Args) const {
513   const llvm::Triple::ArchType Arch = getArch();
514   const llvm::Triple &Triple = getTriple();
515 
516   const Distro Distro(getDriver().getVFS());
517 
518   if (Triple.isAndroid())
519     return Triple.isArch64Bit() ? "/system/bin/linker64" : "/system/bin/linker";
520 
521   if (Triple.isMusl()) {
522     std::string ArchName;
523     bool IsArm = false;
524 
525     switch (Arch) {
526     case llvm::Triple::arm:
527     case llvm::Triple::thumb:
528       ArchName = "arm";
529       IsArm = true;
530       break;
531     case llvm::Triple::armeb:
532     case llvm::Triple::thumbeb:
533       ArchName = "armeb";
534       IsArm = true;
535       break;
536     default:
537       ArchName = Triple.getArchName().str();
538     }
539     if (IsArm &&
540         (Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
541          tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard))
542       ArchName += "hf";
543 
544     return "/lib/ld-musl-" + ArchName + ".so.1";
545   }
546 
547   std::string LibDir;
548   std::string Loader;
549 
550   switch (Arch) {
551   default:
552     llvm_unreachable("unsupported architecture");
553 
554   case llvm::Triple::aarch64:
555     LibDir = "lib";
556     Loader = "ld-linux-aarch64.so.1";
557     break;
558   case llvm::Triple::aarch64_be:
559     LibDir = "lib";
560     Loader = "ld-linux-aarch64_be.so.1";
561     break;
562   case llvm::Triple::arm:
563   case llvm::Triple::thumb:
564   case llvm::Triple::armeb:
565   case llvm::Triple::thumbeb: {
566     const bool HF =
567         Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
568         tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard;
569 
570     LibDir = "lib";
571     Loader = HF ? "ld-linux-armhf.so.3" : "ld-linux.so.3";
572     break;
573   }
574   case llvm::Triple::mips:
575   case llvm::Triple::mipsel:
576   case llvm::Triple::mips64:
577   case llvm::Triple::mips64el: {
578     bool IsNaN2008 = tools::mips::isNaN2008(Args, Triple);
579 
580     LibDir = "lib" + tools::mips::getMipsABILibSuffix(Args, Triple);
581 
582     if (tools::mips::isUCLibc(Args))
583       Loader = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
584     else if (!Triple.hasEnvironment() &&
585              Triple.getVendor() == llvm::Triple::VendorType::MipsTechnologies)
586       Loader =
587           Triple.isLittleEndian() ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
588     else
589       Loader = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
590 
591     break;
592   }
593   case llvm::Triple::ppc:
594     LibDir = "lib";
595     Loader = "ld.so.1";
596     break;
597   case llvm::Triple::ppc64:
598     LibDir = "lib64";
599     Loader =
600         (tools::ppc::hasPPCAbiArg(Args, "elfv2")) ? "ld64.so.2" : "ld64.so.1";
601     break;
602   case llvm::Triple::ppc64le:
603     LibDir = "lib64";
604     Loader =
605         (tools::ppc::hasPPCAbiArg(Args, "elfv1")) ? "ld64.so.1" : "ld64.so.2";
606     break;
607   case llvm::Triple::riscv32: {
608     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
609     LibDir = "lib";
610     Loader = ("ld-linux-riscv32-" + ABIName + ".so.1").str();
611     break;
612   }
613   case llvm::Triple::riscv64: {
614     StringRef ABIName = tools::riscv::getRISCVABI(Args, Triple);
615     LibDir = "lib";
616     Loader = ("ld-linux-riscv64-" + ABIName + ".so.1").str();
617     break;
618   }
619   case llvm::Triple::sparc:
620   case llvm::Triple::sparcel:
621     LibDir = "lib";
622     Loader = "ld-linux.so.2";
623     break;
624   case llvm::Triple::sparcv9:
625     LibDir = "lib64";
626     Loader = "ld-linux.so.2";
627     break;
628   case llvm::Triple::systemz:
629     LibDir = "lib";
630     Loader = "ld64.so.1";
631     break;
632   case llvm::Triple::x86:
633     LibDir = "lib";
634     Loader = "ld-linux.so.2";
635     break;
636   case llvm::Triple::x86_64: {
637     bool X32 = Triple.getEnvironment() == llvm::Triple::GNUX32;
638 
639     LibDir = X32 ? "libx32" : "lib64";
640     Loader = X32 ? "ld-linux-x32.so.2" : "ld-linux-x86-64.so.2";
641     break;
642   }
643   }
644 
645   if (Distro == Distro::Exherbo &&
646       (Triple.getVendor() == llvm::Triple::UnknownVendor ||
647        Triple.getVendor() == llvm::Triple::PC))
648     return "/usr/" + Triple.str() + "/lib/" + Loader;
649   return "/" + LibDir + "/" + Loader;
650 }
651 
652 void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
653                                       ArgStringList &CC1Args) const {
654   const Driver &D = getDriver();
655   std::string SysRoot = computeSysRoot();
656 
657   if (DriverArgs.hasArg(clang::driver::options::OPT_nostdinc))
658     return;
659 
660   if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
661     addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
662 
663   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
664     SmallString<128> P(D.ResourceDir);
665     llvm::sys::path::append(P, "include");
666     addSystemInclude(DriverArgs, CC1Args, P);
667   }
668 
669   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
670     return;
671 
672   // Check for configure-time C include directories.
673   StringRef CIncludeDirs(C_INCLUDE_DIRS);
674   if (CIncludeDirs != "") {
675     SmallVector<StringRef, 5> dirs;
676     CIncludeDirs.split(dirs, ":");
677     for (StringRef dir : dirs) {
678       StringRef Prefix =
679           llvm::sys::path::is_absolute(dir) ? StringRef(SysRoot) : "";
680       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
681     }
682     return;
683   }
684 
685   // Lacking those, try to detect the correct set of system includes for the
686   // target triple.
687 
688   // Add include directories specific to the selected multilib set and multilib.
689   if (GCCInstallation.isValid()) {
690     const auto &Callback = Multilibs.includeDirsCallback();
691     if (Callback) {
692       for (const auto &Path : Callback(GCCInstallation.getMultilib()))
693         addExternCSystemIncludeIfExists(
694             DriverArgs, CC1Args, GCCInstallation.getInstallPath() + Path);
695     }
696   }
697 
698   // Implement generic Debian multiarch support.
699   const StringRef X86_64MultiarchIncludeDirs[] = {
700       "/usr/include/x86_64-linux-gnu",
701 
702       // FIXME: These are older forms of multiarch. It's not clear that they're
703       // in use in any released version of Debian, so we should consider
704       // removing them.
705       "/usr/include/i686-linux-gnu/64", "/usr/include/i486-linux-gnu/64"};
706   const StringRef X86MultiarchIncludeDirs[] = {
707       "/usr/include/i386-linux-gnu",
708 
709       // FIXME: These are older forms of multiarch. It's not clear that they're
710       // in use in any released version of Debian, so we should consider
711       // removing them.
712       "/usr/include/x86_64-linux-gnu/32", "/usr/include/i686-linux-gnu",
713       "/usr/include/i486-linux-gnu"};
714   const StringRef AArch64MultiarchIncludeDirs[] = {
715       "/usr/include/aarch64-linux-gnu"};
716   const StringRef ARMMultiarchIncludeDirs[] = {
717       "/usr/include/arm-linux-gnueabi"};
718   const StringRef ARMHFMultiarchIncludeDirs[] = {
719       "/usr/include/arm-linux-gnueabihf"};
720   const StringRef ARMEBMultiarchIncludeDirs[] = {
721       "/usr/include/armeb-linux-gnueabi"};
722   const StringRef ARMEBHFMultiarchIncludeDirs[] = {
723       "/usr/include/armeb-linux-gnueabihf"};
724   const StringRef MIPSMultiarchIncludeDirs[] = {"/usr/include/mips-linux-gnu"};
725   const StringRef MIPSELMultiarchIncludeDirs[] = {
726       "/usr/include/mipsel-linux-gnu"};
727   const StringRef MIPS64MultiarchIncludeDirs[] = {
728       "/usr/include/mips64-linux-gnuabi64"};
729   const StringRef MIPS64ELMultiarchIncludeDirs[] = {
730       "/usr/include/mips64el-linux-gnuabi64"};
731   const StringRef MIPSN32MultiarchIncludeDirs[] = {
732       "/usr/include/mips64-linux-gnuabin32"};
733   const StringRef MIPSN32ELMultiarchIncludeDirs[] = {
734       "/usr/include/mips64el-linux-gnuabin32"};
735   const StringRef MIPSR6MultiarchIncludeDirs[] = {
736       "/usr/include/mipsisa32-linux-gnu"};
737   const StringRef MIPSR6ELMultiarchIncludeDirs[] = {
738       "/usr/include/mipsisa32r6el-linux-gnu"};
739   const StringRef MIPS64R6MultiarchIncludeDirs[] = {
740       "/usr/include/mipsisa64r6-linux-gnuabi64"};
741   const StringRef MIPS64R6ELMultiarchIncludeDirs[] = {
742       "/usr/include/mipsisa64r6el-linux-gnuabi64"};
743   const StringRef MIPSN32R6MultiarchIncludeDirs[] = {
744       "/usr/include/mipsisa64r6-linux-gnuabin32"};
745   const StringRef MIPSN32R6ELMultiarchIncludeDirs[] = {
746       "/usr/include/mipsisa64r6el-linux-gnuabin32"};
747   const StringRef PPCMultiarchIncludeDirs[] = {
748       "/usr/include/powerpc-linux-gnu",
749       "/usr/include/powerpc-linux-gnuspe"};
750   const StringRef PPC64MultiarchIncludeDirs[] = {
751       "/usr/include/powerpc64-linux-gnu"};
752   const StringRef PPC64LEMultiarchIncludeDirs[] = {
753       "/usr/include/powerpc64le-linux-gnu"};
754   const StringRef SparcMultiarchIncludeDirs[] = {
755       "/usr/include/sparc-linux-gnu"};
756   const StringRef Sparc64MultiarchIncludeDirs[] = {
757       "/usr/include/sparc64-linux-gnu"};
758   const StringRef SYSTEMZMultiarchIncludeDirs[] = {
759       "/usr/include/s390x-linux-gnu"};
760   ArrayRef<StringRef> MultiarchIncludeDirs;
761   switch (getTriple().getArch()) {
762   case llvm::Triple::x86_64:
763     MultiarchIncludeDirs = X86_64MultiarchIncludeDirs;
764     break;
765   case llvm::Triple::x86:
766     MultiarchIncludeDirs = X86MultiarchIncludeDirs;
767     break;
768   case llvm::Triple::aarch64:
769   case llvm::Triple::aarch64_be:
770     MultiarchIncludeDirs = AArch64MultiarchIncludeDirs;
771     break;
772   case llvm::Triple::arm:
773   case llvm::Triple::thumb:
774     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
775       MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs;
776     else
777       MultiarchIncludeDirs = ARMMultiarchIncludeDirs;
778     break;
779   case llvm::Triple::armeb:
780   case llvm::Triple::thumbeb:
781     if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF)
782       MultiarchIncludeDirs = ARMEBHFMultiarchIncludeDirs;
783     else
784       MultiarchIncludeDirs = ARMEBMultiarchIncludeDirs;
785     break;
786   case llvm::Triple::mips:
787     if (getTriple().getSubArch() == llvm::Triple::MipsSubArch_r6)
788       MultiarchIncludeDirs = MIPSR6MultiarchIncludeDirs;
789     else
790       MultiarchIncludeDirs = MIPSMultiarchIncludeDirs;
791     break;
792   case llvm::Triple::mipsel:
793     if (getTriple().getSubArch() == llvm::Triple::MipsSubArch_r6)
794       MultiarchIncludeDirs = MIPSR6ELMultiarchIncludeDirs;
795     else
796       MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs;
797     break;
798   case llvm::Triple::mips64:
799     if (getTriple().getSubArch() == llvm::Triple::MipsSubArch_r6)
800       if (getTriple().getEnvironment() == llvm::Triple::GNUABIN32)
801         MultiarchIncludeDirs = MIPSN32R6MultiarchIncludeDirs;
802       else
803         MultiarchIncludeDirs = MIPS64R6MultiarchIncludeDirs;
804     else if (getTriple().getEnvironment() == llvm::Triple::GNUABIN32)
805       MultiarchIncludeDirs = MIPSN32MultiarchIncludeDirs;
806     else
807       MultiarchIncludeDirs = MIPS64MultiarchIncludeDirs;
808     break;
809   case llvm::Triple::mips64el:
810     if (getTriple().getSubArch() == llvm::Triple::MipsSubArch_r6)
811       if (getTriple().getEnvironment() == llvm::Triple::GNUABIN32)
812         MultiarchIncludeDirs = MIPSN32R6ELMultiarchIncludeDirs;
813       else
814         MultiarchIncludeDirs = MIPS64R6ELMultiarchIncludeDirs;
815     else if (getTriple().getEnvironment() == llvm::Triple::GNUABIN32)
816       MultiarchIncludeDirs = MIPSN32ELMultiarchIncludeDirs;
817     else
818       MultiarchIncludeDirs = MIPS64ELMultiarchIncludeDirs;
819     break;
820   case llvm::Triple::ppc:
821     MultiarchIncludeDirs = PPCMultiarchIncludeDirs;
822     break;
823   case llvm::Triple::ppc64:
824     MultiarchIncludeDirs = PPC64MultiarchIncludeDirs;
825     break;
826   case llvm::Triple::ppc64le:
827     MultiarchIncludeDirs = PPC64LEMultiarchIncludeDirs;
828     break;
829   case llvm::Triple::sparc:
830     MultiarchIncludeDirs = SparcMultiarchIncludeDirs;
831     break;
832   case llvm::Triple::sparcv9:
833     MultiarchIncludeDirs = Sparc64MultiarchIncludeDirs;
834     break;
835   case llvm::Triple::systemz:
836     MultiarchIncludeDirs = SYSTEMZMultiarchIncludeDirs;
837     break;
838   default:
839     break;
840   }
841 
842   const std::string AndroidMultiarchIncludeDir =
843       std::string("/usr/include/") +
844       getMultiarchTriple(D, getTriple(), SysRoot);
845   const StringRef AndroidMultiarchIncludeDirs[] = {AndroidMultiarchIncludeDir};
846   if (getTriple().isAndroid())
847     MultiarchIncludeDirs = AndroidMultiarchIncludeDirs;
848 
849   for (StringRef Dir : MultiarchIncludeDirs) {
850     if (D.getVFS().exists(SysRoot + Dir)) {
851       addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + Dir);
852       break;
853     }
854   }
855 
856   if (getTriple().getOS() == llvm::Triple::RTEMS)
857     return;
858 
859   // Add an include of '/include' directly. This isn't provided by default by
860   // system GCCs, but is often used with cross-compiling GCCs, and harmless to
861   // add even when Clang is acting as-if it were a system compiler.
862   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
863 
864   addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
865 }
866 
867 static std::string DetectLibcxxIncludePath(StringRef base) {
868   std::error_code EC;
869   int MaxVersion = 0;
870   std::string MaxVersionString = "";
871   for (llvm::sys::fs::directory_iterator LI(base, EC), LE; !EC && LI != LE;
872        LI = LI.increment(EC)) {
873     StringRef VersionText = llvm::sys::path::filename(LI->path());
874     int Version;
875     if (VersionText[0] == 'v' &&
876         !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
877       if (Version > MaxVersion) {
878         MaxVersion = Version;
879         MaxVersionString = VersionText;
880       }
881     }
882   }
883   return MaxVersion ? (base + "/" + MaxVersionString).str() : "";
884 }
885 
886 void Linux::addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
887                                   llvm::opt::ArgStringList &CC1Args) const {
888   const std::string& SysRoot = computeSysRoot();
889   const std::string LibCXXIncludePathCandidates[] = {
890       DetectLibcxxIncludePath(getDriver().ResourceDir + "/include/c++"),
891       DetectLibcxxIncludePath(getDriver().Dir + "/../include/c++"),
892       // If this is a development, non-installed, clang, libcxx will
893       // not be found at ../include/c++ but it likely to be found at
894       // one of the following two locations:
895       DetectLibcxxIncludePath(SysRoot + "/usr/local/include/c++"),
896       DetectLibcxxIncludePath(SysRoot + "/usr/include/c++") };
897   for (const auto &IncludePath : LibCXXIncludePathCandidates) {
898     if (IncludePath.empty() || !getVFS().exists(IncludePath))
899       continue;
900     // Use the first candidate that exists.
901     addSystemInclude(DriverArgs, CC1Args, IncludePath);
902     return;
903   }
904 }
905 
906 void Linux::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
907                                      llvm::opt::ArgStringList &CC1Args) const {
908   // We need a detected GCC installation on Linux to provide libstdc++'s
909   // headers.
910   if (!GCCInstallation.isValid())
911     return;
912 
913   // By default, look for the C++ headers in an include directory adjacent to
914   // the lib directory of the GCC installation. Note that this is expect to be
915   // equivalent to '/usr/include/c++/X.Y' in almost all cases.
916   StringRef LibDir = GCCInstallation.getParentLibPath();
917   StringRef InstallDir = GCCInstallation.getInstallPath();
918   StringRef TripleStr = GCCInstallation.getTriple().str();
919   const Multilib &Multilib = GCCInstallation.getMultilib();
920   const std::string GCCMultiarchTriple = getMultiarchTriple(
921       getDriver(), GCCInstallation.getTriple(), getDriver().SysRoot);
922   const std::string TargetMultiarchTriple =
923       getMultiarchTriple(getDriver(), getTriple(), getDriver().SysRoot);
924   const GCCVersion &Version = GCCInstallation.getVersion();
925 
926   // The primary search for libstdc++ supports multiarch variants.
927   if (addLibStdCXXIncludePaths(LibDir.str() + "/../include",
928                                "/c++/" + Version.Text, TripleStr,
929                                GCCMultiarchTriple, TargetMultiarchTriple,
930                                Multilib.includeSuffix(), DriverArgs, CC1Args))
931     return;
932 
933   // Otherwise, fall back on a bunch of options which don't use multiarch
934   // layouts for simplicity.
935   const std::string LibStdCXXIncludePathCandidates[] = {
936       // Gentoo is weird and places its headers inside the GCC install,
937       // so if the first attempt to find the headers fails, try these patterns.
938       InstallDir.str() + "/include/g++-v" + Version.Text,
939       InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." +
940           Version.MinorStr,
941       InstallDir.str() + "/include/g++-v" + Version.MajorStr,
942       // Android standalone toolchain has C++ headers in yet another place.
943       LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.Text,
944       // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++,
945       // without a subdirectory corresponding to the gcc version.
946       LibDir.str() + "/../include/c++",
947       // Cray's gcc installation puts headers under "g++" without a
948       // version suffix.
949       LibDir.str() + "/../include/g++",
950   };
951 
952   for (const auto &IncludePath : LibStdCXXIncludePathCandidates) {
953     if (addLibStdCXXIncludePaths(IncludePath, /*Suffix*/ "", TripleStr,
954                                  /*GCCMultiarchTriple*/ "",
955                                  /*TargetMultiarchTriple*/ "",
956                                  Multilib.includeSuffix(), DriverArgs, CC1Args))
957       break;
958   }
959 }
960 
961 void Linux::AddCudaIncludeArgs(const ArgList &DriverArgs,
962                                ArgStringList &CC1Args) const {
963   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
964 }
965 
966 void Linux::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
967                                 ArgStringList &CC1Args) const {
968   if (GCCInstallation.isValid()) {
969     CC1Args.push_back("-isystem");
970     CC1Args.push_back(DriverArgs.MakeArgString(
971         GCCInstallation.getParentLibPath() + "/../" +
972         GCCInstallation.getTriple().str() + "/include"));
973   }
974 }
975 
976 bool Linux::isPIEDefault() const {
977   return (getTriple().isAndroid() && !getTriple().isAndroidVersionLT(16)) ||
978           getTriple().isMusl() || getSanitizerArgs().requiresPIE();
979 }
980 
981 bool Linux::isNoExecStackDefault() const {
982     return getTriple().isAndroid();
983 }
984 
985 bool Linux::IsMathErrnoDefault() const {
986   if (getTriple().isAndroid())
987     return false;
988   return Generic_ELF::IsMathErrnoDefault();
989 }
990 
991 SanitizerMask Linux::getSupportedSanitizers() const {
992   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
993   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
994   const bool IsMIPS = getTriple().isMIPS32();
995   const bool IsMIPS64 = getTriple().isMIPS64();
996   const bool IsPowerPC64 = getTriple().getArch() == llvm::Triple::ppc64 ||
997                            getTriple().getArch() == llvm::Triple::ppc64le;
998   const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64 ||
999                          getTriple().getArch() == llvm::Triple::aarch64_be;
1000   const bool IsArmArch = getTriple().getArch() == llvm::Triple::arm ||
1001                          getTriple().getArch() == llvm::Triple::thumb ||
1002                          getTriple().getArch() == llvm::Triple::armeb ||
1003                          getTriple().getArch() == llvm::Triple::thumbeb;
1004   SanitizerMask Res = ToolChain::getSupportedSanitizers();
1005   Res |= SanitizerKind::Address;
1006   Res |= SanitizerKind::PointerCompare;
1007   Res |= SanitizerKind::PointerSubtract;
1008   Res |= SanitizerKind::Fuzzer;
1009   Res |= SanitizerKind::FuzzerNoLink;
1010   Res |= SanitizerKind::KernelAddress;
1011   Res |= SanitizerKind::Memory;
1012   Res |= SanitizerKind::Vptr;
1013   Res |= SanitizerKind::SafeStack;
1014   if (IsX86_64 || IsMIPS64 || IsAArch64)
1015     Res |= SanitizerKind::DataFlow;
1016   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsArmArch || IsPowerPC64)
1017     Res |= SanitizerKind::Leak;
1018   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsPowerPC64)
1019     Res |= SanitizerKind::Thread;
1020   if (IsX86_64)
1021     Res |= SanitizerKind::KernelMemory;
1022   if (IsX86 || IsX86_64)
1023     Res |= SanitizerKind::Function;
1024   if (IsX86_64 || IsMIPS64 || IsAArch64 || IsX86 || IsMIPS || IsArmArch ||
1025       IsPowerPC64)
1026     Res |= SanitizerKind::Scudo;
1027   if (IsX86_64 || IsAArch64) {
1028     Res |= SanitizerKind::HWAddress;
1029     Res |= SanitizerKind::KernelHWAddress;
1030   }
1031   return Res;
1032 }
1033 
1034 void Linux::addProfileRTLibs(const llvm::opt::ArgList &Args,
1035                              llvm::opt::ArgStringList &CmdArgs) const {
1036   if (!needsProfileRT(Args)) return;
1037 
1038   // Add linker option -u__llvm_runtime_variable to cause runtime
1039   // initialization module to be linked in.
1040   if ((!Args.hasArg(options::OPT_coverage)) &&
1041       (!Args.hasArg(options::OPT_ftest_coverage)))
1042     CmdArgs.push_back(Args.MakeArgString(
1043         Twine("-u", llvm::getInstrProfRuntimeHookVarName())));
1044   ToolChain::addProfileRTLibs(Args, CmdArgs);
1045 }
1046