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