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