xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/Fuchsia.cpp (revision c7a063741720ef81d4caa4613242579d12f1d605)
1 //===--- Fuchsia.cpp - Fuchsia 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 "Fuchsia.h"
10 #include "CommonArgs.h"
11 #include "clang/Config/config.h"
12 #include "clang/Driver/Compilation.h"
13 #include "clang/Driver/Driver.h"
14 #include "clang/Driver/DriverDiagnostic.h"
15 #include "clang/Driver/Options.h"
16 #include "clang/Driver/SanitizerArgs.h"
17 #include "llvm/Option/ArgList.h"
18 #include "llvm/ProfileData/InstrProf.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/VirtualFileSystem.h"
22 
23 using namespace clang::driver;
24 using namespace clang::driver::toolchains;
25 using namespace clang::driver::tools;
26 using namespace clang;
27 using namespace llvm::opt;
28 
29 using tools::addMultilibFlag;
30 
31 void fuchsia::Linker::ConstructJob(Compilation &C, const JobAction &JA,
32                                    const InputInfo &Output,
33                                    const InputInfoList &Inputs,
34                                    const ArgList &Args,
35                                    const char *LinkingOutput) const {
36   const toolchains::Fuchsia &ToolChain =
37       static_cast<const toolchains::Fuchsia &>(getToolChain());
38   const Driver &D = ToolChain.getDriver();
39 
40   ArgStringList CmdArgs;
41 
42   // Silence warning for "clang -g foo.o -o foo"
43   Args.ClaimAllArgs(options::OPT_g_Group);
44   // and "clang -emit-llvm foo.o -o foo"
45   Args.ClaimAllArgs(options::OPT_emit_llvm);
46   // and for "clang -w foo.o -o foo". Other warning options are already
47   // handled somewhere else.
48   Args.ClaimAllArgs(options::OPT_w);
49 
50   CmdArgs.push_back("-z");
51   CmdArgs.push_back("max-page-size=4096");
52 
53   CmdArgs.push_back("-z");
54   CmdArgs.push_back("now");
55 
56   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
57   if (llvm::sys::path::filename(Exec).equals_insensitive("ld.lld") ||
58       llvm::sys::path::stem(Exec).equals_insensitive("ld.lld")) {
59     CmdArgs.push_back("-z");
60     CmdArgs.push_back("rodynamic");
61     CmdArgs.push_back("-z");
62     CmdArgs.push_back("separate-loadable-segments");
63     CmdArgs.push_back("-z");
64     CmdArgs.push_back("rel");
65     CmdArgs.push_back("--pack-dyn-relocs=relr");
66   }
67 
68   if (!D.SysRoot.empty())
69     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
70 
71   if (!Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_r))
72     CmdArgs.push_back("-pie");
73 
74   if (Args.hasArg(options::OPT_rdynamic))
75     CmdArgs.push_back("-export-dynamic");
76 
77   if (Args.hasArg(options::OPT_s))
78     CmdArgs.push_back("-s");
79 
80   if (Args.hasArg(options::OPT_r)) {
81     CmdArgs.push_back("-r");
82   } else {
83     CmdArgs.push_back("--build-id");
84     CmdArgs.push_back("--hash-style=gnu");
85   }
86 
87   CmdArgs.push_back("--eh-frame-hdr");
88 
89   if (Args.hasArg(options::OPT_static))
90     CmdArgs.push_back("-Bstatic");
91   else if (Args.hasArg(options::OPT_shared))
92     CmdArgs.push_back("-shared");
93 
94   const SanitizerArgs &SanArgs = ToolChain.getSanitizerArgs(Args);
95 
96   if (!Args.hasArg(options::OPT_shared)) {
97     std::string Dyld = D.DyldPrefix;
98     if (SanArgs.needsAsanRt() && SanArgs.needsSharedRt())
99       Dyld += "asan/";
100     if (SanArgs.needsHwasanRt() && SanArgs.needsSharedRt())
101       Dyld += "hwasan/";
102     if (SanArgs.needsTsanRt() && SanArgs.needsSharedRt())
103       Dyld += "tsan/";
104     Dyld += "ld.so.1";
105     CmdArgs.push_back("-dynamic-linker");
106     CmdArgs.push_back(Args.MakeArgString(Dyld));
107   }
108 
109   CmdArgs.push_back("-o");
110   CmdArgs.push_back(Output.getFilename());
111 
112   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
113                    options::OPT_r)) {
114     if (!Args.hasArg(options::OPT_shared)) {
115       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("Scrt1.o")));
116     }
117   }
118 
119   Args.AddAllArgs(CmdArgs, options::OPT_L);
120   Args.AddAllArgs(CmdArgs, options::OPT_u);
121 
122   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
123 
124   if (D.isUsingLTO()) {
125     assert(!Inputs.empty() && "Must have at least one input.");
126     addLTOOptions(ToolChain, Args, CmdArgs, Output, Inputs[0],
127                   D.getLTOMode() == LTOK_Thin);
128   }
129 
130   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
131   bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
132   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
133   ToolChain.addProfileRTLibs(Args, CmdArgs);
134 
135   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
136                    options::OPT_r)) {
137     if (Args.hasArg(options::OPT_static))
138       CmdArgs.push_back("-Bdynamic");
139 
140     if (D.CCCIsCXX()) {
141       if (ToolChain.ShouldLinkCXXStdlib(Args)) {
142         bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
143                                    !Args.hasArg(options::OPT_static);
144         CmdArgs.push_back("--push-state");
145         CmdArgs.push_back("--as-needed");
146         if (OnlyLibstdcxxStatic)
147           CmdArgs.push_back("-Bstatic");
148         ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
149         if (OnlyLibstdcxxStatic)
150           CmdArgs.push_back("-Bdynamic");
151         CmdArgs.push_back("-lm");
152         CmdArgs.push_back("--pop-state");
153       }
154     }
155 
156     if (NeedsSanitizerDeps)
157       linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
158 
159     if (NeedsXRayDeps)
160       linkXRayRuntimeDeps(ToolChain, CmdArgs);
161 
162     AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
163 
164     if (Args.hasArg(options::OPT_pthread) ||
165         Args.hasArg(options::OPT_pthreads))
166       CmdArgs.push_back("-lpthread");
167 
168     if (Args.hasArg(options::OPT_fsplit_stack))
169       CmdArgs.push_back("--wrap=pthread_create");
170 
171     if (!Args.hasArg(options::OPT_nolibc))
172       CmdArgs.push_back("-lc");
173   }
174 
175   C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
176                                          Exec, CmdArgs, Inputs, Output));
177 }
178 
179 /// Fuchsia - Fuchsia tool chain which can call as(1) and ld(1) directly.
180 
181 Fuchsia::Fuchsia(const Driver &D, const llvm::Triple &Triple,
182                  const ArgList &Args)
183     : ToolChain(D, Triple, Args) {
184   getProgramPaths().push_back(getDriver().getInstalledDir());
185   if (getDriver().getInstalledDir() != D.Dir)
186     getProgramPaths().push_back(D.Dir);
187 
188   if (!D.SysRoot.empty()) {
189     SmallString<128> P(D.SysRoot);
190     llvm::sys::path::append(P, "lib");
191     getFilePaths().push_back(std::string(P.str()));
192   }
193 
194   auto FilePaths = [&](const Multilib &M) -> std::vector<std::string> {
195     std::vector<std::string> FP;
196     for (const std::string &Path : getStdlibPaths()) {
197       SmallString<128> P(Path);
198       llvm::sys::path::append(P, M.gccSuffix());
199       FP.push_back(std::string(P.str()));
200     }
201     return FP;
202   };
203 
204   Multilibs.push_back(Multilib());
205   // Use the noexcept variant with -fno-exceptions to avoid the extra overhead.
206   Multilibs.push_back(Multilib("noexcept", {}, {}, 1)
207                           .flag("-fexceptions")
208                           .flag("+fno-exceptions"));
209   // ASan has higher priority because we always want the instrumentated version.
210   Multilibs.push_back(Multilib("asan", {}, {}, 2)
211                           .flag("+fsanitize=address"));
212   // Use the asan+noexcept variant with ASan and -fno-exceptions.
213   Multilibs.push_back(Multilib("asan+noexcept", {}, {}, 3)
214                           .flag("+fsanitize=address")
215                           .flag("-fexceptions")
216                           .flag("+fno-exceptions"));
217   // HWASan has higher priority because we always want the instrumentated
218   // version.
219   Multilibs.push_back(
220       Multilib("hwasan", {}, {}, 4).flag("+fsanitize=hwaddress"));
221   // Use the hwasan+noexcept variant with HWASan and -fno-exceptions.
222   Multilibs.push_back(Multilib("hwasan+noexcept", {}, {}, 5)
223                           .flag("+fsanitize=hwaddress")
224                           .flag("-fexceptions")
225                           .flag("+fno-exceptions"));
226   // Use the relative vtables ABI.
227   // TODO: Remove these multilibs once relative vtables are enabled by default
228   // for Fuchsia.
229   Multilibs.push_back(Multilib("relative-vtables", {}, {}, 6)
230                           .flag("+fexperimental-relative-c++-abi-vtables"));
231   Multilibs.push_back(Multilib("relative-vtables+noexcept", {}, {}, 7)
232                           .flag("+fexperimental-relative-c++-abi-vtables")
233                           .flag("-fexceptions")
234                           .flag("+fno-exceptions"));
235   Multilibs.push_back(Multilib("relative-vtables+asan", {}, {}, 8)
236                           .flag("+fexperimental-relative-c++-abi-vtables")
237                           .flag("+fsanitize=address"));
238   Multilibs.push_back(Multilib("relative-vtables+asan+noexcept", {}, {}, 9)
239                           .flag("+fexperimental-relative-c++-abi-vtables")
240                           .flag("+fsanitize=address")
241                           .flag("-fexceptions")
242                           .flag("+fno-exceptions"));
243   Multilibs.push_back(Multilib("relative-vtables+hwasan", {}, {}, 10)
244                           .flag("+fexperimental-relative-c++-abi-vtables")
245                           .flag("+fsanitize=hwaddress"));
246   Multilibs.push_back(Multilib("relative-vtables+hwasan+noexcept", {}, {}, 11)
247                           .flag("+fexperimental-relative-c++-abi-vtables")
248                           .flag("+fsanitize=hwaddress")
249                           .flag("-fexceptions")
250                           .flag("+fno-exceptions"));
251   // Use Itanium C++ ABI for the compat multilib.
252   Multilibs.push_back(Multilib("compat", {}, {}, 12).flag("+fc++-abi=itanium"));
253 
254   Multilibs.FilterOut([&](const Multilib &M) {
255     std::vector<std::string> RD = FilePaths(M);
256     return llvm::all_of(RD, [&](std::string P) { return !getVFS().exists(P); });
257   });
258 
259   Multilib::flags_list Flags;
260   addMultilibFlag(
261       Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions, true),
262       "fexceptions", Flags);
263   addMultilibFlag(getSanitizerArgs(Args).needsAsanRt(), "fsanitize=address",
264                   Flags);
265   addMultilibFlag(getSanitizerArgs(Args).needsHwasanRt(), "fsanitize=hwaddress",
266                   Flags);
267 
268   addMultilibFlag(
269       Args.hasFlag(options::OPT_fexperimental_relative_cxx_abi_vtables,
270                    options::OPT_fno_experimental_relative_cxx_abi_vtables,
271                    /*default=*/false),
272       "fexperimental-relative-c++-abi-vtables", Flags);
273   addMultilibFlag(Args.getLastArgValue(options::OPT_fcxx_abi_EQ) == "itanium",
274                   "fc++-abi=itanium", Flags);
275 
276   Multilibs.setFilePathsCallback(FilePaths);
277 
278   if (Multilibs.select(Flags, SelectedMultilib))
279     if (!SelectedMultilib.isDefault())
280       if (const auto &PathsCallback = Multilibs.filePathsCallback())
281         for (const auto &Path : PathsCallback(SelectedMultilib))
282           // Prepend the multilib path to ensure it takes the precedence.
283           getFilePaths().insert(getFilePaths().begin(), Path);
284 }
285 
286 std::string Fuchsia::ComputeEffectiveClangTriple(const ArgList &Args,
287                                                  types::ID InputType) const {
288   llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
289   return Triple.str();
290 }
291 
292 Tool *Fuchsia::buildLinker() const {
293   return new tools::fuchsia::Linker(*this);
294 }
295 
296 ToolChain::RuntimeLibType Fuchsia::GetRuntimeLibType(
297     const ArgList &Args) const {
298   if (Arg *A = Args.getLastArg(clang::driver::options::OPT_rtlib_EQ)) {
299     StringRef Value = A->getValue();
300     if (Value != "compiler-rt")
301       getDriver().Diag(clang::diag::err_drv_invalid_rtlib_name)
302           << A->getAsString(Args);
303   }
304 
305   return ToolChain::RLT_CompilerRT;
306 }
307 
308 ToolChain::CXXStdlibType
309 Fuchsia::GetCXXStdlibType(const ArgList &Args) const {
310   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
311     StringRef Value = A->getValue();
312     if (Value != "libc++")
313       getDriver().Diag(diag::err_drv_invalid_stdlib_name)
314         << A->getAsString(Args);
315   }
316 
317   return ToolChain::CST_Libcxx;
318 }
319 
320 void Fuchsia::addClangTargetOptions(const ArgList &DriverArgs,
321                                     ArgStringList &CC1Args,
322                                     Action::OffloadKind) const {
323   if (!DriverArgs.hasFlag(options::OPT_fuse_init_array,
324                           options::OPT_fno_use_init_array, true))
325     CC1Args.push_back("-fno-use-init-array");
326 }
327 
328 void Fuchsia::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
329                                         ArgStringList &CC1Args) const {
330   const Driver &D = getDriver();
331 
332   if (DriverArgs.hasArg(options::OPT_nostdinc))
333     return;
334 
335   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
336     SmallString<128> P(D.ResourceDir);
337     llvm::sys::path::append(P, "include");
338     addSystemInclude(DriverArgs, CC1Args, P);
339   }
340 
341   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
342     return;
343 
344   // Check for configure-time C include directories.
345   StringRef CIncludeDirs(C_INCLUDE_DIRS);
346   if (CIncludeDirs != "") {
347     SmallVector<StringRef, 5> dirs;
348     CIncludeDirs.split(dirs, ":");
349     for (StringRef dir : dirs) {
350       StringRef Prefix =
351           llvm::sys::path::is_absolute(dir) ? "" : StringRef(D.SysRoot);
352       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
353     }
354     return;
355   }
356 
357   if (!D.SysRoot.empty()) {
358     SmallString<128> P(D.SysRoot);
359     llvm::sys::path::append(P, "include");
360     addExternCSystemInclude(DriverArgs, CC1Args, P.str());
361   }
362 }
363 
364 void Fuchsia::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
365                                            ArgStringList &CC1Args) const {
366   if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
367       DriverArgs.hasArg(options::OPT_nostdincxx))
368     return;
369 
370   const Driver &D = getDriver();
371   std::string Target = getTripleString();
372 
373   auto AddCXXIncludePath = [&](StringRef Path) {
374     std::string Version = detectLibcxxVersion(Path);
375     if (Version.empty())
376       return;
377 
378     // First add the per-target include path.
379     SmallString<128> TargetDir(Path);
380     llvm::sys::path::append(TargetDir, Target, "c++", Version);
381     if (getVFS().exists(TargetDir))
382       addSystemInclude(DriverArgs, CC1Args, TargetDir);
383 
384     // Second add the generic one.
385     SmallString<128> Dir(Path);
386     llvm::sys::path::append(Dir, "c++", Version);
387     addSystemInclude(DriverArgs, CC1Args, Dir);
388   };
389 
390   switch (GetCXXStdlibType(DriverArgs)) {
391   case ToolChain::CST_Libcxx: {
392     SmallString<128> P(D.Dir);
393     llvm::sys::path::append(P, "..", "include");
394     AddCXXIncludePath(P);
395     break;
396   }
397 
398   default:
399     llvm_unreachable("invalid stdlib name");
400   }
401 }
402 
403 void Fuchsia::AddCXXStdlibLibArgs(const ArgList &Args,
404                                   ArgStringList &CmdArgs) const {
405   switch (GetCXXStdlibType(Args)) {
406   case ToolChain::CST_Libcxx:
407     CmdArgs.push_back("-lc++");
408     break;
409 
410   case ToolChain::CST_Libstdcxx:
411     llvm_unreachable("invalid stdlib name");
412   }
413 }
414 
415 SanitizerMask Fuchsia::getSupportedSanitizers() const {
416   SanitizerMask Res = ToolChain::getSupportedSanitizers();
417   Res |= SanitizerKind::Address;
418   Res |= SanitizerKind::HWAddress;
419   Res |= SanitizerKind::PointerCompare;
420   Res |= SanitizerKind::PointerSubtract;
421   Res |= SanitizerKind::Fuzzer;
422   Res |= SanitizerKind::FuzzerNoLink;
423   Res |= SanitizerKind::Leak;
424   Res |= SanitizerKind::SafeStack;
425   Res |= SanitizerKind::Scudo;
426   Res |= SanitizerKind::Thread;
427   return Res;
428 }
429 
430 SanitizerMask Fuchsia::getDefaultSanitizers() const {
431   SanitizerMask Res;
432   switch (getTriple().getArch()) {
433   case llvm::Triple::aarch64:
434     Res |= SanitizerKind::ShadowCallStack;
435     break;
436   case llvm::Triple::x86_64:
437     Res |= SanitizerKind::SafeStack;
438     break;
439   default:
440     // TODO: Enable SafeStack on RISC-V once tested.
441     break;
442   }
443   return Res;
444 }
445