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