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