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