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