1 //===--- SanitizerArgs.cpp - Arguments for sanitizer tools ---------------===// 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 #include "clang/Driver/SanitizerArgs.h" 9 #include "ToolChains/CommonArgs.h" 10 #include "clang/Basic/Sanitizers.h" 11 #include "clang/Driver/Driver.h" 12 #include "clang/Driver/DriverDiagnostic.h" 13 #include "clang/Driver/Options.h" 14 #include "clang/Driver/ToolChain.h" 15 #include "llvm/ADT/StringExtras.h" 16 #include "llvm/ADT/StringSwitch.h" 17 #include "llvm/Support/FileSystem.h" 18 #include "llvm/Support/Path.h" 19 #include "llvm/Support/SpecialCaseList.h" 20 #include "llvm/Support/TargetParser.h" 21 #include <memory> 22 23 using namespace clang; 24 using namespace clang::driver; 25 using namespace llvm::opt; 26 27 static const SanitizerMask NeedsUbsanRt = 28 SanitizerKind::Undefined | SanitizerKind::Integer | 29 SanitizerKind::ImplicitConversion | SanitizerKind::Nullability | 30 SanitizerKind::CFI | SanitizerKind::FloatDivideByZero; 31 static const SanitizerMask NeedsUbsanCxxRt = 32 SanitizerKind::Vptr | SanitizerKind::CFI; 33 static const SanitizerMask NotAllowedWithTrap = SanitizerKind::Vptr; 34 static const SanitizerMask NotAllowedWithMinimalRuntime = 35 SanitizerKind::Function | SanitizerKind::Vptr; 36 static const SanitizerMask RequiresPIE = 37 SanitizerKind::DataFlow | SanitizerKind::HWAddress | SanitizerKind::Scudo; 38 static const SanitizerMask NeedsUnwindTables = 39 SanitizerKind::Address | SanitizerKind::HWAddress | SanitizerKind::Thread | 40 SanitizerKind::Memory | SanitizerKind::DataFlow; 41 static const SanitizerMask SupportsCoverage = 42 SanitizerKind::Address | SanitizerKind::HWAddress | 43 SanitizerKind::KernelAddress | SanitizerKind::KernelHWAddress | 44 SanitizerKind::MemTag | SanitizerKind::Memory | 45 SanitizerKind::KernelMemory | SanitizerKind::Leak | 46 SanitizerKind::Undefined | SanitizerKind::Integer | 47 SanitizerKind::ImplicitConversion | SanitizerKind::Nullability | 48 SanitizerKind::DataFlow | SanitizerKind::Fuzzer | 49 SanitizerKind::FuzzerNoLink | SanitizerKind::FloatDivideByZero | 50 SanitizerKind::SafeStack | SanitizerKind::ShadowCallStack; 51 static const SanitizerMask RecoverableByDefault = 52 SanitizerKind::Undefined | SanitizerKind::Integer | 53 SanitizerKind::ImplicitConversion | SanitizerKind::Nullability | 54 SanitizerKind::FloatDivideByZero; 55 static const SanitizerMask Unrecoverable = 56 SanitizerKind::Unreachable | SanitizerKind::Return; 57 static const SanitizerMask AlwaysRecoverable = 58 SanitizerKind::KernelAddress | SanitizerKind::KernelHWAddress; 59 static const SanitizerMask LegacyFsanitizeRecoverMask = 60 SanitizerKind::Undefined | SanitizerKind::Integer; 61 static const SanitizerMask NeedsLTO = SanitizerKind::CFI; 62 static const SanitizerMask TrappingSupported = 63 (SanitizerKind::Undefined & ~SanitizerKind::Vptr) | 64 SanitizerKind::UnsignedIntegerOverflow | SanitizerKind::ImplicitConversion | 65 SanitizerKind::Nullability | SanitizerKind::LocalBounds | 66 SanitizerKind::CFI | SanitizerKind::FloatDivideByZero; 67 static const SanitizerMask TrappingDefault = SanitizerKind::CFI; 68 static const SanitizerMask CFIClasses = 69 SanitizerKind::CFIVCall | SanitizerKind::CFINVCall | 70 SanitizerKind::CFIMFCall | SanitizerKind::CFIDerivedCast | 71 SanitizerKind::CFIUnrelatedCast; 72 static const SanitizerMask CompatibleWithMinimalRuntime = 73 TrappingSupported | SanitizerKind::Scudo | SanitizerKind::ShadowCallStack; 74 75 enum CoverageFeature { 76 CoverageFunc = 1 << 0, 77 CoverageBB = 1 << 1, 78 CoverageEdge = 1 << 2, 79 CoverageIndirCall = 1 << 3, 80 CoverageTraceBB = 1 << 4, // Deprecated. 81 CoverageTraceCmp = 1 << 5, 82 CoverageTraceDiv = 1 << 6, 83 CoverageTraceGep = 1 << 7, 84 Coverage8bitCounters = 1 << 8, // Deprecated. 85 CoverageTracePC = 1 << 9, 86 CoverageTracePCGuard = 1 << 10, 87 CoverageNoPrune = 1 << 11, 88 CoverageInline8bitCounters = 1 << 12, 89 CoveragePCTable = 1 << 13, 90 CoverageStackDepth = 1 << 14, 91 }; 92 93 /// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any 94 /// invalid components. Returns a SanitizerMask. 95 static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A, 96 bool DiagnoseErrors); 97 98 /// Parse -f(no-)?sanitize-coverage= flag values, diagnosing any invalid 99 /// components. Returns OR of members of \c CoverageFeature enumeration. 100 static int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A); 101 102 /// Produce an argument string from ArgList \p Args, which shows how it 103 /// provides some sanitizer kind from \p Mask. For example, the argument list 104 /// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt 105 /// would produce "-fsanitize=vptr". 106 static std::string lastArgumentForMask(const Driver &D, 107 const llvm::opt::ArgList &Args, 108 SanitizerMask Mask); 109 110 /// Produce an argument string from argument \p A, which shows how it provides 111 /// a value in \p Mask. For instance, the argument 112 /// "-fsanitize=address,alignment" with mask \c NeedsUbsanRt would produce 113 /// "-fsanitize=alignment". 114 static std::string describeSanitizeArg(const llvm::opt::Arg *A, 115 SanitizerMask Mask); 116 117 /// Produce a string containing comma-separated names of sanitizers in \p 118 /// Sanitizers set. 119 static std::string toString(const clang::SanitizerSet &Sanitizers); 120 121 static void addDefaultBlacklists(const Driver &D, SanitizerMask Kinds, 122 std::vector<std::string> &BlacklistFiles) { 123 struct Blacklist { 124 const char *File; 125 SanitizerMask Mask; 126 } Blacklists[] = {{"asan_blacklist.txt", SanitizerKind::Address}, 127 {"hwasan_blacklist.txt", SanitizerKind::HWAddress}, 128 {"memtag_blacklist.txt", SanitizerKind::MemTag}, 129 {"msan_blacklist.txt", SanitizerKind::Memory}, 130 {"tsan_blacklist.txt", SanitizerKind::Thread}, 131 {"dfsan_abilist.txt", SanitizerKind::DataFlow}, 132 {"cfi_blacklist.txt", SanitizerKind::CFI}, 133 {"ubsan_blacklist.txt", 134 SanitizerKind::Undefined | SanitizerKind::Integer | 135 SanitizerKind::Nullability | 136 SanitizerKind::FloatDivideByZero}}; 137 138 for (auto BL : Blacklists) { 139 if (!(Kinds & BL.Mask)) 140 continue; 141 142 clang::SmallString<64> Path(D.ResourceDir); 143 llvm::sys::path::append(Path, "share", BL.File); 144 if (D.getVFS().exists(Path)) 145 BlacklistFiles.push_back(Path.str()); 146 else if (BL.Mask == SanitizerKind::CFI) 147 // If cfi_blacklist.txt cannot be found in the resource dir, driver 148 // should fail. 149 D.Diag(clang::diag::err_drv_no_such_file) << Path; 150 } 151 } 152 153 /// Sets group bits for every group that has at least one representative already 154 /// enabled in \p Kinds. 155 static SanitizerMask setGroupBits(SanitizerMask Kinds) { 156 #define SANITIZER(NAME, ID) 157 #define SANITIZER_GROUP(NAME, ID, ALIAS) \ 158 if (Kinds & SanitizerKind::ID) \ 159 Kinds |= SanitizerKind::ID##Group; 160 #include "clang/Basic/Sanitizers.def" 161 return Kinds; 162 } 163 164 static SanitizerMask parseSanitizeTrapArgs(const Driver &D, 165 const llvm::opt::ArgList &Args) { 166 SanitizerMask TrapRemove; // During the loop below, the accumulated set of 167 // sanitizers disabled by the current sanitizer 168 // argument or any argument after it. 169 SanitizerMask TrappingKinds; 170 SanitizerMask TrappingSupportedWithGroups = setGroupBits(TrappingSupported); 171 172 for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend(); 173 I != E; ++I) { 174 const auto *Arg = *I; 175 if (Arg->getOption().matches(options::OPT_fsanitize_trap_EQ)) { 176 Arg->claim(); 177 SanitizerMask Add = parseArgValues(D, Arg, true); 178 Add &= ~TrapRemove; 179 if (SanitizerMask InvalidValues = Add & ~TrappingSupportedWithGroups) { 180 SanitizerSet S; 181 S.Mask = InvalidValues; 182 D.Diag(diag::err_drv_unsupported_option_argument) << "-fsanitize-trap" 183 << toString(S); 184 } 185 TrappingKinds |= expandSanitizerGroups(Add) & ~TrapRemove; 186 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) { 187 Arg->claim(); 188 TrapRemove |= expandSanitizerGroups(parseArgValues(D, Arg, true)); 189 } else if (Arg->getOption().matches( 190 options::OPT_fsanitize_undefined_trap_on_error)) { 191 Arg->claim(); 192 TrappingKinds |= 193 expandSanitizerGroups(SanitizerKind::UndefinedGroup & ~TrapRemove) & 194 ~TrapRemove; 195 } else if (Arg->getOption().matches( 196 options::OPT_fno_sanitize_undefined_trap_on_error)) { 197 Arg->claim(); 198 TrapRemove |= expandSanitizerGroups(SanitizerKind::UndefinedGroup); 199 } 200 } 201 202 // Apply default trapping behavior. 203 TrappingKinds |= TrappingDefault & ~TrapRemove; 204 205 return TrappingKinds; 206 } 207 208 bool SanitizerArgs::needsUbsanRt() const { 209 // All of these include ubsan. 210 if (needsAsanRt() || needsMsanRt() || needsHwasanRt() || needsTsanRt() || 211 needsDfsanRt() || needsLsanRt() || needsCfiDiagRt() || 212 (needsScudoRt() && !requiresMinimalRuntime())) 213 return false; 214 215 return (Sanitizers.Mask & NeedsUbsanRt & ~TrapSanitizers.Mask) || 216 CoverageFeatures; 217 } 218 219 bool SanitizerArgs::needsCfiRt() const { 220 return !(Sanitizers.Mask & SanitizerKind::CFI & ~TrapSanitizers.Mask) && 221 CfiCrossDso && !ImplicitCfiRuntime; 222 } 223 224 bool SanitizerArgs::needsCfiDiagRt() const { 225 return (Sanitizers.Mask & SanitizerKind::CFI & ~TrapSanitizers.Mask) && 226 CfiCrossDso && !ImplicitCfiRuntime; 227 } 228 229 bool SanitizerArgs::requiresPIE() const { 230 return NeedPIE || (Sanitizers.Mask & RequiresPIE); 231 } 232 233 bool SanitizerArgs::needsUnwindTables() const { 234 return static_cast<bool>(Sanitizers.Mask & NeedsUnwindTables); 235 } 236 237 bool SanitizerArgs::needsLTO() const { 238 return static_cast<bool>(Sanitizers.Mask & NeedsLTO); 239 } 240 241 SanitizerArgs::SanitizerArgs(const ToolChain &TC, 242 const llvm::opt::ArgList &Args) { 243 SanitizerMask AllRemove; // During the loop below, the accumulated set of 244 // sanitizers disabled by the current sanitizer 245 // argument or any argument after it. 246 SanitizerMask AllAddedKinds; // Mask of all sanitizers ever enabled by 247 // -fsanitize= flags (directly or via group 248 // expansion), some of which may be disabled 249 // later. Used to carefully prune 250 // unused-argument diagnostics. 251 SanitizerMask DiagnosedKinds; // All Kinds we have diagnosed up to now. 252 // Used to deduplicate diagnostics. 253 SanitizerMask Kinds; 254 const SanitizerMask Supported = setGroupBits(TC.getSupportedSanitizers()); 255 256 CfiCrossDso = Args.hasFlag(options::OPT_fsanitize_cfi_cross_dso, 257 options::OPT_fno_sanitize_cfi_cross_dso, false); 258 259 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode(); 260 261 const Driver &D = TC.getDriver(); 262 SanitizerMask TrappingKinds = parseSanitizeTrapArgs(D, Args); 263 SanitizerMask InvalidTrappingKinds = TrappingKinds & NotAllowedWithTrap; 264 265 MinimalRuntime = 266 Args.hasFlag(options::OPT_fsanitize_minimal_runtime, 267 options::OPT_fno_sanitize_minimal_runtime, MinimalRuntime); 268 269 // The object size sanitizer should not be enabled at -O0. 270 Arg *OptLevel = Args.getLastArg(options::OPT_O_Group); 271 bool RemoveObjectSizeAtO0 = 272 !OptLevel || OptLevel->getOption().matches(options::OPT_O0); 273 274 for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend(); 275 I != E; ++I) { 276 const auto *Arg = *I; 277 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) { 278 Arg->claim(); 279 SanitizerMask Add = parseArgValues(D, Arg, /*AllowGroups=*/true); 280 281 if (RemoveObjectSizeAtO0) { 282 AllRemove |= SanitizerKind::ObjectSize; 283 284 // The user explicitly enabled the object size sanitizer. Warn 285 // that this does nothing at -O0. 286 if (Add & SanitizerKind::ObjectSize) 287 D.Diag(diag::warn_drv_object_size_disabled_O0) 288 << Arg->getAsString(Args); 289 } 290 291 AllAddedKinds |= expandSanitizerGroups(Add); 292 293 // Avoid diagnosing any sanitizer which is disabled later. 294 Add &= ~AllRemove; 295 // At this point we have not expanded groups, so any unsupported 296 // sanitizers in Add are those which have been explicitly enabled. 297 // Diagnose them. 298 if (SanitizerMask KindsToDiagnose = 299 Add & InvalidTrappingKinds & ~DiagnosedKinds) { 300 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose); 301 D.Diag(diag::err_drv_argument_not_allowed_with) 302 << Desc << "-fsanitize-trap=undefined"; 303 DiagnosedKinds |= KindsToDiagnose; 304 } 305 Add &= ~InvalidTrappingKinds; 306 307 if (MinimalRuntime) { 308 if (SanitizerMask KindsToDiagnose = 309 Add & NotAllowedWithMinimalRuntime & ~DiagnosedKinds) { 310 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose); 311 D.Diag(diag::err_drv_argument_not_allowed_with) 312 << Desc << "-fsanitize-minimal-runtime"; 313 DiagnosedKinds |= KindsToDiagnose; 314 } 315 Add &= ~NotAllowedWithMinimalRuntime; 316 } 317 318 // FIXME: Make CFI on member function calls compatible with cross-DSO CFI. 319 // There are currently two problems: 320 // - Virtual function call checks need to pass a pointer to the function 321 // address to llvm.type.test and a pointer to the address point to the 322 // diagnostic function. Currently we pass the same pointer to both 323 // places. 324 // - Non-virtual function call checks may need to check multiple type 325 // identifiers. 326 // Fixing both of those may require changes to the cross-DSO CFI 327 // interface. 328 if (CfiCrossDso && (Add & SanitizerKind::CFIMFCall & ~DiagnosedKinds)) { 329 D.Diag(diag::err_drv_argument_not_allowed_with) 330 << "-fsanitize=cfi-mfcall" 331 << "-fsanitize-cfi-cross-dso"; 332 Add &= ~SanitizerKind::CFIMFCall; 333 DiagnosedKinds |= SanitizerKind::CFIMFCall; 334 } 335 336 if (SanitizerMask KindsToDiagnose = Add & ~Supported & ~DiagnosedKinds) { 337 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose); 338 D.Diag(diag::err_drv_unsupported_opt_for_target) 339 << Desc << TC.getTriple().str(); 340 DiagnosedKinds |= KindsToDiagnose; 341 } 342 Add &= Supported; 343 344 // Test for -fno-rtti + explicit -fsanitizer=vptr before expanding groups 345 // so we don't error out if -fno-rtti and -fsanitize=undefined were 346 // passed. 347 if ((Add & SanitizerKind::Vptr) && (RTTIMode == ToolChain::RM_Disabled)) { 348 if (const llvm::opt::Arg *NoRTTIArg = TC.getRTTIArg()) { 349 assert(NoRTTIArg->getOption().matches(options::OPT_fno_rtti) && 350 "RTTI disabled without -fno-rtti option?"); 351 // The user explicitly passed -fno-rtti with -fsanitize=vptr, but 352 // the vptr sanitizer requires RTTI, so this is a user error. 353 D.Diag(diag::err_drv_argument_not_allowed_with) 354 << "-fsanitize=vptr" << NoRTTIArg->getAsString(Args); 355 } else { 356 // The vptr sanitizer requires RTTI, but RTTI is disabled (by 357 // default). Warn that the vptr sanitizer is being disabled. 358 D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default); 359 } 360 361 // Take out the Vptr sanitizer from the enabled sanitizers 362 AllRemove |= SanitizerKind::Vptr; 363 } 364 365 Add = expandSanitizerGroups(Add); 366 // Group expansion may have enabled a sanitizer which is disabled later. 367 Add &= ~AllRemove; 368 // Silently discard any unsupported sanitizers implicitly enabled through 369 // group expansion. 370 Add &= ~InvalidTrappingKinds; 371 if (MinimalRuntime) { 372 Add &= ~NotAllowedWithMinimalRuntime; 373 } 374 if (CfiCrossDso) 375 Add &= ~SanitizerKind::CFIMFCall; 376 Add &= Supported; 377 378 if (Add & SanitizerKind::Fuzzer) 379 Add |= SanitizerKind::FuzzerNoLink; 380 381 // Enable coverage if the fuzzing flag is set. 382 if (Add & SanitizerKind::FuzzerNoLink) { 383 CoverageFeatures |= CoverageInline8bitCounters | CoverageIndirCall | 384 CoverageTraceCmp | CoveragePCTable; 385 // Due to TLS differences, stack depth tracking is only enabled on Linux 386 if (TC.getTriple().isOSLinux()) 387 CoverageFeatures |= CoverageStackDepth; 388 } 389 390 Kinds |= Add; 391 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) { 392 Arg->claim(); 393 SanitizerMask Remove = parseArgValues(D, Arg, true); 394 AllRemove |= expandSanitizerGroups(Remove); 395 } 396 } 397 398 std::pair<SanitizerMask, SanitizerMask> IncompatibleGroups[] = { 399 std::make_pair(SanitizerKind::Address, 400 SanitizerKind::Thread | SanitizerKind::Memory), 401 std::make_pair(SanitizerKind::Thread, SanitizerKind::Memory), 402 std::make_pair(SanitizerKind::Leak, 403 SanitizerKind::Thread | SanitizerKind::Memory), 404 std::make_pair(SanitizerKind::KernelAddress, 405 SanitizerKind::Address | SanitizerKind::Leak | 406 SanitizerKind::Thread | SanitizerKind::Memory), 407 std::make_pair(SanitizerKind::HWAddress, 408 SanitizerKind::Address | SanitizerKind::Thread | 409 SanitizerKind::Memory | SanitizerKind::KernelAddress), 410 std::make_pair(SanitizerKind::Scudo, 411 SanitizerKind::Address | SanitizerKind::HWAddress | 412 SanitizerKind::Leak | SanitizerKind::Thread | 413 SanitizerKind::Memory | SanitizerKind::KernelAddress), 414 std::make_pair(SanitizerKind::SafeStack, 415 SanitizerKind::Address | SanitizerKind::HWAddress | 416 SanitizerKind::Leak | SanitizerKind::Thread | 417 SanitizerKind::Memory | SanitizerKind::KernelAddress), 418 std::make_pair(SanitizerKind::KernelHWAddress, 419 SanitizerKind::Address | SanitizerKind::HWAddress | 420 SanitizerKind::Leak | SanitizerKind::Thread | 421 SanitizerKind::Memory | SanitizerKind::KernelAddress | 422 SanitizerKind::SafeStack), 423 std::make_pair(SanitizerKind::KernelMemory, 424 SanitizerKind::Address | SanitizerKind::HWAddress | 425 SanitizerKind::Leak | SanitizerKind::Thread | 426 SanitizerKind::Memory | SanitizerKind::KernelAddress | 427 SanitizerKind::Scudo | SanitizerKind::SafeStack), 428 std::make_pair(SanitizerKind::MemTag, 429 SanitizerKind::Address | SanitizerKind::KernelAddress | 430 SanitizerKind::HWAddress | 431 SanitizerKind::KernelHWAddress)}; 432 // Enable toolchain specific default sanitizers if not explicitly disabled. 433 SanitizerMask Default = TC.getDefaultSanitizers() & ~AllRemove; 434 435 // Disable default sanitizers that are incompatible with explicitly requested 436 // ones. 437 for (auto G : IncompatibleGroups) { 438 SanitizerMask Group = G.first; 439 if ((Default & Group) && (Kinds & G.second)) 440 Default &= ~Group; 441 } 442 443 Kinds |= Default; 444 445 // We disable the vptr sanitizer if it was enabled by group expansion but RTTI 446 // is disabled. 447 if ((Kinds & SanitizerKind::Vptr) && (RTTIMode == ToolChain::RM_Disabled)) { 448 Kinds &= ~SanitizerKind::Vptr; 449 } 450 451 // Check that LTO is enabled if we need it. 452 if ((Kinds & NeedsLTO) && !D.isUsingLTO()) { 453 D.Diag(diag::err_drv_argument_only_allowed_with) 454 << lastArgumentForMask(D, Args, Kinds & NeedsLTO) << "-flto"; 455 } 456 457 if ((Kinds & SanitizerKind::ShadowCallStack) && TC.getTriple().isAArch64() && 458 !llvm::AArch64::isX18ReservedByDefault(TC.getTriple()) && 459 !Args.hasArg(options::OPT_ffixed_x18)) { 460 D.Diag(diag::err_drv_argument_only_allowed_with) 461 << lastArgumentForMask(D, Args, Kinds & SanitizerKind::ShadowCallStack) 462 << "-ffixed-x18"; 463 } 464 465 // Report error if there are non-trapping sanitizers that require 466 // c++abi-specific parts of UBSan runtime, and they are not provided by the 467 // toolchain. We don't have a good way to check the latter, so we just 468 // check if the toolchan supports vptr. 469 if (~Supported & SanitizerKind::Vptr) { 470 SanitizerMask KindsToDiagnose = Kinds & ~TrappingKinds & NeedsUbsanCxxRt; 471 // The runtime library supports the Microsoft C++ ABI, but only well enough 472 // for CFI. FIXME: Remove this once we support vptr on Windows. 473 if (TC.getTriple().isOSWindows()) 474 KindsToDiagnose &= ~SanitizerKind::CFI; 475 if (KindsToDiagnose) { 476 SanitizerSet S; 477 S.Mask = KindsToDiagnose; 478 D.Diag(diag::err_drv_unsupported_opt_for_target) 479 << ("-fno-sanitize-trap=" + toString(S)) << TC.getTriple().str(); 480 Kinds &= ~KindsToDiagnose; 481 } 482 } 483 484 // Warn about incompatible groups of sanitizers. 485 for (auto G : IncompatibleGroups) { 486 SanitizerMask Group = G.first; 487 if (Kinds & Group) { 488 if (SanitizerMask Incompatible = Kinds & G.second) { 489 D.Diag(clang::diag::err_drv_argument_not_allowed_with) 490 << lastArgumentForMask(D, Args, Group) 491 << lastArgumentForMask(D, Args, Incompatible); 492 Kinds &= ~Incompatible; 493 } 494 } 495 } 496 // FIXME: Currently -fsanitize=leak is silently ignored in the presence of 497 // -fsanitize=address. Perhaps it should print an error, or perhaps 498 // -f(-no)sanitize=leak should change whether leak detection is enabled by 499 // default in ASan? 500 501 // Parse -f(no-)?sanitize-recover flags. 502 SanitizerMask RecoverableKinds = RecoverableByDefault | AlwaysRecoverable; 503 SanitizerMask DiagnosedUnrecoverableKinds; 504 SanitizerMask DiagnosedAlwaysRecoverableKinds; 505 for (const auto *Arg : Args) { 506 const char *DeprecatedReplacement = nullptr; 507 if (Arg->getOption().matches(options::OPT_fsanitize_recover)) { 508 DeprecatedReplacement = 509 "-fsanitize-recover=undefined,integer' or '-fsanitize-recover=all"; 510 RecoverableKinds |= expandSanitizerGroups(LegacyFsanitizeRecoverMask); 511 Arg->claim(); 512 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover)) { 513 DeprecatedReplacement = "-fno-sanitize-recover=undefined,integer' or " 514 "'-fno-sanitize-recover=all"; 515 RecoverableKinds &= ~expandSanitizerGroups(LegacyFsanitizeRecoverMask); 516 Arg->claim(); 517 } else if (Arg->getOption().matches(options::OPT_fsanitize_recover_EQ)) { 518 SanitizerMask Add = parseArgValues(D, Arg, true); 519 // Report error if user explicitly tries to recover from unrecoverable 520 // sanitizer. 521 if (SanitizerMask KindsToDiagnose = 522 Add & Unrecoverable & ~DiagnosedUnrecoverableKinds) { 523 SanitizerSet SetToDiagnose; 524 SetToDiagnose.Mask |= KindsToDiagnose; 525 D.Diag(diag::err_drv_unsupported_option_argument) 526 << Arg->getOption().getName() << toString(SetToDiagnose); 527 DiagnosedUnrecoverableKinds |= KindsToDiagnose; 528 } 529 RecoverableKinds |= expandSanitizerGroups(Add); 530 Arg->claim(); 531 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) { 532 SanitizerMask Remove = parseArgValues(D, Arg, true); 533 // Report error if user explicitly tries to disable recovery from 534 // always recoverable sanitizer. 535 if (SanitizerMask KindsToDiagnose = 536 Remove & AlwaysRecoverable & ~DiagnosedAlwaysRecoverableKinds) { 537 SanitizerSet SetToDiagnose; 538 SetToDiagnose.Mask |= KindsToDiagnose; 539 D.Diag(diag::err_drv_unsupported_option_argument) 540 << Arg->getOption().getName() << toString(SetToDiagnose); 541 DiagnosedAlwaysRecoverableKinds |= KindsToDiagnose; 542 } 543 RecoverableKinds &= ~expandSanitizerGroups(Remove); 544 Arg->claim(); 545 } 546 if (DeprecatedReplacement) { 547 D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args) 548 << DeprecatedReplacement; 549 } 550 } 551 RecoverableKinds &= Kinds; 552 RecoverableKinds &= ~Unrecoverable; 553 554 TrappingKinds &= Kinds; 555 RecoverableKinds &= ~TrappingKinds; 556 557 // Setup blacklist files. 558 // Add default blacklist from resource directory. 559 addDefaultBlacklists(D, Kinds, SystemBlacklistFiles); 560 // Parse -f(no-)sanitize-blacklist options. 561 for (const auto *Arg : Args) { 562 if (Arg->getOption().matches(options::OPT_fsanitize_blacklist)) { 563 Arg->claim(); 564 std::string BLPath = Arg->getValue(); 565 if (D.getVFS().exists(BLPath)) { 566 UserBlacklistFiles.push_back(BLPath); 567 } else { 568 D.Diag(clang::diag::err_drv_no_such_file) << BLPath; 569 } 570 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_blacklist)) { 571 Arg->claim(); 572 UserBlacklistFiles.clear(); 573 SystemBlacklistFiles.clear(); 574 } 575 } 576 // Validate blacklists format. 577 { 578 std::string BLError; 579 std::unique_ptr<llvm::SpecialCaseList> SCL( 580 llvm::SpecialCaseList::create(UserBlacklistFiles, D.getVFS(), BLError)); 581 if (!SCL.get()) 582 D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError; 583 } 584 { 585 std::string BLError; 586 std::unique_ptr<llvm::SpecialCaseList> SCL(llvm::SpecialCaseList::create( 587 SystemBlacklistFiles, D.getVFS(), BLError)); 588 if (!SCL.get()) 589 D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError; 590 } 591 592 // Parse -f[no-]sanitize-memory-track-origins[=level] options. 593 if (AllAddedKinds & SanitizerKind::Memory) { 594 if (Arg *A = 595 Args.getLastArg(options::OPT_fsanitize_memory_track_origins_EQ, 596 options::OPT_fsanitize_memory_track_origins, 597 options::OPT_fno_sanitize_memory_track_origins)) { 598 if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) { 599 MsanTrackOrigins = 2; 600 } else if (A->getOption().matches( 601 options::OPT_fno_sanitize_memory_track_origins)) { 602 MsanTrackOrigins = 0; 603 } else { 604 StringRef S = A->getValue(); 605 if (S.getAsInteger(0, MsanTrackOrigins) || MsanTrackOrigins < 0 || 606 MsanTrackOrigins > 2) { 607 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S; 608 } 609 } 610 } 611 MsanUseAfterDtor = 612 Args.hasFlag(options::OPT_fsanitize_memory_use_after_dtor, 613 options::OPT_fno_sanitize_memory_use_after_dtor, 614 MsanUseAfterDtor); 615 NeedPIE |= !(TC.getTriple().isOSLinux() && 616 TC.getTriple().getArch() == llvm::Triple::x86_64); 617 } else { 618 MsanUseAfterDtor = false; 619 } 620 621 if (AllAddedKinds & SanitizerKind::Thread) { 622 TsanMemoryAccess = Args.hasFlag( 623 options::OPT_fsanitize_thread_memory_access, 624 options::OPT_fno_sanitize_thread_memory_access, TsanMemoryAccess); 625 TsanFuncEntryExit = Args.hasFlag( 626 options::OPT_fsanitize_thread_func_entry_exit, 627 options::OPT_fno_sanitize_thread_func_entry_exit, TsanFuncEntryExit); 628 TsanAtomics = 629 Args.hasFlag(options::OPT_fsanitize_thread_atomics, 630 options::OPT_fno_sanitize_thread_atomics, TsanAtomics); 631 } 632 633 if (AllAddedKinds & SanitizerKind::CFI) { 634 // Without PIE, external function address may resolve to a PLT record, which 635 // can not be verified by the target module. 636 NeedPIE |= CfiCrossDso; 637 CfiICallGeneralizePointers = 638 Args.hasArg(options::OPT_fsanitize_cfi_icall_generalize_pointers); 639 640 if (CfiCrossDso && CfiICallGeneralizePointers) 641 D.Diag(diag::err_drv_argument_not_allowed_with) 642 << "-fsanitize-cfi-cross-dso" 643 << "-fsanitize-cfi-icall-generalize-pointers"; 644 645 CfiCanonicalJumpTables = 646 Args.hasFlag(options::OPT_fsanitize_cfi_canonical_jump_tables, 647 options::OPT_fno_sanitize_cfi_canonical_jump_tables, true); 648 } 649 650 Stats = Args.hasFlag(options::OPT_fsanitize_stats, 651 options::OPT_fno_sanitize_stats, false); 652 653 if (MinimalRuntime) { 654 SanitizerMask IncompatibleMask = 655 Kinds & ~setGroupBits(CompatibleWithMinimalRuntime); 656 if (IncompatibleMask) 657 D.Diag(clang::diag::err_drv_argument_not_allowed_with) 658 << "-fsanitize-minimal-runtime" 659 << lastArgumentForMask(D, Args, IncompatibleMask); 660 661 SanitizerMask NonTrappingCfi = Kinds & SanitizerKind::CFI & ~TrappingKinds; 662 if (NonTrappingCfi) 663 D.Diag(clang::diag::err_drv_argument_only_allowed_with) 664 << "fsanitize-minimal-runtime" 665 << "fsanitize-trap=cfi"; 666 } 667 668 // Parse -f(no-)?sanitize-coverage flags if coverage is supported by the 669 // enabled sanitizers. 670 for (const auto *Arg : Args) { 671 if (Arg->getOption().matches(options::OPT_fsanitize_coverage)) { 672 int LegacySanitizeCoverage; 673 if (Arg->getNumValues() == 1 && 674 !StringRef(Arg->getValue(0)) 675 .getAsInteger(0, LegacySanitizeCoverage)) { 676 CoverageFeatures = 0; 677 Arg->claim(); 678 if (LegacySanitizeCoverage != 0) { 679 D.Diag(diag::warn_drv_deprecated_arg) 680 << Arg->getAsString(Args) << "-fsanitize-coverage=trace-pc-guard"; 681 } 682 continue; 683 } 684 CoverageFeatures |= parseCoverageFeatures(D, Arg); 685 686 // Disable coverage and not claim the flags if there is at least one 687 // non-supporting sanitizer. 688 if (!(AllAddedKinds & ~AllRemove & ~setGroupBits(SupportsCoverage))) { 689 Arg->claim(); 690 } else { 691 CoverageFeatures = 0; 692 } 693 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_coverage)) { 694 Arg->claim(); 695 CoverageFeatures &= ~parseCoverageFeatures(D, Arg); 696 } 697 } 698 // Choose at most one coverage type: function, bb, or edge. 699 if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageBB)) 700 D.Diag(clang::diag::err_drv_argument_not_allowed_with) 701 << "-fsanitize-coverage=func" 702 << "-fsanitize-coverage=bb"; 703 if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageEdge)) 704 D.Diag(clang::diag::err_drv_argument_not_allowed_with) 705 << "-fsanitize-coverage=func" 706 << "-fsanitize-coverage=edge"; 707 if ((CoverageFeatures & CoverageBB) && (CoverageFeatures & CoverageEdge)) 708 D.Diag(clang::diag::err_drv_argument_not_allowed_with) 709 << "-fsanitize-coverage=bb" 710 << "-fsanitize-coverage=edge"; 711 // Basic block tracing and 8-bit counters require some type of coverage 712 // enabled. 713 if (CoverageFeatures & CoverageTraceBB) 714 D.Diag(clang::diag::warn_drv_deprecated_arg) 715 << "-fsanitize-coverage=trace-bb" 716 << "-fsanitize-coverage=trace-pc-guard"; 717 if (CoverageFeatures & Coverage8bitCounters) 718 D.Diag(clang::diag::warn_drv_deprecated_arg) 719 << "-fsanitize-coverage=8bit-counters" 720 << "-fsanitize-coverage=trace-pc-guard"; 721 722 int InsertionPointTypes = CoverageFunc | CoverageBB | CoverageEdge; 723 int InstrumentationTypes = 724 CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters; 725 if ((CoverageFeatures & InsertionPointTypes) && 726 !(CoverageFeatures & InstrumentationTypes)) { 727 D.Diag(clang::diag::warn_drv_deprecated_arg) 728 << "-fsanitize-coverage=[func|bb|edge]" 729 << "-fsanitize-coverage=[func|bb|edge],[trace-pc-guard|trace-pc]"; 730 } 731 732 // trace-pc w/o func/bb/edge implies edge. 733 if (!(CoverageFeatures & InsertionPointTypes)) { 734 if (CoverageFeatures & 735 (CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters)) 736 CoverageFeatures |= CoverageEdge; 737 738 if (CoverageFeatures & CoverageStackDepth) 739 CoverageFeatures |= CoverageFunc; 740 } 741 742 SharedRuntime = 743 Args.hasFlag(options::OPT_shared_libsan, options::OPT_static_libsan, 744 TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia() || 745 TC.getTriple().isOSDarwin()); 746 747 ImplicitCfiRuntime = TC.getTriple().isAndroid(); 748 749 if (AllAddedKinds & SanitizerKind::Address) { 750 NeedPIE |= TC.getTriple().isOSFuchsia(); 751 if (Arg *A = 752 Args.getLastArg(options::OPT_fsanitize_address_field_padding)) { 753 StringRef S = A->getValue(); 754 // Legal values are 0 and 1, 2, but in future we may add more levels. 755 if (S.getAsInteger(0, AsanFieldPadding) || AsanFieldPadding < 0 || 756 AsanFieldPadding > 2) { 757 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S; 758 } 759 } 760 761 if (Arg *WindowsDebugRTArg = 762 Args.getLastArg(options::OPT__SLASH_MTd, options::OPT__SLASH_MT, 763 options::OPT__SLASH_MDd, options::OPT__SLASH_MD, 764 options::OPT__SLASH_LDd, options::OPT__SLASH_LD)) { 765 switch (WindowsDebugRTArg->getOption().getID()) { 766 case options::OPT__SLASH_MTd: 767 case options::OPT__SLASH_MDd: 768 case options::OPT__SLASH_LDd: 769 D.Diag(clang::diag::err_drv_argument_not_allowed_with) 770 << WindowsDebugRTArg->getAsString(Args) 771 << lastArgumentForMask(D, Args, SanitizerKind::Address); 772 D.Diag(clang::diag::note_drv_address_sanitizer_debug_runtime); 773 } 774 } 775 776 AsanUseAfterScope = Args.hasFlag( 777 options::OPT_fsanitize_address_use_after_scope, 778 options::OPT_fno_sanitize_address_use_after_scope, AsanUseAfterScope); 779 780 AsanPoisonCustomArrayCookie = Args.hasFlag( 781 options::OPT_fsanitize_address_poison_custom_array_cookie, 782 options::OPT_fno_sanitize_address_poison_custom_array_cookie, 783 AsanPoisonCustomArrayCookie); 784 785 // As a workaround for a bug in gold 2.26 and earlier, dead stripping of 786 // globals in ASan is disabled by default on ELF targets. 787 // See https://sourceware.org/bugzilla/show_bug.cgi?id=19002 788 AsanGlobalsDeadStripping = 789 !TC.getTriple().isOSBinFormatELF() || TC.getTriple().isOSFuchsia() || 790 TC.getTriple().isPS4() || 791 Args.hasArg(options::OPT_fsanitize_address_globals_dead_stripping); 792 793 AsanUseOdrIndicator = 794 Args.hasFlag(options::OPT_fsanitize_address_use_odr_indicator, 795 options::OPT_fno_sanitize_address_use_odr_indicator, 796 AsanUseOdrIndicator); 797 798 if (AllAddedKinds & SanitizerKind::PointerCompare & ~AllRemove) { 799 AsanInvalidPointerCmp = true; 800 } 801 802 if (AllAddedKinds & SanitizerKind::PointerSubtract & ~AllRemove) { 803 AsanInvalidPointerSub = true; 804 } 805 806 } else { 807 AsanUseAfterScope = false; 808 // -fsanitize=pointer-compare/pointer-subtract requires -fsanitize=address. 809 SanitizerMask DetectInvalidPointerPairs = 810 SanitizerKind::PointerCompare | SanitizerKind::PointerSubtract; 811 if (AllAddedKinds & DetectInvalidPointerPairs & ~AllRemove) { 812 TC.getDriver().Diag(clang::diag::err_drv_argument_only_allowed_with) 813 << lastArgumentForMask(D, Args, 814 SanitizerKind::PointerCompare | 815 SanitizerKind::PointerSubtract) 816 << "-fsanitize=address"; 817 } 818 } 819 820 if (AllAddedKinds & SanitizerKind::HWAddress) { 821 if (Arg *HwasanAbiArg = 822 Args.getLastArg(options::OPT_fsanitize_hwaddress_abi_EQ)) { 823 HwasanAbi = HwasanAbiArg->getValue(); 824 if (HwasanAbi != "platform" && HwasanAbi != "interceptor") 825 D.Diag(clang::diag::err_drv_invalid_value) 826 << HwasanAbiArg->getAsString(Args) << HwasanAbi; 827 } else { 828 HwasanAbi = "interceptor"; 829 } 830 } 831 832 if (AllAddedKinds & SanitizerKind::SafeStack) { 833 // SafeStack runtime is built into the system on Fuchsia. 834 SafeStackRuntime = !TC.getTriple().isOSFuchsia(); 835 } 836 837 LinkRuntimes = 838 Args.hasFlag(options::OPT_fsanitize_link_runtime, 839 options::OPT_fno_sanitize_link_runtime, LinkRuntimes); 840 841 // Parse -link-cxx-sanitizer flag. 842 LinkCXXRuntimes = Args.hasArg(options::OPT_fsanitize_link_cxx_runtime, 843 options::OPT_fno_sanitize_link_cxx_runtime, 844 LinkCXXRuntimes) || 845 D.CCCIsCXX(); 846 847 // Finally, initialize the set of available and recoverable sanitizers. 848 Sanitizers.Mask |= Kinds; 849 RecoverableSanitizers.Mask |= RecoverableKinds; 850 TrapSanitizers.Mask |= TrappingKinds; 851 assert(!(RecoverableKinds & TrappingKinds) && 852 "Overlap between recoverable and trapping sanitizers"); 853 } 854 855 static std::string toString(const clang::SanitizerSet &Sanitizers) { 856 std::string Res; 857 #define SANITIZER(NAME, ID) \ 858 if (Sanitizers.has(SanitizerKind::ID)) { \ 859 if (!Res.empty()) \ 860 Res += ","; \ 861 Res += NAME; \ 862 } 863 #include "clang/Basic/Sanitizers.def" 864 return Res; 865 } 866 867 static void addIncludeLinkerOption(const ToolChain &TC, 868 const llvm::opt::ArgList &Args, 869 llvm::opt::ArgStringList &CmdArgs, 870 StringRef SymbolName) { 871 SmallString<64> LinkerOptionFlag; 872 LinkerOptionFlag = "--linker-option=/include:"; 873 if (TC.getTriple().getArch() == llvm::Triple::x86) { 874 // Win32 mangles C function names with a '_' prefix. 875 LinkerOptionFlag += '_'; 876 } 877 LinkerOptionFlag += SymbolName; 878 CmdArgs.push_back(Args.MakeArgString(LinkerOptionFlag)); 879 } 880 881 static bool hasTargetFeatureMTE(const llvm::opt::ArgStringList &CmdArgs) { 882 for (auto Start = CmdArgs.begin(), End = CmdArgs.end(); Start != End; ++Start) { 883 auto It = std::find(Start, End, StringRef("+mte")); 884 if (It == End) 885 break; 886 if (It > Start && *std::prev(It) == StringRef("-target-feature")) 887 return true; 888 Start = It; 889 } 890 return false; 891 } 892 893 void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, 894 llvm::opt::ArgStringList &CmdArgs, 895 types::ID InputType) const { 896 // NVPTX doesn't currently support sanitizers. Bailing out here means that 897 // e.g. -fsanitize=address applies only to host code, which is what we want 898 // for now. 899 if (TC.getTriple().isNVPTX()) 900 return; 901 902 // Translate available CoverageFeatures to corresponding clang-cc1 flags. 903 // Do it even if Sanitizers.empty() since some forms of coverage don't require 904 // sanitizers. 905 std::pair<int, const char *> CoverageFlags[] = { 906 std::make_pair(CoverageFunc, "-fsanitize-coverage-type=1"), 907 std::make_pair(CoverageBB, "-fsanitize-coverage-type=2"), 908 std::make_pair(CoverageEdge, "-fsanitize-coverage-type=3"), 909 std::make_pair(CoverageIndirCall, "-fsanitize-coverage-indirect-calls"), 910 std::make_pair(CoverageTraceBB, "-fsanitize-coverage-trace-bb"), 911 std::make_pair(CoverageTraceCmp, "-fsanitize-coverage-trace-cmp"), 912 std::make_pair(CoverageTraceDiv, "-fsanitize-coverage-trace-div"), 913 std::make_pair(CoverageTraceGep, "-fsanitize-coverage-trace-gep"), 914 std::make_pair(Coverage8bitCounters, "-fsanitize-coverage-8bit-counters"), 915 std::make_pair(CoverageTracePC, "-fsanitize-coverage-trace-pc"), 916 std::make_pair(CoverageTracePCGuard, "-fsanitize-coverage-trace-pc-guard"), 917 std::make_pair(CoverageInline8bitCounters, "-fsanitize-coverage-inline-8bit-counters"), 918 std::make_pair(CoveragePCTable, "-fsanitize-coverage-pc-table"), 919 std::make_pair(CoverageNoPrune, "-fsanitize-coverage-no-prune"), 920 std::make_pair(CoverageStackDepth, "-fsanitize-coverage-stack-depth")}; 921 for (auto F : CoverageFlags) { 922 if (CoverageFeatures & F.first) 923 CmdArgs.push_back(F.second); 924 } 925 926 if (TC.getTriple().isOSWindows() && needsUbsanRt()) { 927 // Instruct the code generator to embed linker directives in the object file 928 // that cause the required runtime libraries to be linked. 929 CmdArgs.push_back(Args.MakeArgString( 930 "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone"))); 931 if (types::isCXX(InputType)) 932 CmdArgs.push_back(Args.MakeArgString( 933 "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone_cxx"))); 934 } 935 if (TC.getTriple().isOSWindows() && needsStatsRt()) { 936 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" + 937 TC.getCompilerRT(Args, "stats_client"))); 938 939 // The main executable must export the stats runtime. 940 // FIXME: Only exporting from the main executable (e.g. based on whether the 941 // translation unit defines main()) would save a little space, but having 942 // multiple copies of the runtime shouldn't hurt. 943 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" + 944 TC.getCompilerRT(Args, "stats"))); 945 addIncludeLinkerOption(TC, Args, CmdArgs, "__sanitizer_stats_register"); 946 } 947 948 if (Sanitizers.empty()) 949 return; 950 CmdArgs.push_back(Args.MakeArgString("-fsanitize=" + toString(Sanitizers))); 951 952 if (!RecoverableSanitizers.empty()) 953 CmdArgs.push_back(Args.MakeArgString("-fsanitize-recover=" + 954 toString(RecoverableSanitizers))); 955 956 if (!TrapSanitizers.empty()) 957 CmdArgs.push_back( 958 Args.MakeArgString("-fsanitize-trap=" + toString(TrapSanitizers))); 959 960 for (const auto &BLPath : UserBlacklistFiles) { 961 SmallString<64> BlacklistOpt("-fsanitize-blacklist="); 962 BlacklistOpt += BLPath; 963 CmdArgs.push_back(Args.MakeArgString(BlacklistOpt)); 964 } 965 for (const auto &BLPath : SystemBlacklistFiles) { 966 SmallString<64> BlacklistOpt("-fsanitize-system-blacklist="); 967 BlacklistOpt += BLPath; 968 CmdArgs.push_back(Args.MakeArgString(BlacklistOpt)); 969 } 970 971 if (MsanTrackOrigins) 972 CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins=" + 973 Twine(MsanTrackOrigins))); 974 975 if (MsanUseAfterDtor) 976 CmdArgs.push_back("-fsanitize-memory-use-after-dtor"); 977 978 // FIXME: Pass these parameters as function attributes, not as -llvm flags. 979 if (!TsanMemoryAccess) { 980 CmdArgs.push_back("-mllvm"); 981 CmdArgs.push_back("-tsan-instrument-memory-accesses=0"); 982 CmdArgs.push_back("-mllvm"); 983 CmdArgs.push_back("-tsan-instrument-memintrinsics=0"); 984 } 985 if (!TsanFuncEntryExit) { 986 CmdArgs.push_back("-mllvm"); 987 CmdArgs.push_back("-tsan-instrument-func-entry-exit=0"); 988 } 989 if (!TsanAtomics) { 990 CmdArgs.push_back("-mllvm"); 991 CmdArgs.push_back("-tsan-instrument-atomics=0"); 992 } 993 994 if (CfiCrossDso) 995 CmdArgs.push_back("-fsanitize-cfi-cross-dso"); 996 997 if (CfiICallGeneralizePointers) 998 CmdArgs.push_back("-fsanitize-cfi-icall-generalize-pointers"); 999 1000 if (CfiCanonicalJumpTables) 1001 CmdArgs.push_back("-fsanitize-cfi-canonical-jump-tables"); 1002 1003 if (Stats) 1004 CmdArgs.push_back("-fsanitize-stats"); 1005 1006 if (MinimalRuntime) 1007 CmdArgs.push_back("-fsanitize-minimal-runtime"); 1008 1009 if (AsanFieldPadding) 1010 CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-field-padding=" + 1011 Twine(AsanFieldPadding))); 1012 1013 if (AsanUseAfterScope) 1014 CmdArgs.push_back("-fsanitize-address-use-after-scope"); 1015 1016 if (AsanPoisonCustomArrayCookie) 1017 CmdArgs.push_back("-fsanitize-address-poison-custom-array-cookie"); 1018 1019 if (AsanGlobalsDeadStripping) 1020 CmdArgs.push_back("-fsanitize-address-globals-dead-stripping"); 1021 1022 if (AsanUseOdrIndicator) 1023 CmdArgs.push_back("-fsanitize-address-use-odr-indicator"); 1024 1025 if (AsanInvalidPointerCmp) { 1026 CmdArgs.push_back("-mllvm"); 1027 CmdArgs.push_back("-asan-detect-invalid-pointer-cmp"); 1028 } 1029 1030 if (AsanInvalidPointerSub) { 1031 CmdArgs.push_back("-mllvm"); 1032 CmdArgs.push_back("-asan-detect-invalid-pointer-sub"); 1033 } 1034 1035 if (!HwasanAbi.empty()) { 1036 CmdArgs.push_back("-default-function-attr"); 1037 CmdArgs.push_back(Args.MakeArgString("hwasan-abi=" + HwasanAbi)); 1038 } 1039 1040 if (Sanitizers.has(SanitizerKind::HWAddress)) { 1041 CmdArgs.push_back("-target-feature"); 1042 CmdArgs.push_back("+tagged-globals"); 1043 } 1044 1045 // MSan: Workaround for PR16386. 1046 // ASan: This is mainly to help LSan with cases such as 1047 // https://github.com/google/sanitizers/issues/373 1048 // We can't make this conditional on -fsanitize=leak, as that flag shouldn't 1049 // affect compilation. 1050 if (Sanitizers.has(SanitizerKind::Memory) || 1051 Sanitizers.has(SanitizerKind::Address)) 1052 CmdArgs.push_back("-fno-assume-sane-operator-new"); 1053 1054 // Require -fvisibility= flag on non-Windows when compiling if vptr CFI is 1055 // enabled. 1056 if (Sanitizers.hasOneOf(CFIClasses) && !TC.getTriple().isOSWindows() && 1057 !Args.hasArg(options::OPT_fvisibility_EQ)) { 1058 TC.getDriver().Diag(clang::diag::err_drv_argument_only_allowed_with) 1059 << lastArgumentForMask(TC.getDriver(), Args, 1060 Sanitizers.Mask & CFIClasses) 1061 << "-fvisibility="; 1062 } 1063 1064 if (Sanitizers.has(SanitizerKind::MemTag) && !hasTargetFeatureMTE(CmdArgs)) 1065 TC.getDriver().Diag(diag::err_stack_tagging_requires_hardware_feature); 1066 } 1067 1068 SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A, 1069 bool DiagnoseErrors) { 1070 assert((A->getOption().matches(options::OPT_fsanitize_EQ) || 1071 A->getOption().matches(options::OPT_fno_sanitize_EQ) || 1072 A->getOption().matches(options::OPT_fsanitize_recover_EQ) || 1073 A->getOption().matches(options::OPT_fno_sanitize_recover_EQ) || 1074 A->getOption().matches(options::OPT_fsanitize_trap_EQ) || 1075 A->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) && 1076 "Invalid argument in parseArgValues!"); 1077 SanitizerMask Kinds; 1078 for (int i = 0, n = A->getNumValues(); i != n; ++i) { 1079 const char *Value = A->getValue(i); 1080 SanitizerMask Kind; 1081 // Special case: don't accept -fsanitize=all. 1082 if (A->getOption().matches(options::OPT_fsanitize_EQ) && 1083 0 == strcmp("all", Value)) 1084 Kind = SanitizerMask(); 1085 else 1086 Kind = parseSanitizerValue(Value, /*AllowGroups=*/true); 1087 1088 if (Kind) 1089 Kinds |= Kind; 1090 else if (DiagnoseErrors) 1091 D.Diag(clang::diag::err_drv_unsupported_option_argument) 1092 << A->getOption().getName() << Value; 1093 } 1094 return Kinds; 1095 } 1096 1097 int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A) { 1098 assert(A->getOption().matches(options::OPT_fsanitize_coverage) || 1099 A->getOption().matches(options::OPT_fno_sanitize_coverage)); 1100 int Features = 0; 1101 for (int i = 0, n = A->getNumValues(); i != n; ++i) { 1102 const char *Value = A->getValue(i); 1103 int F = llvm::StringSwitch<int>(Value) 1104 .Case("func", CoverageFunc) 1105 .Case("bb", CoverageBB) 1106 .Case("edge", CoverageEdge) 1107 .Case("indirect-calls", CoverageIndirCall) 1108 .Case("trace-bb", CoverageTraceBB) 1109 .Case("trace-cmp", CoverageTraceCmp) 1110 .Case("trace-div", CoverageTraceDiv) 1111 .Case("trace-gep", CoverageTraceGep) 1112 .Case("8bit-counters", Coverage8bitCounters) 1113 .Case("trace-pc", CoverageTracePC) 1114 .Case("trace-pc-guard", CoverageTracePCGuard) 1115 .Case("no-prune", CoverageNoPrune) 1116 .Case("inline-8bit-counters", CoverageInline8bitCounters) 1117 .Case("pc-table", CoveragePCTable) 1118 .Case("stack-depth", CoverageStackDepth) 1119 .Default(0); 1120 if (F == 0) 1121 D.Diag(clang::diag::err_drv_unsupported_option_argument) 1122 << A->getOption().getName() << Value; 1123 Features |= F; 1124 } 1125 return Features; 1126 } 1127 1128 std::string lastArgumentForMask(const Driver &D, const llvm::opt::ArgList &Args, 1129 SanitizerMask Mask) { 1130 for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(), 1131 E = Args.rend(); 1132 I != E; ++I) { 1133 const auto *Arg = *I; 1134 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) { 1135 SanitizerMask AddKinds = 1136 expandSanitizerGroups(parseArgValues(D, Arg, false)); 1137 if (AddKinds & Mask) 1138 return describeSanitizeArg(Arg, Mask); 1139 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) { 1140 SanitizerMask RemoveKinds = 1141 expandSanitizerGroups(parseArgValues(D, Arg, false)); 1142 Mask &= ~RemoveKinds; 1143 } 1144 } 1145 llvm_unreachable("arg list didn't provide expected value"); 1146 } 1147 1148 std::string describeSanitizeArg(const llvm::opt::Arg *A, SanitizerMask Mask) { 1149 assert(A->getOption().matches(options::OPT_fsanitize_EQ) 1150 && "Invalid argument in describeSanitizerArg!"); 1151 1152 std::string Sanitizers; 1153 for (int i = 0, n = A->getNumValues(); i != n; ++i) { 1154 if (expandSanitizerGroups( 1155 parseSanitizerValue(A->getValue(i), /*AllowGroups=*/true)) & 1156 Mask) { 1157 if (!Sanitizers.empty()) 1158 Sanitizers += ","; 1159 Sanitizers += A->getValue(i); 1160 } 1161 } 1162 1163 assert(!Sanitizers.empty() && "arg didn't provide expected value"); 1164 return "-fsanitize=" + Sanitizers; 1165 } 1166