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