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