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/MultilibBuilder.h"
16#include "clang/Driver/Options.h"
17#include "clang/Driver/SanitizerArgs.h"
18#include "llvm/Option/ArgList.h"
19#include "llvm/ProfileData/InstrProf.h"
20#include "llvm/Support/FileSystem.h"
21#include "llvm/Support/Path.h"
22#include "llvm/Support/VirtualFileSystem.h"
23
24using namespace clang::driver;
25using namespace clang::driver::toolchains;
26using namespace clang::driver::tools;
27using namespace clang;
28using namespace llvm::opt;
29
30using tools::addMultilibFlag;
31
32void fuchsia::Linker::ConstructJob(Compilation &C, const JobAction &JA,
33 const InputInfo &Output,
34 const InputInfoList &Inputs,
35 const ArgList &Args,
36 const char *LinkingOutput) const {
37 const auto &ToolChain = static_cast<const Fuchsia &>(getToolChain());
38 const Driver &D = ToolChain.getDriver();
39
40 const llvm::Triple &Triple = ToolChain.getEffectiveTriple();
41
42 ArgStringList CmdArgs;
43
44 // Silence warning for "clang -g foo.o -o foo"
45 Args.ClaimAllArgs(options::OPT_g_Group);
46 // and "clang -emit-llvm foo.o -o foo"
47 Args.ClaimAllArgs(options::OPT_emit_llvm);
48 // and for "clang -w foo.o -o foo". Other warning options are already
49 // handled somewhere else.
50 Args.ClaimAllArgs(options::OPT_w);
51
52 CmdArgs.push_back(Elt: "-z");
53 CmdArgs.push_back(Elt: "max-page-size=4096");
54
55 CmdArgs.push_back(Elt: "-z");
56 CmdArgs.push_back(Elt: "now");
57
58 CmdArgs.push_back(Elt: "-z");
59 CmdArgs.push_back(Elt: "start-stop-visibility=hidden");
60
61 const char *Exec = Args.MakeArgString(Str: ToolChain.GetLinkerPath());
62 if (llvm::sys::path::filename(path: Exec).equals_insensitive(RHS: "ld.lld") ||
63 llvm::sys::path::stem(path: Exec).equals_insensitive(RHS: "ld.lld")) {
64 CmdArgs.push_back(Elt: "-z");
65 CmdArgs.push_back(Elt: "rodynamic");
66 CmdArgs.push_back(Elt: "-z");
67 CmdArgs.push_back(Elt: "separate-loadable-segments");
68 CmdArgs.push_back(Elt: "-z");
69 CmdArgs.push_back(Elt: "rel");
70 CmdArgs.push_back(Elt: "--pack-dyn-relocs=relr");
71 }
72
73 if (!D.SysRoot.empty())
74 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--sysroot=" + D.SysRoot));
75
76 if (!Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_r))
77 CmdArgs.push_back(Elt: "-pie");
78
79 if (Args.hasArg(options::OPT_rdynamic))
80 CmdArgs.push_back(Elt: "-export-dynamic");
81
82 if (Args.hasArg(options::OPT_s))
83 CmdArgs.push_back(Elt: "-s");
84
85 if (Args.hasArg(options::OPT_r)) {
86 CmdArgs.push_back(Elt: "-r");
87 } else {
88 CmdArgs.push_back(Elt: "--build-id");
89 CmdArgs.push_back(Elt: "--hash-style=gnu");
90 }
91
92 if (ToolChain.getArch() == llvm::Triple::aarch64) {
93 CmdArgs.push_back(Elt: "--execute-only");
94
95 std::string CPU = getCPUName(D, Args, T: Triple);
96 if (CPU.empty() || CPU == "generic" || CPU == "cortex-a53")
97 CmdArgs.push_back(Elt: "--fix-cortex-a53-843419");
98 }
99
100 CmdArgs.push_back(Elt: "--eh-frame-hdr");
101
102 if (Args.hasArg(options::OPT_static))
103 CmdArgs.push_back(Elt: "-Bstatic");
104 else if (Args.hasArg(options::OPT_shared))
105 CmdArgs.push_back(Elt: "-shared");
106
107 const SanitizerArgs &SanArgs = ToolChain.getSanitizerArgs(JobArgs: Args);
108
109 if (!Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_r)) {
110 std::string Dyld = D.DyldPrefix;
111 if (SanArgs.needsAsanRt() && SanArgs.needsSharedRt())
112 Dyld += "asan/";
113 if (SanArgs.needsHwasanRt() && SanArgs.needsSharedRt())
114 Dyld += "hwasan/";
115 if (SanArgs.needsTsanRt() && SanArgs.needsSharedRt())
116 Dyld += "tsan/";
117 Dyld += "ld.so.1";
118 CmdArgs.push_back(Elt: "-dynamic-linker");
119 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Dyld));
120 }
121
122 if (Triple.isRISCV64()) {
123 CmdArgs.push_back(Elt: "-X");
124 if (Args.hasArg(options::OPT_mno_relax))
125 CmdArgs.push_back(Elt: "--no-relax");
126 }
127
128 CmdArgs.push_back(Elt: "-o");
129 CmdArgs.push_back(Elt: Output.getFilename());
130
131 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
132 options::OPT_r)) {
133 if (!Args.hasArg(options::OPT_shared)) {
134 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetFilePath(Name: "Scrt1.o")));
135 }
136 }
137
138 Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_u});
139
140 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
141
142 if (D.isUsingLTO()) {
143 assert(!Inputs.empty() && "Must have at least one input.");
144 // Find the first filename InputInfo object.
145 auto Input = llvm::find_if(
146 Range: Inputs, P: [](const InputInfo &II) -> bool { return II.isFilename(); });
147 if (Input == Inputs.end())
148 // For a very rare case, all of the inputs to the linker are
149 // InputArg. If that happens, just use the first InputInfo.
150 Input = Inputs.begin();
151
152 addLTOOptions(ToolChain, Args, CmdArgs, Output, Input: *Input,
153 IsThinLTO: D.getLTOMode() == LTOK_Thin);
154 }
155
156 addLinkerCompressDebugSectionsOption(TC: ToolChain, Args, CmdArgs);
157 AddLinkerInputs(TC: ToolChain, Inputs, Args, CmdArgs, JA);
158
159 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
160 options::OPT_r)) {
161 if (Args.hasArg(options::OPT_static))
162 CmdArgs.push_back(Elt: "-Bdynamic");
163
164 if (D.CCCIsCXX()) {
165 if (ToolChain.ShouldLinkCXXStdlib(Args)) {
166 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
167 !Args.hasArg(options::OPT_static);
168 CmdArgs.push_back(Elt: "--push-state");
169 CmdArgs.push_back(Elt: "--as-needed");
170 if (OnlyLibstdcxxStatic)
171 CmdArgs.push_back(Elt: "-Bstatic");
172 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
173 if (OnlyLibstdcxxStatic)
174 CmdArgs.push_back(Elt: "-Bdynamic");
175 CmdArgs.push_back(Elt: "-lm");
176 CmdArgs.push_back(Elt: "--pop-state");
177 }
178 }
179
180 // Note that Fuchsia never needs to link in sanitizer runtime deps. Any
181 // sanitizer runtimes with system dependencies use the `.deplibs` feature
182 // instead.
183 addSanitizerRuntimes(TC: ToolChain, Args, CmdArgs);
184
185 addXRayRuntime(TC: ToolChain, Args, CmdArgs);
186
187 ToolChain.addProfileRTLibs(Args, CmdArgs);
188
189 AddRunTimeLibs(TC: ToolChain, D, CmdArgs, Args);
190
191 if (Args.hasArg(options::OPT_pthread) ||
192 Args.hasArg(options::OPT_pthreads))
193 CmdArgs.push_back(Elt: "-lpthread");
194
195 if (Args.hasArg(options::OPT_fsplit_stack))
196 CmdArgs.push_back(Elt: "--wrap=pthread_create");
197
198 if (!Args.hasArg(options::OPT_nolibc))
199 CmdArgs.push_back(Elt: "-lc");
200 }
201
202 C.addCommand(C: std::make_unique<Command>(args: JA, args: *this,
203 args: ResponseFileSupport::AtFileCurCP(),
204 args&: Exec, args&: CmdArgs, args: Inputs, args: Output));
205}
206
207void fuchsia::StaticLibTool::ConstructJob(Compilation &C, const JobAction &JA,
208 const InputInfo &Output,
209 const InputInfoList &Inputs,
210 const ArgList &Args,
211 const char *LinkingOutput) const {
212 const Driver &D = getToolChain().getDriver();
213
214 // Silence warning for "clang -g foo.o -o foo"
215 Args.ClaimAllArgs(options::OPT_g_Group);
216 // and "clang -emit-llvm foo.o -o foo"
217 Args.ClaimAllArgs(options::OPT_emit_llvm);
218 // and for "clang -w foo.o -o foo". Other warning options are already
219 // handled somewhere else.
220 Args.ClaimAllArgs(options::OPT_w);
221 // Silence warnings when linking C code with a C++ '-stdlib' argument.
222 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
223
224 // ar tool command "llvm-ar <options> <output_file> <input_files>".
225 ArgStringList CmdArgs;
226 // Create and insert file members with a deterministic index.
227 CmdArgs.push_back(Elt: "rcsD");
228 CmdArgs.push_back(Elt: Output.getFilename());
229
230 for (const auto &II : Inputs) {
231 if (II.isFilename()) {
232 CmdArgs.push_back(Elt: II.getFilename());
233 }
234 }
235
236 // Delete old output archive file if it already exists before generating a new
237 // archive file.
238 const char *OutputFileName = Output.getFilename();
239 if (Output.isFilename() && llvm::sys::fs::exists(Path: OutputFileName)) {
240 if (std::error_code EC = llvm::sys::fs::remove(path: OutputFileName)) {
241 D.Diag(diag::DiagID: err_drv_unable_to_remove_file) << EC.message();
242 return;
243 }
244 }
245
246 const char *Exec = Args.MakeArgString(Str: getToolChain().GetStaticLibToolPath());
247 C.addCommand(C: std::make_unique<Command>(args: JA, args: *this,
248 args: ResponseFileSupport::AtFileCurCP(),
249 args&: Exec, args&: CmdArgs, args: Inputs, args: Output));
250}
251
252/// Fuchsia - Fuchsia tool chain which can call as(1) and ld(1) directly.
253
254Fuchsia::Fuchsia(const Driver &D, const llvm::Triple &Triple,
255 const ArgList &Args)
256 : ToolChain(D, Triple, Args) {
257 getProgramPaths().push_back(Elt: getDriver().Dir);
258
259 if (!D.SysRoot.empty()) {
260 SmallString<128> P(D.SysRoot);
261 llvm::sys::path::append(path&: P, a: "lib");
262 getFilePaths().push_back(Elt: std::string(P));
263 }
264
265 auto FilePaths = [&](const Multilib &M) -> std::vector<std::string> {
266 std::vector<std::string> FP;
267 if (std::optional<std::string> Path = getStdlibPath()) {
268 SmallString<128> P(*Path);
269 llvm::sys::path::append(path&: P, a: M.gccSuffix());
270 FP.push_back(x: std::string(P));
271 }
272 return FP;
273 };
274
275 Multilibs.push_back(M: Multilib());
276 // Use the noexcept variant with -fno-exceptions to avoid the extra overhead.
277 Multilibs.push_back(M: MultilibBuilder("noexcept", {}, {})
278 .flag(Flag: "-fexceptions", /*Disallow=*/true)
279 .flag(Flag: "-fno-exceptions")
280 .makeMultilib());
281 // ASan has higher priority because we always want the instrumentated version.
282 Multilibs.push_back(M: MultilibBuilder("asan", {}, {})
283 .flag(Flag: "-fsanitize=address")
284 .makeMultilib());
285 // Use the asan+noexcept variant with ASan and -fno-exceptions.
286 Multilibs.push_back(M: MultilibBuilder("asan+noexcept", {}, {})
287 .flag(Flag: "-fsanitize=address")
288 .flag(Flag: "-fexceptions", /*Disallow=*/true)
289 .flag(Flag: "-fno-exceptions")
290 .makeMultilib());
291 // HWASan has higher priority because we always want the instrumentated
292 // version.
293 Multilibs.push_back(M: MultilibBuilder("hwasan", {}, {})
294 .flag(Flag: "-fsanitize=hwaddress")
295 .makeMultilib());
296 // Use the hwasan+noexcept variant with HWASan and -fno-exceptions.
297 Multilibs.push_back(M: MultilibBuilder("hwasan+noexcept", {}, {})
298 .flag(Flag: "-fsanitize=hwaddress")
299 .flag(Flag: "-fexceptions", /*Disallow=*/true)
300 .flag(Flag: "-fno-exceptions")
301 .makeMultilib());
302 // Use Itanium C++ ABI for the compat multilib.
303 Multilibs.push_back(M: MultilibBuilder("compat", {}, {})
304 .flag(Flag: "-fc++-abi=itanium")
305 .makeMultilib());
306
307 Multilibs.FilterOut(F: [&](const Multilib &M) {
308 std::vector<std::string> RD = FilePaths(M);
309 return llvm::all_of(Range&: RD, P: [&](std::string P) { return !getVFS().exists(Path: P); });
310 });
311
312 Multilib::flags_list Flags;
313 bool Exceptions =
314 Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions, true);
315 addMultilibFlag(Enabled: Exceptions, Flag: "-fexceptions", Flags);
316 addMultilibFlag(Enabled: !Exceptions, Flag: "-fno-exceptions", Flags);
317 addMultilibFlag(Enabled: getSanitizerArgs(JobArgs: Args).needsAsanRt(), Flag: "-fsanitize=address",
318 Flags);
319 addMultilibFlag(Enabled: getSanitizerArgs(JobArgs: Args).needsHwasanRt(),
320 Flag: "-fsanitize=hwaddress", Flags);
321
322 addMultilibFlag(Args.getLastArgValue(options::Id: OPT_fcxx_abi_EQ) == "itanium",
323 "-fc++-abi=itanium", Flags);
324
325 Multilibs.setFilePathsCallback(FilePaths);
326
327 if (Multilibs.select(Flags, SelectedMultilibs)) {
328 // Ensure that -print-multi-directory only outputs one multilib directory.
329 Multilib LastSelected = SelectedMultilibs.back();
330 SelectedMultilibs = {LastSelected};
331
332 if (!SelectedMultilibs.back().isDefault())
333 if (const auto &PathsCallback = Multilibs.filePathsCallback())
334 for (const auto &Path : PathsCallback(SelectedMultilibs.back()))
335 // Prepend the multilib path to ensure it takes the precedence.
336 getFilePaths().insert(I: getFilePaths().begin(), Elt: Path);
337 }
338}
339
340std::string Fuchsia::ComputeEffectiveClangTriple(const ArgList &Args,
341 types::ID InputType) const {
342 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
343 return Triple.str();
344}
345
346Tool *Fuchsia::buildLinker() const {
347 return new tools::fuchsia::Linker(*this);
348}
349
350Tool *Fuchsia::buildStaticLibTool() const {
351 return new tools::fuchsia::StaticLibTool(*this);
352}
353
354ToolChain::RuntimeLibType Fuchsia::GetRuntimeLibType(
355 const ArgList &Args) const {
356 if (Arg *A = Args.getLastArg(clang::driver::options::OPT_rtlib_EQ)) {
357 StringRef Value = A->getValue();
358 if (Value != "compiler-rt")
359 getDriver().Diag(clang::diag::DiagID: err_drv_invalid_rtlib_name)
360 << A->getAsString(Args);
361 }
362
363 return ToolChain::RLT_CompilerRT;
364}
365
366ToolChain::CXXStdlibType
367Fuchsia::GetCXXStdlibType(const ArgList &Args) const {
368 if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
369 StringRef Value = A->getValue();
370 if (Value != "libc++")
371 getDriver().Diag(diag::DiagID: err_drv_invalid_stdlib_name)
372 << A->getAsString(Args);
373 }
374
375 return ToolChain::CST_Libcxx;
376}
377
378void Fuchsia::addClangTargetOptions(const ArgList &DriverArgs,
379 ArgStringList &CC1Args,
380 Action::OffloadKind) const {
381 if (!DriverArgs.hasFlag(options::OPT_fuse_init_array,
382 options::OPT_fno_use_init_array, true))
383 CC1Args.push_back(Elt: "-fno-use-init-array");
384}
385
386void Fuchsia::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
387 ArgStringList &CC1Args) const {
388 const Driver &D = getDriver();
389
390 if (DriverArgs.hasArg(options::OPT_nostdinc))
391 return;
392
393 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
394 SmallString<128> P(D.ResourceDir);
395 llvm::sys::path::append(path&: P, a: "include");
396 addSystemInclude(DriverArgs, CC1Args, Path: P);
397 }
398
399 if (DriverArgs.hasArg(options::OPT_nostdlibinc))
400 return;
401
402 // Check for configure-time C include directories.
403 StringRef CIncludeDirs(C_INCLUDE_DIRS);
404 if (CIncludeDirs != "") {
405 SmallVector<StringRef, 5> dirs;
406 CIncludeDirs.split(A&: dirs, Separator: ":");
407 for (StringRef dir : dirs) {
408 StringRef Prefix =
409 llvm::sys::path::is_absolute(path: dir) ? "" : StringRef(D.SysRoot);
410 addExternCSystemInclude(DriverArgs, CC1Args, Path: Prefix + dir);
411 }
412 return;
413 }
414
415 if (!D.SysRoot.empty()) {
416 SmallString<128> P(D.SysRoot);
417 llvm::sys::path::append(path&: P, a: "include");
418 addExternCSystemInclude(DriverArgs, CC1Args, Path: P.str());
419 }
420}
421
422void Fuchsia::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
423 ArgStringList &CC1Args) const {
424 if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdlibinc,
425 options::OPT_nostdincxx))
426 return;
427
428 const Driver &D = getDriver();
429 std::string Target = getTripleString();
430
431 auto AddCXXIncludePath = [&](StringRef Path) {
432 std::string Version = detectLibcxxVersion(IncludePath: Path);
433 if (Version.empty())
434 return;
435
436 // First add the per-target include path.
437 SmallString<128> TargetDir(Path);
438 llvm::sys::path::append(path&: TargetDir, a: Target, b: "c++", c: Version);
439 if (getVFS().exists(Path: TargetDir))
440 addSystemInclude(DriverArgs, CC1Args, Path: TargetDir);
441
442 // Second add the generic one.
443 SmallString<128> Dir(Path);
444 llvm::sys::path::append(path&: Dir, a: "c++", b: Version);
445 addSystemInclude(DriverArgs, CC1Args, Path: Dir);
446 };
447
448 switch (GetCXXStdlibType(Args: DriverArgs)) {
449 case ToolChain::CST_Libcxx: {
450 SmallString<128> P(D.Dir);
451 llvm::sys::path::append(path&: P, a: "..", b: "include");
452 AddCXXIncludePath(P);
453 break;
454 }
455
456 default:
457 llvm_unreachable("invalid stdlib name");
458 }
459}
460
461void Fuchsia::AddCXXStdlibLibArgs(const ArgList &Args,
462 ArgStringList &CmdArgs) const {
463 switch (GetCXXStdlibType(Args)) {
464 case ToolChain::CST_Libcxx:
465 CmdArgs.push_back(Elt: "-lc++");
466 if (Args.hasArg(options::OPT_fexperimental_library))
467 CmdArgs.push_back(Elt: "-lc++experimental");
468 break;
469
470 case ToolChain::CST_Libstdcxx:
471 llvm_unreachable("invalid stdlib name");
472 }
473}
474
475SanitizerMask Fuchsia::getSupportedSanitizers() const {
476 SanitizerMask Res = ToolChain::getSupportedSanitizers();
477 Res |= SanitizerKind::Address;
478 Res |= SanitizerKind::HWAddress;
479 Res |= SanitizerKind::PointerCompare;
480 Res |= SanitizerKind::PointerSubtract;
481 Res |= SanitizerKind::Fuzzer;
482 Res |= SanitizerKind::FuzzerNoLink;
483 Res |= SanitizerKind::Leak;
484 Res |= SanitizerKind::SafeStack;
485 Res |= SanitizerKind::Scudo;
486 Res |= SanitizerKind::Thread;
487 return Res;
488}
489
490SanitizerMask Fuchsia::getDefaultSanitizers() const {
491 SanitizerMask Res;
492 switch (getTriple().getArch()) {
493 case llvm::Triple::aarch64:
494 case llvm::Triple::riscv64:
495 Res |= SanitizerKind::ShadowCallStack;
496 break;
497 case llvm::Triple::x86_64:
498 Res |= SanitizerKind::SafeStack;
499 break;
500 default:
501 break;
502 }
503 return Res;
504}
505

source code of clang/lib/Driver/ToolChains/Fuchsia.cpp