blob: 43209f01e247b0115698f4703ccff7d7ce36b7d6 [file] [log] [blame]
Alexey Samsonov442c60a2013-08-08 10:11:02 +00001//===--- 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//===----------------------------------------------------------------------===//
Alexey Samsonov1b8f12d2013-08-19 09:14:21 +00009#include "clang/Driver/SanitizerArgs.h"
Alexey Samsonov442c60a2013-08-08 10:11:02 +000010
11#include "clang/Driver/Driver.h"
12#include "clang/Driver/DriverDiagnostic.h"
13#include "clang/Driver/Options.h"
14#include "clang/Driver/ToolChain.h"
Alexey Samsonovf064ad52013-08-19 13:59:22 +000015#include "llvm/ADT/OwningPtr.h"
Alexey Samsonov442c60a2013-08-08 10:11:02 +000016#include "llvm/ADT/StringSwitch.h"
17#include "llvm/Support/FileSystem.h"
18#include "llvm/Support/Path.h"
Alexey Samsonovf064ad52013-08-19 13:59:22 +000019#include "llvm/Transforms/Utils/SpecialCaseList.h"
Alexey Samsonov442c60a2013-08-08 10:11:02 +000020
21using namespace clang::driver;
22using namespace llvm::opt;
23
Alexey Samsonov1e9fdc12013-08-08 11:32:17 +000024void SanitizerArgs::clear() {
25 Kind = 0;
26 BlacklistFile = "";
27 MsanTrackOrigins = false;
Peter Collingbournec6911a22013-11-01 18:16:25 +000028 AsanZeroBaseShadow = false;
Alexey Samsonov1e9fdc12013-08-08 11:32:17 +000029 UbsanTrapOnError = false;
30}
31
32SanitizerArgs::SanitizerArgs() {
33 clear();
34}
Alexey Samsonov442c60a2013-08-08 10:11:02 +000035
Peter Collingbournec6911a22013-11-01 18:16:25 +000036SanitizerArgs::SanitizerArgs(const ToolChain &TC,
37 const llvm::opt::ArgList &Args) {
Alexey Samsonov1e9fdc12013-08-08 11:32:17 +000038 clear();
Peter Collingbournec6911a22013-11-01 18:16:25 +000039 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) {
Alexey Samsonov442c60a2013-08-08 10:11:02 +000049 unsigned Add, Remove;
50 if (!parse(D, Args, *I, Add, Remove, true))
51 continue;
52 (*I)->claim();
Peter Collingbournec6911a22013-11-01 18:16:25 +000053
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
Alexey Samsonov442c60a2013-08-08 10:11:02 +000071 Kind |= Add;
Alexey Samsonov442c60a2013-08-08 10:11:02 +000072 }
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).
Peter Collingbournec6911a22013-11-01 18:16:25 +0000134 if ((Kind & AddressFull) != 0 && (AllAdd & Address) == 0)
Alexey Samsonov442c60a2013-08-08 10:11:02 +0000135 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();
Alexey Samsonovf064ad52013-08-19 13:59:22 +0000144 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 {
Alexey Samsonov442c60a2013-08-08 10:11:02 +0000154 D.Diag(diag::err_drv_no_such_file) << BLPath;
Alexey Samsonovf064ad52013-08-19 13:59:22 +0000155 }
Alexey Samsonov442c60a2013-08-08 10:11:02 +0000156 }
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) {
Peter Collingbournec6911a22013-11-01 18:16:25 +0000175 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 }
Alexey Samsonov442c60a2013-08-08 10:11:02 +0000187 }
188}
189
Peter Collingbournec6911a22013-11-01 18:16:25 +0000190void SanitizerArgs::addArgs(const llvm::opt::ArgList &Args,
Alexey Samsonov442c60a2013-08-08 10:11:02 +0000191 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
Peter Collingbournec6911a22013-11-01 18:16:25 +0000210 if (AsanZeroBaseShadow)
211 CmdArgs.push_back(
212 Args.MakeArgString("-fsanitize-address-zero-base-shadow"));
Alexey Samsonov442c60a2013-08-08 10:11:02 +0000213
214 // Workaround for PR16386.
215 if (needsMsanRt())
216 CmdArgs.push_back(Args.MakeArgString("-fno-assume-sane-operator-new"));
217}
218
Alexey Samsonov442c60a2013-08-08 10:11:02 +0000219unsigned SanitizerArgs::parse(const char *Value) {
220 unsigned ParsedKind = llvm::StringSwitch<SanitizeKind>(Value)
221#define SANITIZER(NAME, ID) .Case(NAME, ID)
Peter Collingbournec6911a22013-11-01 18:16:25 +0000222#define SANITIZER_GROUP(NAME, ID, ALIAS) .Case(NAME, ID##Group)
Alexey Samsonov442c60a2013-08-08 10:11:02 +0000223#include "clang/Basic/Sanitizers.def"
224 .Default(SanitizeKind());
Kostya Serebryanyd85ec0e2013-09-23 09:52:37 +0000225 // Assume -fsanitize=address implies -fsanitize=init-order,use-after-return.
Alexey Samsonov442c60a2013-08-08 10:11:02 +0000226 // FIXME: This should be either specified in Sanitizers.def, or go away when
Kostya Serebryanyd85ec0e2013-09-23 09:52:37 +0000227 // we get rid of "-fsanitize=init-order,use-after-return" flags at all.
Alexey Samsonov442c60a2013-08-08 10:11:02 +0000228 if (ParsedKind & Address)
Kostya Serebryanyd85ec0e2013-09-23 09:52:37 +0000229 ParsedKind |= InitOrder | UseAfterReturn;
Alexey Samsonov442c60a2013-08-08 10:11:02 +0000230 return ParsedKind;
231}
232
Peter Collingbournec6911a22013-11-01 18:16:25 +0000233unsigned 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
Alexey Samsonov442c60a2013-08-08 10:11:02 +0000281unsigned 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)) {
Richard Smith69170e62013-10-22 22:51:04 +0000318 Add = LocalBounds;
319 DeprecatedReplacement = "-fsanitize=local-bounds";
Alexey Samsonov442c60a2013-08-08 10:11:02 +0000320 } 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) &&
Peter Collingbournec6911a22013-11-01 18:16:25 +0000344 (expandGroups(Add) & Kind))
Alexey Samsonov442c60a2013-08-08 10:11:02 +0000345 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
Peter Collingbournec6911a22013-11-01 18:16:25 +0000357 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 }
Alexey Samsonov442c60a2013-08-08 10:11:02 +0000365
Peter Collingbournec6911a22013-11-01 18:16:25 +0000366 assert(!Sanitizers.empty() && "arg didn't provide expected value");
367 return "-fsanitize=" + Sanitizers;
Alexey Samsonov442c60a2013-08-08 10:11:02 +0000368}
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";
Peter Collingbourne5d27a512013-08-14 18:54:18 +0000379 else if (Kind & NeedsDfsanRt)
380 BlacklistFile = "dfsan_abilist.txt";
381
Alexey Samsonov442c60a2013-08-08 10:11:02 +0000382 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}