clang 8.0.0

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