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,
34  NeedsUnwindTables = Address | Thread | Memory | DataFlow,
35  SupportsCoverage = Address | KernelAddress | Memory | Leak | Undefined |
36  Integer | Nullability | DataFlow | Fuzzer | FuzzerNoLink,
37  RecoverableByDefault = Undefined | Integer | Nullability,
38  Unrecoverable = Unreachable | Return,
39  LegacyFsanitizeRecoverMask = Undefined | Integer,
40  NeedsLTO = CFI,
41  TrappingSupported = (Undefined & ~Vptr) | UnsignedIntegerOverflow |
42  Nullability | LocalBounds | CFI,
44  CFIClasses = CFIVCall | CFINVCall | CFIDerivedCast | CFIUnrelatedCast,
46 };
47 
49  CoverageFunc = 1 << 0,
50  CoverageBB = 1 << 1,
51  CoverageEdge = 1 << 2,
53  CoverageTraceBB = 1 << 4, // Deprecated.
54  CoverageTraceCmp = 1 << 5,
55  CoverageTraceDiv = 1 << 6,
56  CoverageTraceGep = 1 << 7,
57  Coverage8bitCounters = 1 << 8, // Deprecated.
58  CoverageTracePC = 1 << 9,
60  CoverageNoPrune = 1 << 11,
62  CoveragePCTable = 1 << 13,
63  CoverageStackDepth = 1 << 14,
64 };
65 
66 /// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
67 /// invalid components. Returns a SanitizerMask.
68 static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
69  bool DiagnoseErrors);
70 
71 /// Parse -f(no-)?sanitize-coverage= flag values, diagnosing any invalid
72 /// components. Returns OR of members of \c CoverageFeature enumeration.
73 static int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A);
74 
75 /// Produce an argument string from ArgList \p Args, which shows how it
76 /// provides some sanitizer kind from \p Mask. For example, the argument list
77 /// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt
78 /// would produce "-fsanitize=vptr".
79 static std::string lastArgumentForMask(const Driver &D,
80  const llvm::opt::ArgList &Args,
81  SanitizerMask Mask);
82 
83 /// Produce an argument string from argument \p A, which shows how it provides
84 /// a value in \p Mask. For instance, the argument
85 /// "-fsanitize=address,alignment" with mask \c NeedsUbsanRt would produce
86 /// "-fsanitize=alignment".
87 static std::string describeSanitizeArg(const llvm::opt::Arg *A,
88  SanitizerMask Mask);
89 
90 /// Produce a string containing comma-separated names of sanitizers in \p
91 /// Sanitizers set.
92 static std::string toString(const clang::SanitizerSet &Sanitizers);
93 
94 static bool getDefaultBlacklist(const Driver &D, SanitizerMask Kinds,
95  std::string &BLPath) {
96  const char *BlacklistFile = nullptr;
97  if (Kinds & Address)
98  BlacklistFile = "asan_blacklist.txt";
99  else if (Kinds & Memory)
100  BlacklistFile = "msan_blacklist.txt";
101  else if (Kinds & Thread)
102  BlacklistFile = "tsan_blacklist.txt";
103  else if (Kinds & DataFlow)
104  BlacklistFile = "dfsan_abilist.txt";
105  else if (Kinds & CFI)
106  BlacklistFile = "cfi_blacklist.txt";
107  else if (Kinds & (Undefined | Integer | Nullability))
108  BlacklistFile = "ubsan_blacklist.txt";
109 
110  if (BlacklistFile) {
112  llvm::sys::path::append(Path, BlacklistFile);
113  BLPath = Path.str();
114  return true;
115  }
116  return false;
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() || needsTsanRt() || needsDfsanRt() ||
176  needsLsanRt() || needsCfiDiagRt())
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), std::make_pair(Address, Memory),
374  std::make_pair(Thread, Memory), std::make_pair(Leak, Thread),
375  std::make_pair(Leak, Memory), std::make_pair(KernelAddress, Address),
376  std::make_pair(KernelAddress, Leak),
377  std::make_pair(KernelAddress, Thread),
378  std::make_pair(KernelAddress, Memory),
379  std::make_pair(Efficiency, Address),
380  std::make_pair(Efficiency, Leak),
381  std::make_pair(Efficiency, Thread),
382  std::make_pair(Efficiency, Memory),
383  std::make_pair(Efficiency, KernelAddress)};
384  for (auto G : IncompatibleGroups) {
385  SanitizerMask Group = G.first;
386  if (Kinds & Group) {
387  if (SanitizerMask Incompatible = Kinds & G.second) {
388  D.Diag(clang::diag::err_drv_argument_not_allowed_with)
389  << lastArgumentForMask(D, Args, Group)
390  << lastArgumentForMask(D, Args, Incompatible);
391  Kinds &= ~Incompatible;
392  }
393  }
394  }
395  // FIXME: Currently -fsanitize=leak is silently ignored in the presence of
396  // -fsanitize=address. Perhaps it should print an error, or perhaps
397  // -f(-no)sanitize=leak should change whether leak detection is enabled by
398  // default in ASan?
399 
400  // Parse -f(no-)?sanitize-recover flags.
401  SanitizerMask RecoverableKinds = RecoverableByDefault;
402  SanitizerMask DiagnosedUnrecoverableKinds = 0;
403  for (const auto *Arg : Args) {
404  const char *DeprecatedReplacement = nullptr;
405  if (Arg->getOption().matches(options::OPT_fsanitize_recover)) {
406  DeprecatedReplacement =
407  "-fsanitize-recover=undefined,integer' or '-fsanitize-recover=all";
409  Arg->claim();
410  } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover)) {
411  DeprecatedReplacement = "-fno-sanitize-recover=undefined,integer' or "
412  "'-fno-sanitize-recover=all";
414  Arg->claim();
415  } else if (Arg->getOption().matches(options::OPT_fsanitize_recover_EQ)) {
416  SanitizerMask Add = parseArgValues(D, Arg, true);
417  // Report error if user explicitly tries to recover from unrecoverable
418  // sanitizer.
419  if (SanitizerMask KindsToDiagnose =
420  Add & Unrecoverable & ~DiagnosedUnrecoverableKinds) {
421  SanitizerSet SetToDiagnose;
422  SetToDiagnose.Mask |= KindsToDiagnose;
423  D.Diag(diag::err_drv_unsupported_option_argument)
424  << Arg->getOption().getName() << toString(SetToDiagnose);
425  DiagnosedUnrecoverableKinds |= KindsToDiagnose;
426  }
427  RecoverableKinds |= expandSanitizerGroups(Add);
428  Arg->claim();
429  } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) {
430  RecoverableKinds &= ~expandSanitizerGroups(parseArgValues(D, Arg, true));
431  Arg->claim();
432  }
433  if (DeprecatedReplacement) {
434  D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
435  << DeprecatedReplacement;
436  }
437  }
438  RecoverableKinds &= Kinds;
439  RecoverableKinds &= ~Unrecoverable;
440 
441  TrappingKinds &= Kinds;
442 
443  // Setup blacklist files.
444  // Add default blacklist from resource directory.
445  {
446  std::string BLPath;
447  if (getDefaultBlacklist(D, Kinds, BLPath) && llvm::sys::fs::exists(BLPath))
448  BlacklistFiles.push_back(BLPath);
449  }
450  // Parse -f(no-)sanitize-blacklist options.
451  for (const auto *Arg : Args) {
452  if (Arg->getOption().matches(options::OPT_fsanitize_blacklist)) {
453  Arg->claim();
454  std::string BLPath = Arg->getValue();
455  if (llvm::sys::fs::exists(BLPath)) {
456  BlacklistFiles.push_back(BLPath);
457  ExtraDeps.push_back(BLPath);
458  } else
459  D.Diag(clang::diag::err_drv_no_such_file) << BLPath;
460 
461  } else if (Arg->getOption().matches(options::OPT_fno_sanitize_blacklist)) {
462  Arg->claim();
463  BlacklistFiles.clear();
464  ExtraDeps.clear();
465  }
466  }
467  // Validate blacklists format.
468  {
469  std::string BLError;
470  std::unique_ptr<llvm::SpecialCaseList> SCL(
471  llvm::SpecialCaseList::create(BlacklistFiles, BLError));
472  if (!SCL.get())
473  D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError;
474  }
475 
476  // Parse -f[no-]sanitize-memory-track-origins[=level] options.
477  if (AllAddedKinds & Memory) {
478  if (Arg *A =
479  Args.getLastArg(options::OPT_fsanitize_memory_track_origins_EQ,
480  options::OPT_fsanitize_memory_track_origins,
481  options::OPT_fno_sanitize_memory_track_origins)) {
482  if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) {
483  MsanTrackOrigins = 2;
484  } else if (A->getOption().matches(
485  options::OPT_fno_sanitize_memory_track_origins)) {
486  MsanTrackOrigins = 0;
487  } else {
488  StringRef S = A->getValue();
489  if (S.getAsInteger(0, MsanTrackOrigins) || MsanTrackOrigins < 0 ||
490  MsanTrackOrigins > 2) {
491  D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
492  }
493  }
494  }
495  MsanUseAfterDtor =
496  Args.hasFlag(options::OPT_fsanitize_memory_use_after_dtor,
497  options::OPT_fno_sanitize_memory_use_after_dtor,
498  MsanUseAfterDtor);
499  NeedPIE |= !(TC.getTriple().isOSLinux() &&
500  TC.getTriple().getArch() == llvm::Triple::x86_64);
501  } else {
502  MsanUseAfterDtor = false;
503  }
504 
505  if (AllAddedKinds & Thread) {
506  TsanMemoryAccess = Args.hasFlag(options::OPT_fsanitize_thread_memory_access,
507  options::OPT_fno_sanitize_thread_memory_access,
508  TsanMemoryAccess);
509  TsanFuncEntryExit = Args.hasFlag(options::OPT_fsanitize_thread_func_entry_exit,
510  options::OPT_fno_sanitize_thread_func_entry_exit,
511  TsanFuncEntryExit);
512  TsanAtomics = Args.hasFlag(options::OPT_fsanitize_thread_atomics,
513  options::OPT_fno_sanitize_thread_atomics,
514  TsanAtomics);
515  }
516 
517  if (AllAddedKinds & CFI) {
518  CfiCrossDso = Args.hasFlag(options::OPT_fsanitize_cfi_cross_dso,
519  options::OPT_fno_sanitize_cfi_cross_dso, false);
520  // Without PIE, external function address may resolve to a PLT record, which
521  // can not be verified by the target module.
522  NeedPIE |= CfiCrossDso;
523  }
524 
525  Stats = Args.hasFlag(options::OPT_fsanitize_stats,
526  options::OPT_fno_sanitize_stats, false);
527 
528  if (MinimalRuntime) {
529  SanitizerMask IncompatibleMask =
531  if (IncompatibleMask)
532  D.Diag(clang::diag::err_drv_argument_not_allowed_with)
533  << "-fsanitize-minimal-runtime"
534  << lastArgumentForMask(D, Args, IncompatibleMask);
535 
536  SanitizerMask NonTrappingCfi = Kinds & CFI & ~TrappingKinds;
537  if (NonTrappingCfi)
538  D.Diag(clang::diag::err_drv_argument_only_allowed_with)
539  << "fsanitize-minimal-runtime"
540  << "fsanitize-trap=cfi";
541  }
542 
543  // Parse -f(no-)?sanitize-coverage flags if coverage is supported by the
544  // enabled sanitizers.
545  for (const auto *Arg : Args) {
546  if (Arg->getOption().matches(options::OPT_fsanitize_coverage)) {
547  int LegacySanitizeCoverage;
548  if (Arg->getNumValues() == 1 &&
549  !StringRef(Arg->getValue(0))
550  .getAsInteger(0, LegacySanitizeCoverage)) {
551  CoverageFeatures = 0;
552  Arg->claim();
553  if (LegacySanitizeCoverage != 0) {
554  D.Diag(diag::warn_drv_deprecated_arg)
555  << Arg->getAsString(Args) << "-fsanitize-coverage=trace-pc-guard";
556  }
557  continue;
558  }
559  CoverageFeatures |= parseCoverageFeatures(D, Arg);
560 
561  // Disable coverage and not claim the flags if there is at least one
562  // non-supporting sanitizer.
563  if (!(AllAddedKinds & ~AllRemove & ~setGroupBits(SupportsCoverage))) {
564  Arg->claim();
565  } else {
566  CoverageFeatures = 0;
567  }
568  } else if (Arg->getOption().matches(options::OPT_fno_sanitize_coverage)) {
569  Arg->claim();
570  CoverageFeatures &= ~parseCoverageFeatures(D, Arg);
571  }
572  }
573  // Choose at most one coverage type: function, bb, or edge.
574  if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageBB))
575  D.Diag(clang::diag::err_drv_argument_not_allowed_with)
576  << "-fsanitize-coverage=func"
577  << "-fsanitize-coverage=bb";
578  if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageEdge))
579  D.Diag(clang::diag::err_drv_argument_not_allowed_with)
580  << "-fsanitize-coverage=func"
581  << "-fsanitize-coverage=edge";
582  if ((CoverageFeatures & CoverageBB) && (CoverageFeatures & CoverageEdge))
583  D.Diag(clang::diag::err_drv_argument_not_allowed_with)
584  << "-fsanitize-coverage=bb"
585  << "-fsanitize-coverage=edge";
586  // Basic block tracing and 8-bit counters require some type of coverage
587  // enabled.
588  if (CoverageFeatures & CoverageTraceBB)
589  D.Diag(clang::diag::warn_drv_deprecated_arg)
590  << "-fsanitize-coverage=trace-bb"
591  << "-fsanitize-coverage=trace-pc-guard";
592  if (CoverageFeatures & Coverage8bitCounters)
593  D.Diag(clang::diag::warn_drv_deprecated_arg)
594  << "-fsanitize-coverage=8bit-counters"
595  << "-fsanitize-coverage=trace-pc-guard";
596 
597  int InsertionPointTypes = CoverageFunc | CoverageBB | CoverageEdge;
598  int InstrumentationTypes =
600  if ((CoverageFeatures & InsertionPointTypes) &&
601  !(CoverageFeatures & InstrumentationTypes)) {
602  D.Diag(clang::diag::warn_drv_deprecated_arg)
603  << "-fsanitize-coverage=[func|bb|edge]"
604  << "-fsanitize-coverage=[func|bb|edge],[trace-pc-guard|trace-pc]";
605  }
606 
607  // trace-pc w/o func/bb/edge implies edge.
608  if (!(CoverageFeatures & InsertionPointTypes)) {
609  if (CoverageFeatures &
611  CoverageFeatures |= CoverageEdge;
612 
613  if (CoverageFeatures & CoverageStackDepth)
614  CoverageFeatures |= CoverageFunc;
615  }
616 
617  SharedRuntime =
618  Args.hasFlag(options::OPT_shared_libsan, options::OPT_static_libsan,
619  TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia() ||
620  TC.getTriple().isOSDarwin());
621 
622  ImplicitCfiRuntime = TC.getTriple().isAndroid();
623 
624  if (AllAddedKinds & Address) {
625  NeedPIE |= TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia();
626  if (Arg *A =
627  Args.getLastArg(options::OPT_fsanitize_address_field_padding)) {
628  StringRef S = A->getValue();
629  // Legal values are 0 and 1, 2, but in future we may add more levels.
630  if (S.getAsInteger(0, AsanFieldPadding) || AsanFieldPadding < 0 ||
631  AsanFieldPadding > 2) {
632  D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
633  }
634  }
635 
636  if (Arg *WindowsDebugRTArg =
637  Args.getLastArg(options::OPT__SLASH_MTd, options::OPT__SLASH_MT,
638  options::OPT__SLASH_MDd, options::OPT__SLASH_MD,
639  options::OPT__SLASH_LDd, options::OPT__SLASH_LD)) {
640  switch (WindowsDebugRTArg->getOption().getID()) {
641  case options::OPT__SLASH_MTd:
642  case options::OPT__SLASH_MDd:
643  case options::OPT__SLASH_LDd:
644  D.Diag(clang::diag::err_drv_argument_not_allowed_with)
645  << WindowsDebugRTArg->getAsString(Args)
646  << lastArgumentForMask(D, Args, Address);
647  D.Diag(clang::diag::note_drv_address_sanitizer_debug_runtime);
648  }
649  }
650 
651  AsanUseAfterScope = Args.hasFlag(
652  options::OPT_fsanitize_address_use_after_scope,
653  options::OPT_fno_sanitize_address_use_after_scope, AsanUseAfterScope);
654 
655  // As a workaround for a bug in gold 2.26 and earlier, dead stripping of
656  // globals in ASan is disabled by default on ELF targets.
657  // See https://sourceware.org/bugzilla/show_bug.cgi?id=19002
658  AsanGlobalsDeadStripping =
659  !TC.getTriple().isOSBinFormatELF() || TC.getTriple().isOSFuchsia() ||
660  Args.hasArg(options::OPT_fsanitize_address_globals_dead_stripping);
661  } else {
662  AsanUseAfterScope = false;
663  }
664 
665  if (AllAddedKinds & SafeStack) {
666  // SafeStack runtime is built into the system on Fuchsia.
667  SafeStackRuntime = !TC.getTriple().isOSFuchsia();
668  }
669 
670  // Parse -link-cxx-sanitizer flag.
671  LinkCXXRuntimes =
672  Args.hasArg(options::OPT_fsanitize_link_cxx_runtime) || D.CCCIsCXX();
673 
674  // Finally, initialize the set of available and recoverable sanitizers.
675  Sanitizers.Mask |= Kinds;
676  RecoverableSanitizers.Mask |= RecoverableKinds;
677  TrapSanitizers.Mask |= TrappingKinds;
678 }
679 
680 static std::string toString(const clang::SanitizerSet &Sanitizers) {
681  std::string Res;
682 #define SANITIZER(NAME, ID) \
683  if (Sanitizers.has(ID)) { \
684  if (!Res.empty()) \
685  Res += ","; \
686  Res += NAME; \
687  }
688 #include "clang/Basic/Sanitizers.def"
689  return Res;
690 }
691 
692 static void addIncludeLinkerOption(const ToolChain &TC,
693  const llvm::opt::ArgList &Args,
694  llvm::opt::ArgStringList &CmdArgs,
695  StringRef SymbolName) {
696  SmallString<64> LinkerOptionFlag;
697  LinkerOptionFlag = "--linker-option=/include:";
698  if (TC.getTriple().getArch() == llvm::Triple::x86) {
699  // Win32 mangles C function names with a '_' prefix.
700  LinkerOptionFlag += '_';
701  }
702  LinkerOptionFlag += SymbolName;
703  CmdArgs.push_back(Args.MakeArgString(LinkerOptionFlag));
704 }
705 
706 void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args,
707  llvm::opt::ArgStringList &CmdArgs,
708  types::ID InputType) const {
709  // NVPTX doesn't currently support sanitizers. Bailing out here means that
710  // e.g. -fsanitize=address applies only to host code, which is what we want
711  // for now.
712  if (TC.getTriple().isNVPTX())
713  return;
714 
715  // Translate available CoverageFeatures to corresponding clang-cc1 flags.
716  // Do it even if Sanitizers.empty() since some forms of coverage don't require
717  // sanitizers.
718  std::pair<int, const char *> CoverageFlags[] = {
719  std::make_pair(CoverageFunc, "-fsanitize-coverage-type=1"),
720  std::make_pair(CoverageBB, "-fsanitize-coverage-type=2"),
721  std::make_pair(CoverageEdge, "-fsanitize-coverage-type=3"),
722  std::make_pair(CoverageIndirCall, "-fsanitize-coverage-indirect-calls"),
723  std::make_pair(CoverageTraceBB, "-fsanitize-coverage-trace-bb"),
724  std::make_pair(CoverageTraceCmp, "-fsanitize-coverage-trace-cmp"),
725  std::make_pair(CoverageTraceDiv, "-fsanitize-coverage-trace-div"),
726  std::make_pair(CoverageTraceGep, "-fsanitize-coverage-trace-gep"),
727  std::make_pair(Coverage8bitCounters, "-fsanitize-coverage-8bit-counters"),
728  std::make_pair(CoverageTracePC, "-fsanitize-coverage-trace-pc"),
729  std::make_pair(CoverageTracePCGuard, "-fsanitize-coverage-trace-pc-guard"),
730  std::make_pair(CoverageInline8bitCounters, "-fsanitize-coverage-inline-8bit-counters"),
731  std::make_pair(CoveragePCTable, "-fsanitize-coverage-pc-table"),
732  std::make_pair(CoverageNoPrune, "-fsanitize-coverage-no-prune"),
733  std::make_pair(CoverageStackDepth, "-fsanitize-coverage-stack-depth")};
734  for (auto F : CoverageFlags) {
735  if (CoverageFeatures & F.first)
736  CmdArgs.push_back(F.second);
737  }
738 
739  if (TC.getTriple().isOSWindows() && needsUbsanRt()) {
740  // Instruct the code generator to embed linker directives in the object file
741  // that cause the required runtime libraries to be linked.
742  CmdArgs.push_back(Args.MakeArgString(
743  "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone")));
744  if (types::isCXX(InputType))
745  CmdArgs.push_back(Args.MakeArgString(
746  "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone_cxx")));
747  }
748  if (TC.getTriple().isOSWindows() && needsStatsRt()) {
749  CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
750  TC.getCompilerRT(Args, "stats_client")));
751 
752  // The main executable must export the stats runtime.
753  // FIXME: Only exporting from the main executable (e.g. based on whether the
754  // translation unit defines main()) would save a little space, but having
755  // multiple copies of the runtime shouldn't hurt.
756  CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
757  TC.getCompilerRT(Args, "stats")));
758  addIncludeLinkerOption(TC, Args, CmdArgs, "__sanitizer_stats_register");
759  }
760 
761  if (Sanitizers.empty())
762  return;
763  CmdArgs.push_back(Args.MakeArgString("-fsanitize=" + toString(Sanitizers)));
764 
765  if (!RecoverableSanitizers.empty())
766  CmdArgs.push_back(Args.MakeArgString("-fsanitize-recover=" +
767  toString(RecoverableSanitizers)));
768 
769  if (!TrapSanitizers.empty())
770  CmdArgs.push_back(
771  Args.MakeArgString("-fsanitize-trap=" + toString(TrapSanitizers)));
772 
773  for (const auto &BLPath : BlacklistFiles) {
774  SmallString<64> BlacklistOpt("-fsanitize-blacklist=");
775  BlacklistOpt += BLPath;
776  CmdArgs.push_back(Args.MakeArgString(BlacklistOpt));
777  }
778  for (const auto &Dep : ExtraDeps) {
779  SmallString<64> ExtraDepOpt("-fdepfile-entry=");
780  ExtraDepOpt += Dep;
781  CmdArgs.push_back(Args.MakeArgString(ExtraDepOpt));
782  }
783 
784  if (MsanTrackOrigins)
785  CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins=" +
786  llvm::utostr(MsanTrackOrigins)));
787 
788  if (MsanUseAfterDtor)
789  CmdArgs.push_back("-fsanitize-memory-use-after-dtor");
790 
791  // FIXME: Pass these parameters as function attributes, not as -llvm flags.
792  if (!TsanMemoryAccess) {
793  CmdArgs.push_back("-mllvm");
794  CmdArgs.push_back("-tsan-instrument-memory-accesses=0");
795  CmdArgs.push_back("-mllvm");
796  CmdArgs.push_back("-tsan-instrument-memintrinsics=0");
797  }
798  if (!TsanFuncEntryExit) {
799  CmdArgs.push_back("-mllvm");
800  CmdArgs.push_back("-tsan-instrument-func-entry-exit=0");
801  }
802  if (!TsanAtomics) {
803  CmdArgs.push_back("-mllvm");
804  CmdArgs.push_back("-tsan-instrument-atomics=0");
805  }
806 
807  if (CfiCrossDso)
808  CmdArgs.push_back("-fsanitize-cfi-cross-dso");
809 
810  if (Stats)
811  CmdArgs.push_back("-fsanitize-stats");
812 
813  if (MinimalRuntime)
814  CmdArgs.push_back("-fsanitize-minimal-runtime");
815 
816  if (AsanFieldPadding)
817  CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-field-padding=" +
818  llvm::utostr(AsanFieldPadding)));
819 
820  if (AsanUseAfterScope)
821  CmdArgs.push_back("-fsanitize-address-use-after-scope");
822 
823  if (AsanGlobalsDeadStripping)
824  CmdArgs.push_back("-fsanitize-address-globals-dead-stripping");
825 
826  // MSan: Workaround for PR16386.
827  // ASan: This is mainly to help LSan with cases such as
828  // https://code.google.com/p/address-sanitizer/issues/detail?id=373
829  // We can't make this conditional on -fsanitize=leak, as that flag shouldn't
830  // affect compilation.
831  if (Sanitizers.has(Memory) || Sanitizers.has(Address))
832  CmdArgs.push_back("-fno-assume-sane-operator-new");
833 
834  // Require -fvisibility= flag on non-Windows when compiling if vptr CFI is
835  // enabled.
836  if (Sanitizers.hasOneOf(CFIClasses) && !TC.getTriple().isOSWindows() &&
837  !Args.hasArg(options::OPT_fvisibility_EQ)) {
838  TC.getDriver().Diag(clang::diag::err_drv_argument_only_allowed_with)
839  << lastArgumentForMask(TC.getDriver(), Args,
840  Sanitizers.Mask & CFIClasses)
841  << "-fvisibility=";
842  }
843 }
844 
845 SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
846  bool DiagnoseErrors) {
847  assert((A->getOption().matches(options::OPT_fsanitize_EQ) ||
848  A->getOption().matches(options::OPT_fno_sanitize_EQ) ||
849  A->getOption().matches(options::OPT_fsanitize_recover_EQ) ||
850  A->getOption().matches(options::OPT_fno_sanitize_recover_EQ) ||
851  A->getOption().matches(options::OPT_fsanitize_trap_EQ) ||
852  A->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) &&
853  "Invalid argument in parseArgValues!");
854  SanitizerMask Kinds = 0;
855  for (int i = 0, n = A->getNumValues(); i != n; ++i) {
856  const char *Value = A->getValue(i);
858  // Special case: don't accept -fsanitize=all.
859  if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
860  0 == strcmp("all", Value))
861  Kind = 0;
862  // Similarly, don't accept -fsanitize=efficiency-all.
863  else if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
864  0 == strcmp("efficiency-all", Value))
865  Kind = 0;
866  else
867  Kind = parseSanitizerValue(Value, /*AllowGroups=*/true);
868 
869  if (Kind)
870  Kinds |= Kind;
871  else if (DiagnoseErrors)
872  D.Diag(clang::diag::err_drv_unsupported_option_argument)
873  << A->getOption().getName() << Value;
874  }
875  return Kinds;
876 }
877 
878 int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A) {
879  assert(A->getOption().matches(options::OPT_fsanitize_coverage) ||
880  A->getOption().matches(options::OPT_fno_sanitize_coverage));
881  int Features = 0;
882  for (int i = 0, n = A->getNumValues(); i != n; ++i) {
883  const char *Value = A->getValue(i);
884  int F = llvm::StringSwitch<int>(Value)
885  .Case("func", CoverageFunc)
886  .Case("bb", CoverageBB)
887  .Case("edge", CoverageEdge)
888  .Case("indirect-calls", CoverageIndirCall)
889  .Case("trace-bb", CoverageTraceBB)
890  .Case("trace-cmp", CoverageTraceCmp)
891  .Case("trace-div", CoverageTraceDiv)
892  .Case("trace-gep", CoverageTraceGep)
893  .Case("8bit-counters", Coverage8bitCounters)
894  .Case("trace-pc", CoverageTracePC)
895  .Case("trace-pc-guard", CoverageTracePCGuard)
896  .Case("no-prune", CoverageNoPrune)
897  .Case("inline-8bit-counters", CoverageInline8bitCounters)
898  .Case("pc-table", CoveragePCTable)
899  .Case("stack-depth", CoverageStackDepth)
900  .Default(0);
901  if (F == 0)
902  D.Diag(clang::diag::err_drv_unsupported_option_argument)
903  << A->getOption().getName() << Value;
904  Features |= F;
905  }
906  return Features;
907 }
908 
909 std::string lastArgumentForMask(const Driver &D, const llvm::opt::ArgList &Args,
910  SanitizerMask Mask) {
911  for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(),
912  E = Args.rend();
913  I != E; ++I) {
914  const auto *Arg = *I;
915  if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
916  SanitizerMask AddKinds =
917  expandSanitizerGroups(parseArgValues(D, Arg, false));
918  if (AddKinds & Mask)
919  return describeSanitizeArg(Arg, Mask);
920  } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
921  SanitizerMask RemoveKinds =
922  expandSanitizerGroups(parseArgValues(D, Arg, false));
923  Mask &= ~RemoveKinds;
924  }
925  }
926  llvm_unreachable("arg list didn't provide expected value");
927 }
928 
929 std::string describeSanitizeArg(const llvm::opt::Arg *A, SanitizerMask Mask) {
930  assert(A->getOption().matches(options::OPT_fsanitize_EQ)
931  && "Invalid argument in describeSanitizerArg!");
932 
933  std::string Sanitizers;
934  for (int i = 0, n = A->getNumValues(); i != n; ++i) {
936  parseSanitizerValue(A->getValue(i), /*AllowGroups=*/true)) &
937  Mask) {
938  if (!Sanitizers.empty())
939  Sanitizers += ",";
940  Sanitizers += A->getValue(i);
941  }
942  }
943 
944  assert(!Sanitizers.empty() && "arg didn't provide expected value");
945  return "-fsanitize=" + Sanitizers;
946 }
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:207
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:317
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:164
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:514
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:210
static bool getDefaultBlacklist(const Driver &D, SanitizerMask Kinds, std::string &BLPath)
const llvm::Triple & getTriple() const
Definition: ToolChain.h:166
virtual SanitizerMask getSupportedSanitizers() const
Return sanitizers which are available in this toolchain.
Definition: ToolChain.cpp:730
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:72
std::string ResourceDir
The path to the compiler resource directory.
Definition: Driver.h:139