blob: f06cb0148e10a97facd846087d26b51af0631a9d [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"
14#include "llvm/ADT/StringSwitch.h"
15#include "llvm/Support/FileSystem.h"
16#include "llvm/Support/Path.h"
Alexey Samsonov0c127d72013-08-19 13:59:22 +000017#include "llvm/Transforms/Utils/SpecialCaseList.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000018#include <memory>
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;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000146 std::unique_ptr<llvm::SpecialCaseList> SCL(
Alexey Samsonov0c127d72013-08-19 13:59:22 +0000147 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);
Evgeniy Stepanovd04b8612014-01-16 10:19:31 +0000171 if (NeedsAsan)
Peter Collingbourne32701642013-11-01 18:16:25 +0000172 AsanZeroBaseShadow =
Evgeniy Stepanovd04b8612014-01-16 10:19:31 +0000173 (TC.getTriple().getEnvironment() == llvm::Triple::Android);
Alexey Samsonovcf055962013-08-08 10:11:02 +0000174}
175
Peter Collingbourne32701642013-11-01 18:16:25 +0000176void SanitizerArgs::addArgs(const llvm::opt::ArgList &Args,
Alexey Samsonovcf055962013-08-08 10:11:02 +0000177 llvm::opt::ArgStringList &CmdArgs) const {
178 if (!Kind)
179 return;
180 SmallString<256> SanitizeOpt("-fsanitize=");
181#define SANITIZER(NAME, ID) \
182 if (Kind & ID) \
183 SanitizeOpt += NAME ",";
184#include "clang/Basic/Sanitizers.def"
185 SanitizeOpt.pop_back();
186 CmdArgs.push_back(Args.MakeArgString(SanitizeOpt));
187 if (!BlacklistFile.empty()) {
188 SmallString<64> BlacklistOpt("-fsanitize-blacklist=");
189 BlacklistOpt += BlacklistFile;
190 CmdArgs.push_back(Args.MakeArgString(BlacklistOpt));
191 }
192
193 if (MsanTrackOrigins)
194 CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins"));
195
Alexey Samsonovcf055962013-08-08 10:11:02 +0000196 // Workaround for PR16386.
197 if (needsMsanRt())
198 CmdArgs.push_back(Args.MakeArgString("-fno-assume-sane-operator-new"));
199}
200
Alexey Samsonovcf055962013-08-08 10:11:02 +0000201unsigned SanitizerArgs::parse(const char *Value) {
202 unsigned ParsedKind = llvm::StringSwitch<SanitizeKind>(Value)
203#define SANITIZER(NAME, ID) .Case(NAME, ID)
Peter Collingbourne32701642013-11-01 18:16:25 +0000204#define SANITIZER_GROUP(NAME, ID, ALIAS) .Case(NAME, ID##Group)
Alexey Samsonovcf055962013-08-08 10:11:02 +0000205#include "clang/Basic/Sanitizers.def"
206 .Default(SanitizeKind());
Kostya Serebryanybedc6162013-09-23 09:52:37 +0000207 // Assume -fsanitize=address implies -fsanitize=init-order,use-after-return.
Alexey Samsonovcf055962013-08-08 10:11:02 +0000208 // FIXME: This should be either specified in Sanitizers.def, or go away when
Kostya Serebryanybedc6162013-09-23 09:52:37 +0000209 // we get rid of "-fsanitize=init-order,use-after-return" flags at all.
Alexey Samsonovcf055962013-08-08 10:11:02 +0000210 if (ParsedKind & Address)
Kostya Serebryanybedc6162013-09-23 09:52:37 +0000211 ParsedKind |= InitOrder | UseAfterReturn;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000212 return ParsedKind;
213}
214
Peter Collingbourne32701642013-11-01 18:16:25 +0000215unsigned SanitizerArgs::expandGroups(unsigned Kinds) {
216#define SANITIZER(NAME, ID)
217#define SANITIZER_GROUP(NAME, ID, ALIAS) if (Kinds & ID##Group) Kinds |= ID;
218#include "clang/Basic/Sanitizers.def"
219 return Kinds;
220}
221
222void SanitizerArgs::filterUnsupportedMask(const ToolChain &TC, unsigned &Kinds,
223 unsigned Mask,
224 const llvm::opt::ArgList &Args,
225 const llvm::opt::Arg *A,
226 bool DiagnoseErrors,
227 unsigned &DiagnosedKinds) {
228 unsigned MaskedKinds = Kinds & Mask;
229 if (!MaskedKinds)
230 return;
231 Kinds &= ~Mask;
232 // Do we have new kinds to diagnose?
233 if (DiagnoseErrors && (DiagnosedKinds & MaskedKinds) != MaskedKinds) {
234 // Only diagnose the new kinds.
235 std::string Desc =
236 describeSanitizeArg(Args, A, MaskedKinds & ~DiagnosedKinds);
237 TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
238 << Desc << TC.getTriple().str();
239 DiagnosedKinds |= MaskedKinds;
240 }
241}
242
243unsigned SanitizerArgs::filterUnsupportedKinds(const ToolChain &TC,
244 unsigned Kinds,
245 const llvm::opt::ArgList &Args,
246 const llvm::opt::Arg *A,
247 bool DiagnoseErrors,
248 unsigned &DiagnosedKinds) {
249 bool IsLinux = TC.getTriple().getOS() == llvm::Triple::Linux;
250 bool IsX86 = TC.getTriple().getArch() == llvm::Triple::x86;
251 bool IsX86_64 = TC.getTriple().getArch() == llvm::Triple::x86_64;
252 if (!(IsLinux && IsX86_64)) {
253 filterUnsupportedMask(TC, Kinds, Thread | Memory | DataFlow, Args, A,
254 DiagnoseErrors, DiagnosedKinds);
255 }
256 if (!(IsLinux && (IsX86 || IsX86_64))) {
257 filterUnsupportedMask(TC, Kinds, Function, Args, A, DiagnoseErrors,
258 DiagnosedKinds);
259 }
260 return Kinds;
261}
262
Alexey Samsonovcf055962013-08-08 10:11:02 +0000263unsigned SanitizerArgs::parse(const Driver &D, const llvm::opt::Arg *A,
264 bool DiagnoseErrors) {
265 unsigned Kind = 0;
266 for (unsigned I = 0, N = A->getNumValues(); I != N; ++I) {
267 if (unsigned K = parse(A->getValue(I)))
268 Kind |= K;
269 else if (DiagnoseErrors)
270 D.Diag(diag::err_drv_unsupported_option_argument)
271 << A->getOption().getName() << A->getValue(I);
272 }
273 return Kind;
274}
275
276bool SanitizerArgs::parse(const Driver &D, const llvm::opt::ArgList &Args,
277 const llvm::opt::Arg *A, unsigned &Add,
278 unsigned &Remove, bool DiagnoseErrors) {
279 Add = 0;
280 Remove = 0;
281 const char *DeprecatedReplacement = 0;
282 if (A->getOption().matches(options::OPT_faddress_sanitizer)) {
283 Add = Address;
284 DeprecatedReplacement = "-fsanitize=address";
285 } else if (A->getOption().matches(options::OPT_fno_address_sanitizer)) {
286 Remove = Address;
287 DeprecatedReplacement = "-fno-sanitize=address";
288 } else if (A->getOption().matches(options::OPT_fthread_sanitizer)) {
289 Add = Thread;
290 DeprecatedReplacement = "-fsanitize=thread";
291 } else if (A->getOption().matches(options::OPT_fno_thread_sanitizer)) {
292 Remove = Thread;
293 DeprecatedReplacement = "-fno-sanitize=thread";
294 } else if (A->getOption().matches(options::OPT_fcatch_undefined_behavior)) {
295 Add = UndefinedTrap;
296 DeprecatedReplacement =
297 "-fsanitize=undefined-trap -fsanitize-undefined-trap-on-error";
298 } else if (A->getOption().matches(options::OPT_fbounds_checking) ||
299 A->getOption().matches(options::OPT_fbounds_checking_EQ)) {
Richard Smith6b53e222013-10-22 22:51:04 +0000300 Add = LocalBounds;
301 DeprecatedReplacement = "-fsanitize=local-bounds";
Alexey Samsonovcf055962013-08-08 10:11:02 +0000302 } else if (A->getOption().matches(options::OPT_fsanitize_EQ)) {
303 Add = parse(D, A, DiagnoseErrors);
304 } else if (A->getOption().matches(options::OPT_fno_sanitize_EQ)) {
305 Remove = parse(D, A, DiagnoseErrors);
306 } else {
307 // Flag is not relevant to sanitizers.
308 return false;
309 }
310 // If this is a deprecated synonym, produce a warning directing users
311 // towards the new spelling.
312 if (DeprecatedReplacement && DiagnoseErrors)
313 D.Diag(diag::warn_drv_deprecated_arg)
314 << A->getAsString(Args) << DeprecatedReplacement;
315 return true;
316}
317
318std::string SanitizerArgs::lastArgumentForKind(const Driver &D,
319 const llvm::opt::ArgList &Args,
320 unsigned Kind) {
321 for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(),
322 E = Args.rend();
323 I != E; ++I) {
324 unsigned Add, Remove;
325 if (parse(D, Args, *I, Add, Remove, false) &&
Peter Collingbourne32701642013-11-01 18:16:25 +0000326 (expandGroups(Add) & Kind))
Alexey Samsonovcf055962013-08-08 10:11:02 +0000327 return describeSanitizeArg(Args, *I, Kind);
328 Kind &= ~Remove;
329 }
330 llvm_unreachable("arg list didn't provide expected value");
331}
332
333std::string SanitizerArgs::describeSanitizeArg(const llvm::opt::ArgList &Args,
334 const llvm::opt::Arg *A,
335 unsigned Mask) {
336 if (!A->getOption().matches(options::OPT_fsanitize_EQ))
337 return A->getAsString(Args);
338
Peter Collingbourne32701642013-11-01 18:16:25 +0000339 std::string Sanitizers;
340 for (unsigned I = 0, N = A->getNumValues(); I != N; ++I) {
341 if (expandGroups(parse(A->getValue(I))) & Mask) {
342 if (!Sanitizers.empty())
343 Sanitizers += ",";
344 Sanitizers += A->getValue(I);
345 }
346 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000347
Peter Collingbourne32701642013-11-01 18:16:25 +0000348 assert(!Sanitizers.empty() && "arg didn't provide expected value");
349 return "-fsanitize=" + Sanitizers;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000350}
351
352bool SanitizerArgs::getDefaultBlacklistForKind(const Driver &D, unsigned Kind,
353 std::string &BLPath) {
354 const char *BlacklistFile = 0;
355 if (Kind & NeedsAsanRt)
356 BlacklistFile = "asan_blacklist.txt";
357 else if (Kind & NeedsMsanRt)
358 BlacklistFile = "msan_blacklist.txt";
359 else if (Kind & NeedsTsanRt)
360 BlacklistFile = "tsan_blacklist.txt";
Peter Collingbourne276be3c2013-08-14 18:54:18 +0000361 else if (Kind & NeedsDfsanRt)
362 BlacklistFile = "dfsan_abilist.txt";
363
Alexey Samsonovcf055962013-08-08 10:11:02 +0000364 if (BlacklistFile) {
365 SmallString<64> Path(D.ResourceDir);
366 llvm::sys::path::append(Path, BlacklistFile);
367 BLPath = Path.str();
368 return true;
369 }
370 return false;
371}