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 "clang/Driver/Driver.h"
11 #include "clang/Driver/DriverDiagnostic.h"
12 #include "clang/Driver/Options.h"
13 #include "clang/Driver/ToolChain.h"
14 #include "llvm/ADT/StringExtras.h"
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/Support/FileSystem.h"
17 #include "llvm/Support/Path.h"
18 #include "llvm/Support/SpecialCaseList.h"
19 #include <memory>
20 
21 using namespace clang::driver;
22 using namespace llvm::opt;
23 
24 void SanitizerArgs::clear() {
25   Kind = 0;
26   BlacklistFile = "";
27   MsanTrackOrigins = 0;
28   AsanZeroBaseShadow = false;
29   UbsanTrapOnError = false;
30   AsanSharedRuntime = false;
31   LinkCXXRuntimes = false;
32 }
33 
34 SanitizerArgs::SanitizerArgs(const ToolChain &TC,
35                              const llvm::opt::ArgList &Args) {
36   clear();
37   unsigned AllAdd = 0;  // All kinds of sanitizers that were turned on
38                         // at least once (possibly, disabled further).
39   unsigned AllRemove = 0;  // During the loop below, the accumulated set of
40                            // sanitizers disabled by the current sanitizer
41                            // argument or any argument after it.
42   unsigned DiagnosedKinds = 0;  // All Kinds we have diagnosed up to now.
43                                 // Used to deduplicate diagnostics.
44   const Driver &D = TC.getDriver();
45   for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
46        I != E; ++I) {
47     unsigned Add, Remove;
48     if (!parse(D, Args, *I, Add, Remove, true))
49       continue;
50     (*I)->claim();
51 
52     AllAdd |= expandGroups(Add);
53     AllRemove |= expandGroups(Remove);
54 
55     // Avoid diagnosing any sanitizer which is disabled later.
56     Add &= ~AllRemove;
57     // At this point we have not expanded groups, so any unsupported sanitizers
58     // in Add are those which have been explicitly enabled. Diagnose them.
59     Add = filterUnsupportedKinds(TC, Add, Args, *I, /*DiagnoseErrors=*/true,
60                                  DiagnosedKinds);
61     Add = expandGroups(Add);
62     // Group expansion may have enabled a sanitizer which is disabled later.
63     Add &= ~AllRemove;
64     // Silently discard any unsupported sanitizers implicitly enabled through
65     // group expansion.
66     Add = filterUnsupportedKinds(TC, Add, Args, *I, /*DiagnoseErrors=*/false,
67                                  DiagnosedKinds);
68 
69     Kind |= Add;
70   }
71 
72   UbsanTrapOnError =
73     Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error,
74                  options::OPT_fno_sanitize_undefined_trap_on_error, false);
75 
76   // Warn about undefined sanitizer options that require runtime support.
77   if (UbsanTrapOnError && notAllowedWithTrap()) {
78     D.Diag(diag::err_drv_argument_not_allowed_with)
79       << lastArgumentForKind(D, Args, NotAllowedWithTrap)
80       << "-fsanitize-undefined-trap-on-error";
81   }
82 
83   // Only one runtime library can be used at once.
84   bool NeedsAsan = needsAsanRt();
85   bool NeedsTsan = needsTsanRt();
86   bool NeedsMsan = needsMsanRt();
87   bool NeedsLsan = needsLeakDetection();
88   if (NeedsAsan && NeedsTsan)
89     D.Diag(diag::err_drv_argument_not_allowed_with)
90       << lastArgumentForKind(D, Args, NeedsAsanRt)
91       << lastArgumentForKind(D, Args, NeedsTsanRt);
92   if (NeedsAsan && NeedsMsan)
93     D.Diag(diag::err_drv_argument_not_allowed_with)
94       << lastArgumentForKind(D, Args, NeedsAsanRt)
95       << lastArgumentForKind(D, Args, NeedsMsanRt);
96   if (NeedsTsan && NeedsMsan)
97     D.Diag(diag::err_drv_argument_not_allowed_with)
98       << lastArgumentForKind(D, Args, NeedsTsanRt)
99       << lastArgumentForKind(D, Args, NeedsMsanRt);
100   if (NeedsLsan && NeedsTsan)
101     D.Diag(diag::err_drv_argument_not_allowed_with)
102       << lastArgumentForKind(D, Args, NeedsLeakDetection)
103       << lastArgumentForKind(D, Args, NeedsTsanRt);
104   if (NeedsLsan && NeedsMsan)
105     D.Diag(diag::err_drv_argument_not_allowed_with)
106       << lastArgumentForKind(D, Args, NeedsLeakDetection)
107       << lastArgumentForKind(D, Args, NeedsMsanRt);
108   // FIXME: Currently -fsanitize=leak is silently ignored in the presence of
109   // -fsanitize=address. Perhaps it should print an error, or perhaps
110   // -f(-no)sanitize=leak should change whether leak detection is enabled by
111   // default in ASan?
112 
113   // Parse -f(no-)sanitize-blacklist options.
114   if (Arg *BLArg = Args.getLastArg(options::OPT_fsanitize_blacklist,
115                                    options::OPT_fno_sanitize_blacklist)) {
116     if (BLArg->getOption().matches(options::OPT_fsanitize_blacklist)) {
117       std::string BLPath = BLArg->getValue();
118       if (llvm::sys::fs::exists(BLPath)) {
119         // Validate the blacklist format.
120         std::string BLError;
121         std::unique_ptr<llvm::SpecialCaseList> SCL(
122             llvm::SpecialCaseList::create(BLPath, BLError));
123         if (!SCL.get())
124           D.Diag(diag::err_drv_malformed_sanitizer_blacklist) << BLError;
125         else
126           BlacklistFile = BLPath;
127       } else {
128         D.Diag(diag::err_drv_no_such_file) << BLPath;
129       }
130     }
131   } else {
132     // If no -fsanitize-blacklist option is specified, try to look up for
133     // blacklist in the resource directory.
134     std::string BLPath;
135     if (getDefaultBlacklistForKind(D, Kind, BLPath) &&
136         llvm::sys::fs::exists(BLPath))
137       BlacklistFile = BLPath;
138   }
139 
140   // Parse -f[no-]sanitize-memory-track-origins[=level] options.
141   if (NeedsMsan) {
142     if (Arg *A =
143             Args.getLastArg(options::OPT_fsanitize_memory_track_origins_EQ,
144                             options::OPT_fsanitize_memory_track_origins,
145                             options::OPT_fno_sanitize_memory_track_origins)) {
146       if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) {
147         MsanTrackOrigins = 1;
148       } else if (A->getOption().matches(
149                      options::OPT_fno_sanitize_memory_track_origins)) {
150         MsanTrackOrigins = 0;
151       } else {
152         StringRef S = A->getValue();
153         if (S.getAsInteger(0, MsanTrackOrigins) || MsanTrackOrigins < 0 ||
154             MsanTrackOrigins > 2) {
155           D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
156         }
157       }
158     }
159   }
160 
161   if (NeedsAsan) {
162     AsanSharedRuntime =
163         Args.hasArg(options::OPT_shared_libasan) ||
164         (TC.getTriple().getEnvironment() == llvm::Triple::Android);
165     AsanZeroBaseShadow =
166         (TC.getTriple().getEnvironment() == llvm::Triple::Android);
167   }
168 
169   // Parse -link-cxx-sanitizer flag.
170   LinkCXXRuntimes =
171       Args.hasArg(options::OPT_fsanitize_link_cxx_runtime) || D.CCCIsCXX();
172 }
173 
174 void SanitizerArgs::addArgs(const llvm::opt::ArgList &Args,
175                             llvm::opt::ArgStringList &CmdArgs) const {
176   if (!Kind)
177     return;
178   SmallString<256> SanitizeOpt("-fsanitize=");
179 #define SANITIZER(NAME, ID) \
180   if (Kind & ID) \
181     SanitizeOpt += NAME ",";
182 #include "clang/Basic/Sanitizers.def"
183   SanitizeOpt.pop_back();
184   CmdArgs.push_back(Args.MakeArgString(SanitizeOpt));
185   if (!BlacklistFile.empty()) {
186     SmallString<64> BlacklistOpt("-fsanitize-blacklist=");
187     BlacklistOpt += BlacklistFile;
188     CmdArgs.push_back(Args.MakeArgString(BlacklistOpt));
189   }
190 
191   if (MsanTrackOrigins)
192     CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins=" +
193                                          llvm::utostr(MsanTrackOrigins)));
194 
195   // Workaround for PR16386.
196   if (needsMsanRt())
197     CmdArgs.push_back(Args.MakeArgString("-fno-assume-sane-operator-new"));
198 }
199 
200 unsigned SanitizerArgs::parse(const char *Value) {
201   unsigned ParsedKind = llvm::StringSwitch<SanitizeKind>(Value)
202 #define SANITIZER(NAME, ID) .Case(NAME, ID)
203 #define SANITIZER_GROUP(NAME, ID, ALIAS) .Case(NAME, ID##Group)
204 #include "clang/Basic/Sanitizers.def"
205     .Default(SanitizeKind());
206   return ParsedKind;
207 }
208 
209 unsigned SanitizerArgs::expandGroups(unsigned Kinds) {
210 #define SANITIZER(NAME, ID)
211 #define SANITIZER_GROUP(NAME, ID, ALIAS) if (Kinds & ID##Group) Kinds |= ID;
212 #include "clang/Basic/Sanitizers.def"
213   return Kinds;
214 }
215 
216 void SanitizerArgs::filterUnsupportedMask(const ToolChain &TC, unsigned &Kinds,
217                                           unsigned Mask,
218                                           const llvm::opt::ArgList &Args,
219                                           const llvm::opt::Arg *A,
220                                           bool DiagnoseErrors,
221                                           unsigned &DiagnosedKinds) {
222   unsigned MaskedKinds = Kinds & Mask;
223   if (!MaskedKinds)
224     return;
225   Kinds &= ~Mask;
226   // Do we have new kinds to diagnose?
227   if (DiagnoseErrors && (DiagnosedKinds & MaskedKinds) != MaskedKinds) {
228     // Only diagnose the new kinds.
229     std::string Desc =
230         describeSanitizeArg(Args, A, MaskedKinds & ~DiagnosedKinds);
231     TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
232         << Desc << TC.getTriple().str();
233     DiagnosedKinds |= MaskedKinds;
234   }
235 }
236 
237 unsigned SanitizerArgs::filterUnsupportedKinds(const ToolChain &TC,
238                                                unsigned Kinds,
239                                                const llvm::opt::ArgList &Args,
240                                                const llvm::opt::Arg *A,
241                                                bool DiagnoseErrors,
242                                                unsigned &DiagnosedKinds) {
243   bool IsLinux = TC.getTriple().getOS() == llvm::Triple::Linux;
244   bool IsX86 = TC.getTriple().getArch() == llvm::Triple::x86;
245   bool IsX86_64 = TC.getTriple().getArch() == llvm::Triple::x86_64;
246   if (!(IsLinux && IsX86_64)) {
247     filterUnsupportedMask(TC, Kinds, Thread | Memory | DataFlow, Args, A,
248                           DiagnoseErrors, DiagnosedKinds);
249   }
250   if (!(IsLinux && (IsX86 || IsX86_64))) {
251     filterUnsupportedMask(TC, Kinds, Function, Args, A, DiagnoseErrors,
252                           DiagnosedKinds);
253   }
254   return Kinds;
255 }
256 
257 unsigned SanitizerArgs::parse(const Driver &D, const llvm::opt::Arg *A,
258                               bool DiagnoseErrors) {
259   unsigned Kind = 0;
260   for (unsigned I = 0, N = A->getNumValues(); I != N; ++I) {
261     if (unsigned K = parse(A->getValue(I)))
262       Kind |= K;
263     else if (DiagnoseErrors)
264       D.Diag(diag::err_drv_unsupported_option_argument)
265         << A->getOption().getName() << A->getValue(I);
266   }
267   return Kind;
268 }
269 
270 bool SanitizerArgs::parse(const Driver &D, const llvm::opt::ArgList &Args,
271                           const llvm::opt::Arg *A, unsigned &Add,
272                           unsigned &Remove, bool DiagnoseErrors) {
273   Add = 0;
274   Remove = 0;
275   if (A->getOption().matches(options::OPT_fsanitize_EQ)) {
276     Add = parse(D, A, DiagnoseErrors);
277   } else if (A->getOption().matches(options::OPT_fno_sanitize_EQ)) {
278     Remove = parse(D, A, DiagnoseErrors);
279   } else {
280     // Flag is not relevant to sanitizers.
281     return false;
282   }
283   return true;
284 }
285 
286 std::string SanitizerArgs::lastArgumentForKind(const Driver &D,
287                                                const llvm::opt::ArgList &Args,
288                                                unsigned Kind) {
289   for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(),
290                                                   E = Args.rend();
291        I != E; ++I) {
292     unsigned Add, Remove;
293     if (parse(D, Args, *I, Add, Remove, false) &&
294         (expandGroups(Add) & Kind))
295       return describeSanitizeArg(Args, *I, Kind);
296     Kind &= ~Remove;
297   }
298   llvm_unreachable("arg list didn't provide expected value");
299 }
300 
301 std::string SanitizerArgs::describeSanitizeArg(const llvm::opt::ArgList &Args,
302                                                const llvm::opt::Arg *A,
303                                                unsigned Mask) {
304   if (!A->getOption().matches(options::OPT_fsanitize_EQ))
305     return A->getAsString(Args);
306 
307   std::string Sanitizers;
308   for (unsigned I = 0, N = A->getNumValues(); I != N; ++I) {
309     if (expandGroups(parse(A->getValue(I))) & Mask) {
310       if (!Sanitizers.empty())
311         Sanitizers += ",";
312       Sanitizers += A->getValue(I);
313     }
314   }
315 
316   assert(!Sanitizers.empty() && "arg didn't provide expected value");
317   return "-fsanitize=" + Sanitizers;
318 }
319 
320 bool SanitizerArgs::getDefaultBlacklistForKind(const Driver &D, unsigned Kind,
321                                                std::string &BLPath) {
322   const char *BlacklistFile = nullptr;
323   if (Kind & NeedsAsanRt)
324     BlacklistFile = "asan_blacklist.txt";
325   else if (Kind & NeedsMsanRt)
326     BlacklistFile = "msan_blacklist.txt";
327   else if (Kind & NeedsTsanRt)
328     BlacklistFile = "tsan_blacklist.txt";
329   else if (Kind & NeedsDfsanRt)
330     BlacklistFile = "dfsan_abilist.txt";
331 
332   if (BlacklistFile) {
333     SmallString<64> Path(D.ResourceDir);
334     llvm::sys::path::append(Path, BlacklistFile);
335     BLPath = Path.str();
336     return true;
337   }
338   return false;
339 }
340