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