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