1 //===--- SanitizerArgs.cpp - Arguments for sanitizer tools ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
9 #include "clang/Driver/SanitizerArgs.h"
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"
21 using namespace clang::driver;
22 using namespace llvm::opt;
24 void SanitizerArgs::clear() {
27 MsanTrackOrigins = false;
28 AsanZeroBaseShadow = false;
29 UbsanTrapOnError = false;
32 SanitizerArgs::SanitizerArgs() {
36 SanitizerArgs::SanitizerArgs(const ToolChain &TC,
37 const llvm::opt::ArgList &Args) {
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();
50 if (!parse(D, Args, *I, Add, Remove, true))
54 AllAdd |= expandGroups(Add);
55 AllRemove |= expandGroups(Remove);
57 // Avoid diagnosing any sanitizer which is disabled later.
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,
63 Add = expandGroups(Add);
64 // Group expansion may have enabled a sanitizer which is disabled later.
66 // Silently discard any unsupported sanitizers implicitly enabled through
68 Add = filterUnsupportedKinds(TC, Add, Args, *I, /*DiagnoseErrors=*/false,
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);
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";
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,
96 D.Diag(diag::err_drv_argument_not_allowed_with)
97 << lastArgumentForKind(D, Args, NotAllowedWithTrap)
98 << "-fsanitize-undefined-trap-on-error";
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
131 // If -fsanitize contains extra features of ASan, it should also
132 // explicitly contain -fsanitize=address (probably, turned off later in the
134 if ((Kind & AddressFull) != 0 && (AllAdd & Address) == 0)
135 D.Diag(diag::warn_drv_unused_sanitizer)
136 << lastArgumentForKind(D, Args, AddressFull)
137 << "-fsanitize=address";
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.
147 llvm::OwningPtr<llvm::SpecialCaseList> SCL(
148 llvm::SpecialCaseList::create(BLPath, BLError));
150 D.Diag(diag::err_drv_malformed_sanitizer_blacklist) << BLError;
152 BlacklistFile = BLPath;
154 D.Diag(diag::err_drv_no_such_file) << BLPath;
158 // If no -fsanitize-blacklist option is specified, try to look up for
159 // blacklist in the resource directory.
161 if (getDefaultBlacklistForKind(D, Kind, BLPath) &&
162 llvm::sys::fs::exists(BLPath))
163 BlacklistFile = BLPath;
166 // Parse -f(no-)sanitize-memory-track-origins options.
169 Args.hasFlag(options::OPT_fsanitize_memory_track_origins,
170 options::OPT_fno_sanitize_memory_track_origins,
173 // Parse -f(no-)sanitize-address-zero-base-shadow options.
175 bool IsAndroid = (TC.getTriple().getEnvironment() == llvm::Triple::Android);
176 bool ZeroBaseShadowDefault = IsAndroid;
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);
190 void SanitizerArgs::addArgs(const llvm::opt::ArgList &Args,
191 llvm::opt::ArgStringList &CmdArgs) const {
194 SmallString<256> SanitizeOpt("-fsanitize=");
195 #define SANITIZER(NAME, 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));
207 if (MsanTrackOrigins)
208 CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins"));
210 if (AsanZeroBaseShadow)
212 Args.MakeArgString("-fsanitize-address-zero-base-shadow"));
214 // Workaround for PR16386.
216 CmdArgs.push_back(Args.MakeArgString("-fno-assume-sane-operator-new"));
219 unsigned 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;
233 unsigned 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"
240 void SanitizerArgs::filterUnsupportedMask(const ToolChain &TC, unsigned &Kinds,
242 const llvm::opt::ArgList &Args,
243 const llvm::opt::Arg *A,
245 unsigned &DiagnosedKinds) {
246 unsigned MaskedKinds = Kinds & Mask;
250 // Do we have new kinds to diagnose?
251 if (DiagnoseErrors && (DiagnosedKinds & MaskedKinds) != MaskedKinds) {
252 // Only diagnose the new kinds.
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;
261 unsigned SanitizerArgs::filterUnsupportedKinds(const ToolChain &TC,
263 const llvm::opt::ArgList &Args,
264 const llvm::opt::Arg *A,
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);
274 if (!(IsLinux && (IsX86 || IsX86_64))) {
275 filterUnsupportedMask(TC, Kinds, Function, Args, A, DiagnoseErrors,
281 unsigned SanitizerArgs::parse(const Driver &D, const llvm::opt::Arg *A,
282 bool DiagnoseErrors) {
284 for (unsigned I = 0, N = A->getNumValues(); I != N; ++I) {
285 if (unsigned K = parse(A->getValue(I)))
287 else if (DiagnoseErrors)
288 D.Diag(diag::err_drv_unsupported_option_argument)
289 << A->getOption().getName() << A->getValue(I);
294 bool SanitizerArgs::parse(const Driver &D, const llvm::opt::ArgList &Args,
295 const llvm::opt::Arg *A, unsigned &Add,
296 unsigned &Remove, bool DiagnoseErrors) {
299 const char *DeprecatedReplacement = 0;
300 if (A->getOption().matches(options::OPT_faddress_sanitizer)) {
302 DeprecatedReplacement = "-fsanitize=address";
303 } else if (A->getOption().matches(options::OPT_fno_address_sanitizer)) {
305 DeprecatedReplacement = "-fno-sanitize=address";
306 } else if (A->getOption().matches(options::OPT_fthread_sanitizer)) {
308 DeprecatedReplacement = "-fsanitize=thread";
309 } else if (A->getOption().matches(options::OPT_fno_thread_sanitizer)) {
311 DeprecatedReplacement = "-fno-sanitize=thread";
312 } else if (A->getOption().matches(options::OPT_fcatch_undefined_behavior)) {
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)) {
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);
325 // Flag is not relevant to sanitizers.
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;
336 std::string SanitizerArgs::lastArgumentForKind(const Driver &D,
337 const llvm::opt::ArgList &Args,
339 for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(),
342 unsigned Add, Remove;
343 if (parse(D, Args, *I, Add, Remove, false) &&
344 (expandGroups(Add) & Kind))
345 return describeSanitizeArg(Args, *I, Kind);
348 llvm_unreachable("arg list didn't provide expected value");
351 std::string SanitizerArgs::describeSanitizeArg(const llvm::opt::ArgList &Args,
352 const llvm::opt::Arg *A,
354 if (!A->getOption().matches(options::OPT_fsanitize_EQ))
355 return A->getAsString(Args);
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())
362 Sanitizers += A->getValue(I);
366 assert(!Sanitizers.empty() && "arg didn't provide expected value");
367 return "-fsanitize=" + Sanitizers;
370 bool 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";
383 SmallString<64> Path(D.ResourceDir);
384 llvm::sys::path::append(Path, BlacklistFile);