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