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