blob: d09378c4f00802de7237abc5484ec1d003abe33a [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"
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +000014#include "llvm/ADT/StringExtras.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 Samsonovb7dd3292014-07-09 19:40:08 +000018#include "llvm/Support/SpecialCaseList.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000019#include <memory>
Alexey Samsonovcf055962013-08-08 10:11:02 +000020
21using namespace clang::driver;
22using namespace llvm::opt;
23
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000024namespace {
25/// Assign ordinals to possible values of -fsanitize= flag.
26/// We use the ordinal values as bit positions within \c SanitizeKind.
27enum SanitizeOrdinal {
28#define SANITIZER(NAME, ID) SO_##ID,
29#define SANITIZER_GROUP(NAME, ID, ALIAS) SO_##ID##Group,
30#include "clang/Basic/Sanitizers.def"
31 SO_Count
32};
33
34/// Represents a set of sanitizer kinds. It is also used to define:
35/// 1) set of sanitizers each sanitizer group expands into.
36/// 2) set of sanitizers sharing a specific property (e.g.
37/// all sanitizers with zero-base shadow).
38enum SanitizeKind {
39#define SANITIZER(NAME, ID) ID = 1 << SO_##ID,
40#define SANITIZER_GROUP(NAME, ID, ALIAS) \
41ID = ALIAS, ID##Group = 1 << SO_##ID##Group,
42#include "clang/Basic/Sanitizers.def"
43 NeedsUbsanRt = Undefined | Integer,
44 NotAllowedWithTrap = Vptr,
Dmitry Vyukov43419a72014-11-21 12:19:01 +000045 RequiresPIE = Memory | DataFlow,
Kostya Serebryany2d88f3d2015-01-06 01:02:48 +000046 NeedsUnwindTables = Address | Thread | Memory | DataFlow,
Alexey Samsonov88459522015-01-12 22:39:12 +000047 SupportsCoverage = Address | Memory | Leak | Undefined | Integer,
48 RecoverableByDefault = Undefined | Integer,
49 Unrecoverable = Address | Unreachable | Return,
Peter Collingbournea4ccff32015-02-20 20:30:56 +000050 LegacyFsanitizeRecoverMask = Undefined | Integer,
51 NeedsLTO = CFIVptr,
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000052};
53}
54
55/// Returns true if set of \p Sanitizers contain at least one sanitizer from
56/// \p Kinds.
57static bool hasOneOf(const clang::SanitizerSet &Sanitizers, unsigned Kinds) {
58#define SANITIZER(NAME, ID) \
59 if (Sanitizers.has(clang::SanitizerKind::ID) && (Kinds & ID)) \
60 return true;
61#include "clang/Basic/Sanitizers.def"
62 return false;
63}
64
65/// Adds all sanitizers from \p Kinds to \p Sanitizers.
66static void addAllOf(clang::SanitizerSet &Sanitizers, unsigned Kinds) {
67#define SANITIZER(NAME, ID) \
68 if (Kinds & ID) \
69 Sanitizers.set(clang::SanitizerKind::ID, true);
70#include "clang/Basic/Sanitizers.def"
71}
72
73static unsigned toSanitizeKind(clang::SanitizerKind K) {
74#define SANITIZER(NAME, ID) \
75 if (K == clang::SanitizerKind::ID) \
76 return ID;
77#include "clang/Basic/Sanitizers.def"
78 llvm_unreachable("Invalid SanitizerKind!");
79}
80
81/// Parse a single value from a -fsanitize= or -fno-sanitize= value list.
82/// Returns a member of the \c SanitizeKind enumeration, or \c 0
83/// if \p Value is not known.
84static unsigned parseValue(const char *Value);
85
86/// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
87/// invalid components. Returns OR of members of \c SanitizeKind enumeration.
88static unsigned parseArgValues(const Driver &D, const llvm::opt::Arg *A,
89 bool DiagnoseErrors);
90
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000091/// Produce an argument string from ArgList \p Args, which shows how it
92/// provides some sanitizer kind from \p Mask. For example, the argument list
93/// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt
94/// would produce "-fsanitize=vptr".
95static std::string lastArgumentForMask(const Driver &D,
96 const llvm::opt::ArgList &Args,
97 unsigned Mask);
98
99static std::string lastArgumentForKind(const Driver &D,
100 const llvm::opt::ArgList &Args,
101 clang::SanitizerKind K) {
102 return lastArgumentForMask(D, Args, toSanitizeKind(K));
103}
104
105/// Produce an argument string from argument \p A, which shows how it provides
106/// a value in \p Mask. For instance, the argument
107/// "-fsanitize=address,alignment" with mask \c NeedsUbsanRt would produce
108/// "-fsanitize=alignment".
109static std::string describeSanitizeArg(const llvm::opt::Arg *A, unsigned Mask);
110
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000111/// Produce a string containing comma-separated names of sanitizers in \p
112/// Sanitizers set.
113static std::string toString(const clang::SanitizerSet &Sanitizers);
114
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000115/// For each sanitizer group bit set in \p Kinds, set the bits for sanitizers
116/// this group enables.
117static unsigned expandGroups(unsigned Kinds);
118
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000119static unsigned getToolchainUnsupportedKinds(const ToolChain &TC) {
120 bool IsFreeBSD = TC.getTriple().getOS() == llvm::Triple::FreeBSD;
121 bool IsLinux = TC.getTriple().getOS() == llvm::Triple::Linux;
122 bool IsX86 = TC.getTriple().getArch() == llvm::Triple::x86;
123 bool IsX86_64 = TC.getTriple().getArch() == llvm::Triple::x86_64;
Mohit K. Bhakkadf4c47f62015-01-22 07:21:22 +0000124 bool IsMIPS64 = TC.getTriple().getArch() == llvm::Triple::mips64 ||
125 TC.getTriple().getArch() == llvm::Triple::mips64el;
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000126
127 unsigned Unsupported = 0;
Mohit K. Bhakkadf4c47f62015-01-22 07:21:22 +0000128 if (!(IsLinux && (IsX86_64 || IsMIPS64))) {
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000129 Unsupported |= Memory | DataFlow;
130 }
131 if (!((IsLinux || IsFreeBSD) && IsX86_64)) {
132 Unsupported |= Thread;
133 }
134 if (!(IsLinux && (IsX86 || IsX86_64))) {
135 Unsupported |= Function;
136 }
137 return Unsupported;
138}
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000139
140bool SanitizerArgs::needsUbsanRt() const {
141 return !UbsanTrapOnError && hasOneOf(Sanitizers, NeedsUbsanRt);
142}
143
Dmitry Vyukov43419a72014-11-21 12:19:01 +0000144bool SanitizerArgs::requiresPIE() const {
145 return AsanZeroBaseShadow || hasOneOf(Sanitizers, RequiresPIE);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000146}
147
148bool SanitizerArgs::needsUnwindTables() const {
149 return hasOneOf(Sanitizers, NeedsUnwindTables);
150}
151
Peter Collingbournea4ccff32015-02-20 20:30:56 +0000152bool SanitizerArgs::needsLTO() const {
153 return hasOneOf(Sanitizers, CFIVptr);
154}
155
Alexey Samsonovbb14f342013-08-08 11:32:17 +0000156void SanitizerArgs::clear() {
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000157 Sanitizers.clear();
Alexey Samsonov88459522015-01-12 22:39:12 +0000158 RecoverableSanitizers.clear();
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000159 BlacklistFiles.clear();
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000160 SanitizeCoverage = 0;
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000161 MsanTrackOrigins = 0;
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000162 AsanFieldPadding = 0;
Peter Collingbourne32701642013-11-01 18:16:25 +0000163 AsanZeroBaseShadow = false;
Alexey Samsonovbb14f342013-08-08 11:32:17 +0000164 UbsanTrapOnError = false;
Alexey Samsonovbdfa6c22014-04-01 13:31:10 +0000165 AsanSharedRuntime = false;
Alexey Samsonov90490af2014-08-08 22:47:17 +0000166 LinkCXXRuntimes = false;
Alexey Samsonovbb14f342013-08-08 11:32:17 +0000167}
Alexey Samsonovcf055962013-08-08 10:11:02 +0000168
Peter Collingbourne32701642013-11-01 18:16:25 +0000169SanitizerArgs::SanitizerArgs(const ToolChain &TC,
170 const llvm::opt::ArgList &Args) {
Alexey Samsonovbb14f342013-08-08 11:32:17 +0000171 clear();
Peter Collingbourne32701642013-11-01 18:16:25 +0000172 unsigned AllRemove = 0; // During the loop below, the accumulated set of
173 // sanitizers disabled by the current sanitizer
174 // argument or any argument after it.
175 unsigned DiagnosedKinds = 0; // All Kinds we have diagnosed up to now.
176 // Used to deduplicate diagnostics.
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000177 unsigned Kinds = 0;
178 unsigned NotSupported = getToolchainUnsupportedKinds(TC);
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000179 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
180
Peter Collingbourne32701642013-11-01 18:16:25 +0000181 const Driver &D = TC.getDriver();
182 for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
183 I != E; ++I) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000184 const auto *Arg = *I;
185 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
186 Arg->claim();
187 unsigned Add = parseArgValues(D, Arg, true);
Peter Collingbourne32701642013-11-01 18:16:25 +0000188
Alexey Samsonov799f7932014-12-19 02:35:16 +0000189 // Avoid diagnosing any sanitizer which is disabled later.
190 Add &= ~AllRemove;
191 // At this point we have not expanded groups, so any unsupported
192 // sanitizers in Add are those which have been explicitly enabled.
193 // Diagnose them.
194 if (unsigned KindsToDiagnose = Add & NotSupported & ~DiagnosedKinds) {
195 // Only diagnose the new kinds.
196 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
197 D.Diag(diag::err_drv_unsupported_opt_for_target)
198 << Desc << TC.getTriple().str();
199 DiagnosedKinds |= KindsToDiagnose;
200 }
201 Add &= ~NotSupported;
Peter Collingbourne32701642013-11-01 18:16:25 +0000202
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000203 // Test for -fno-rtti + explicit -fsanitizer=vptr before expanding groups
204 // so we don't error out if -fno-rtti and -fsanitize=undefined were
205 // passed.
206 if (Add & SanitizeKind::Vptr &&
207 (RTTIMode == ToolChain::RM_DisabledImplicitly ||
208 RTTIMode == ToolChain::RM_DisabledExplicitly)) {
209 if (RTTIMode == ToolChain::RM_DisabledImplicitly)
210 // Warn about not having rtti enabled if the vptr sanitizer is
211 // explicitly enabled
212 D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default);
213 else {
214 const llvm::opt::Arg *NoRTTIArg = TC.getRTTIArg();
215 assert(NoRTTIArg &&
216 "RTTI disabled explicitly but we have no argument!");
217 D.Diag(diag::err_drv_argument_not_allowed_with)
218 << "-fsanitize=vptr" << NoRTTIArg->getAsString(Args);
219 }
220
221 // Take out the Vptr sanitizer from the enabled sanitizers
222 AllRemove |= SanitizeKind::Vptr;
223 }
224
Alexey Samsonov799f7932014-12-19 02:35:16 +0000225 Add = expandGroups(Add);
226 // Group expansion may have enabled a sanitizer which is disabled later.
227 Add &= ~AllRemove;
228 // Silently discard any unsupported sanitizers implicitly enabled through
229 // group expansion.
230 Add &= ~NotSupported;
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000231
Alexey Samsonov799f7932014-12-19 02:35:16 +0000232 Kinds |= Add;
233 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
234 Arg->claim();
235 unsigned Remove = parseArgValues(D, Arg, true);
236 AllRemove |= expandGroups(Remove);
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000237 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000238 }
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000239 addAllOf(Sanitizers, Kinds);
240
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000241 // We disable the vptr sanitizer if it was enabled by group expansion but RTTI
242 // is disabled.
243 if (Sanitizers.has(SanitizerKind::Vptr) &&
244 (RTTIMode == ToolChain::RM_DisabledImplicitly ||
245 RTTIMode == ToolChain::RM_DisabledExplicitly)) {
246 Kinds &= ~SanitizeKind::Vptr;
247 Sanitizers.set(SanitizerKind::Vptr, 0);
248 }
249
Alexey Samsonov88459522015-01-12 22:39:12 +0000250 // Parse -f(no-)?sanitize-recover flags.
251 unsigned RecoverableKinds = RecoverableByDefault;
252 unsigned DiagnosedUnrecoverableKinds = 0;
253 for (const auto *Arg : Args) {
254 if (Arg->getOption().matches(options::OPT_fsanitize_recover)) {
255 // FIXME: Add deprecation notice, and then remove this flag.
256 RecoverableKinds |= expandGroups(LegacyFsanitizeRecoverMask);
257 Arg->claim();
258 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover)) {
259 // FIXME: Add deprecation notice, and then remove this flag.
260 RecoverableKinds &= ~expandGroups(LegacyFsanitizeRecoverMask);
261 Arg->claim();
262 } else if (Arg->getOption().matches(options::OPT_fsanitize_recover_EQ)) {
263 unsigned Add = parseArgValues(D, Arg, true);
264 // Report error if user explicitly tries to recover from unrecoverable
265 // sanitizer.
266 if (unsigned KindsToDiagnose =
267 Add & Unrecoverable & ~DiagnosedUnrecoverableKinds) {
268 SanitizerSet SetToDiagnose;
269 addAllOf(SetToDiagnose, KindsToDiagnose);
270 D.Diag(diag::err_drv_unsupported_option_argument)
271 << Arg->getOption().getName() << toString(SetToDiagnose);
272 DiagnosedUnrecoverableKinds |= KindsToDiagnose;
273 }
274 RecoverableKinds |= expandGroups(Add);
275 Arg->claim();
276 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) {
277 RecoverableKinds &= ~expandGroups(parseArgValues(D, Arg, true));
278 Arg->claim();
279 }
280 }
281 RecoverableKinds &= Kinds;
282 RecoverableKinds &= ~Unrecoverable;
283 addAllOf(RecoverableSanitizers, RecoverableKinds);
Alexey Samsonovcf055962013-08-08 10:11:02 +0000284
285 UbsanTrapOnError =
Alexey Samsonovcf055962013-08-08 10:11:02 +0000286 Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error,
287 options::OPT_fno_sanitize_undefined_trap_on_error, false);
288
Alexey Samsonovcf055962013-08-08 10:11:02 +0000289 // Warn about undefined sanitizer options that require runtime support.
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000290 if (UbsanTrapOnError && hasOneOf(Sanitizers, NotAllowedWithTrap)) {
291 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
292 << lastArgumentForMask(D, Args, NotAllowedWithTrap)
Alexey Samsonovcb3f8122014-03-20 10:48:29 +0000293 << "-fsanitize-undefined-trap-on-error";
Alexey Samsonovcf055962013-08-08 10:11:02 +0000294 }
295
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000296 // Check for incompatible sanitizers.
297 bool NeedsAsan = Sanitizers.has(SanitizerKind::Address);
298 bool NeedsTsan = Sanitizers.has(SanitizerKind::Thread);
299 bool NeedsMsan = Sanitizers.has(SanitizerKind::Memory);
300 bool NeedsLsan = Sanitizers.has(SanitizerKind::Leak);
Alexey Samsonovcf055962013-08-08 10:11:02 +0000301 if (NeedsAsan && NeedsTsan)
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000302 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
303 << lastArgumentForKind(D, Args, SanitizerKind::Address)
304 << lastArgumentForKind(D, Args, SanitizerKind::Thread);
Alexey Samsonovcf055962013-08-08 10:11:02 +0000305 if (NeedsAsan && NeedsMsan)
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000306 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
307 << lastArgumentForKind(D, Args, SanitizerKind::Address)
308 << lastArgumentForKind(D, Args, SanitizerKind::Memory);
Alexey Samsonovcf055962013-08-08 10:11:02 +0000309 if (NeedsTsan && NeedsMsan)
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000310 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
311 << lastArgumentForKind(D, Args, SanitizerKind::Thread)
312 << lastArgumentForKind(D, Args, SanitizerKind::Memory);
Alexey Samsonovcf055962013-08-08 10:11:02 +0000313 if (NeedsLsan && NeedsTsan)
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000314 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
315 << lastArgumentForKind(D, Args, SanitizerKind::Leak)
316 << lastArgumentForKind(D, Args, SanitizerKind::Thread);
Alexey Samsonovcf055962013-08-08 10:11:02 +0000317 if (NeedsLsan && NeedsMsan)
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000318 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
319 << lastArgumentForKind(D, Args, SanitizerKind::Leak)
320 << lastArgumentForKind(D, Args, SanitizerKind::Memory);
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000321 // FIXME: Currently -fsanitize=leak is silently ignored in the presence of
Alexey Samsonovcf055962013-08-08 10:11:02 +0000322 // -fsanitize=address. Perhaps it should print an error, or perhaps
323 // -f(-no)sanitize=leak should change whether leak detection is enabled by
324 // default in ASan?
325
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000326 // Setup blacklist files.
327 // Add default blacklist from resource directory.
328 {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000329 std::string BLPath;
Alexey Samsonov59f34bb2014-11-14 00:46:39 +0000330 if (getDefaultBlacklist(D, BLPath) && llvm::sys::fs::exists(BLPath))
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000331 BlacklistFiles.push_back(BLPath);
332 }
333 // Parse -f(no-)sanitize-blacklist options.
334 for (const auto *Arg : Args) {
335 if (Arg->getOption().matches(options::OPT_fsanitize_blacklist)) {
336 Arg->claim();
337 std::string BLPath = Arg->getValue();
338 if (llvm::sys::fs::exists(BLPath))
339 BlacklistFiles.push_back(BLPath);
340 else
341 D.Diag(clang::diag::err_drv_no_such_file) << BLPath;
342 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_blacklist)) {
343 Arg->claim();
344 BlacklistFiles.clear();
345 }
346 }
347 // Validate blacklists format.
348 {
349 std::string BLError;
350 std::unique_ptr<llvm::SpecialCaseList> SCL(
351 llvm::SpecialCaseList::create(BlacklistFiles, BLError));
352 if (!SCL.get())
353 D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000354 }
355
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000356 // Parse -f[no-]sanitize-memory-track-origins[=level] options.
357 if (NeedsMsan) {
358 if (Arg *A =
359 Args.getLastArg(options::OPT_fsanitize_memory_track_origins_EQ,
360 options::OPT_fsanitize_memory_track_origins,
361 options::OPT_fno_sanitize_memory_track_origins)) {
362 if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) {
363 MsanTrackOrigins = 1;
364 } else if (A->getOption().matches(
365 options::OPT_fno_sanitize_memory_track_origins)) {
366 MsanTrackOrigins = 0;
367 } else {
368 StringRef S = A->getValue();
369 if (S.getAsInteger(0, MsanTrackOrigins) || MsanTrackOrigins < 0 ||
370 MsanTrackOrigins > 2) {
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000371 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000372 }
373 }
374 }
375 }
376
Kostya Serebryany78df9d02014-12-17 21:46:33 +0000377 // Parse -fsanitize-coverage=N. Currently one of asan/msan/lsan is required.
Kostya Serebryany2d88f3d2015-01-06 01:02:48 +0000378 if (hasOneOf(Sanitizers, SupportsCoverage)) {
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000379 if (Arg *A = Args.getLastArg(options::OPT_fsanitize_coverage)) {
380 StringRef S = A->getValue();
381 // Legal values are 0..4.
382 if (S.getAsInteger(0, SanitizeCoverage) || SanitizeCoverage < 0 ||
383 SanitizeCoverage > 4)
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000384 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000385 }
386 }
387
Alexey Samsonovbdfa6c22014-04-01 13:31:10 +0000388 if (NeedsAsan) {
389 AsanSharedRuntime =
Evgeniy Stepanov6f0ae182014-06-05 11:14:00 +0000390 Args.hasArg(options::OPT_shared_libasan) ||
391 (TC.getTriple().getEnvironment() == llvm::Triple::Android);
Peter Collingbourne32701642013-11-01 18:16:25 +0000392 AsanZeroBaseShadow =
Evgeniy Stepanovd04b8612014-01-16 10:19:31 +0000393 (TC.getTriple().getEnvironment() == llvm::Triple::Android);
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000394 if (Arg *A =
395 Args.getLastArg(options::OPT_fsanitize_address_field_padding)) {
396 StringRef S = A->getValue();
397 // Legal values are 0 and 1, 2, but in future we may add more levels.
398 if (S.getAsInteger(0, AsanFieldPadding) || AsanFieldPadding < 0 ||
399 AsanFieldPadding > 2) {
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000400 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000401 }
402 }
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000403
404 if (Arg *WindowsDebugRTArg =
405 Args.getLastArg(options::OPT__SLASH_MTd, options::OPT__SLASH_MT,
406 options::OPT__SLASH_MDd, options::OPT__SLASH_MD,
407 options::OPT__SLASH_LDd, options::OPT__SLASH_LD)) {
408 switch (WindowsDebugRTArg->getOption().getID()) {
409 case options::OPT__SLASH_MTd:
410 case options::OPT__SLASH_MDd:
411 case options::OPT__SLASH_LDd:
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000412 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000413 << WindowsDebugRTArg->getAsString(Args)
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000414 << lastArgumentForKind(D, Args, SanitizerKind::Address);
415 D.Diag(clang::diag::note_drv_address_sanitizer_debug_runtime);
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000416 }
417 }
Alexey Samsonovbdfa6c22014-04-01 13:31:10 +0000418 }
Alexey Samsonov90490af2014-08-08 22:47:17 +0000419
420 // Parse -link-cxx-sanitizer flag.
421 LinkCXXRuntimes =
422 Args.hasArg(options::OPT_fsanitize_link_cxx_runtime) || D.CCCIsCXX();
Alexey Samsonovcf055962013-08-08 10:11:02 +0000423}
424
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000425static std::string toString(const clang::SanitizerSet &Sanitizers) {
426 std::string Res;
427#define SANITIZER(NAME, ID) \
428 if (Sanitizers.has(clang::SanitizerKind::ID)) { \
429 if (!Res.empty()) \
430 Res += ","; \
431 Res += NAME; \
432 }
433#include "clang/Basic/Sanitizers.def"
434 return Res;
435}
436
Peter Collingbourne32701642013-11-01 18:16:25 +0000437void SanitizerArgs::addArgs(const llvm::opt::ArgList &Args,
Alexey Samsonovcf055962013-08-08 10:11:02 +0000438 llvm::opt::ArgStringList &CmdArgs) const {
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000439 if (Sanitizers.empty())
Alexey Samsonovcf055962013-08-08 10:11:02 +0000440 return;
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000441 CmdArgs.push_back(Args.MakeArgString("-fsanitize=" + toString(Sanitizers)));
442
Alexey Samsonov88459522015-01-12 22:39:12 +0000443 if (!RecoverableSanitizers.empty())
444 CmdArgs.push_back(Args.MakeArgString("-fsanitize-recover=" +
445 toString(RecoverableSanitizers)));
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000446
447 if (UbsanTrapOnError)
448 CmdArgs.push_back("-fsanitize-undefined-trap-on-error");
449
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000450 for (const auto &BLPath : BlacklistFiles) {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000451 SmallString<64> BlacklistOpt("-fsanitize-blacklist=");
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000452 BlacklistOpt += BLPath;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000453 CmdArgs.push_back(Args.MakeArgString(BlacklistOpt));
454 }
455
456 if (MsanTrackOrigins)
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000457 CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins=" +
458 llvm::utostr(MsanTrackOrigins)));
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000459 if (AsanFieldPadding)
460 CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-field-padding=" +
461 llvm::utostr(AsanFieldPadding)));
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000462 if (SanitizeCoverage)
463 CmdArgs.push_back(Args.MakeArgString("-fsanitize-coverage=" +
464 llvm::utostr(SanitizeCoverage)));
Sergey Matveev2ba87782015-02-17 15:09:33 +0000465 // MSan: Workaround for PR16386.
466 // ASan: This is mainly to help LSan with cases such as
467 // https://code.google.com/p/address-sanitizer/issues/detail?id=373
468 // We can't make this conditional on -fsanitize=leak, as that flag shouldn't
469 // affect compilation.
470 if (Sanitizers.has(SanitizerKind::Memory) ||
471 Sanitizers.has(SanitizerKind::Address))
Alexey Samsonovcf055962013-08-08 10:11:02 +0000472 CmdArgs.push_back(Args.MakeArgString("-fno-assume-sane-operator-new"));
473}
474
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000475bool SanitizerArgs::getDefaultBlacklist(const Driver &D, std::string &BLPath) {
476 const char *BlacklistFile = nullptr;
477 if (Sanitizers.has(SanitizerKind::Address))
478 BlacklistFile = "asan_blacklist.txt";
479 else if (Sanitizers.has(SanitizerKind::Memory))
480 BlacklistFile = "msan_blacklist.txt";
481 else if (Sanitizers.has(SanitizerKind::Thread))
482 BlacklistFile = "tsan_blacklist.txt";
483 else if (Sanitizers.has(SanitizerKind::DataFlow))
484 BlacklistFile = "dfsan_abilist.txt";
485
486 if (BlacklistFile) {
487 SmallString<64> Path(D.ResourceDir);
488 llvm::sys::path::append(Path, BlacklistFile);
489 BLPath = Path.str();
490 return true;
491 }
492 return false;
493}
494
495unsigned parseValue(const char *Value) {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000496 unsigned ParsedKind = llvm::StringSwitch<SanitizeKind>(Value)
497#define SANITIZER(NAME, ID) .Case(NAME, ID)
Peter Collingbourne32701642013-11-01 18:16:25 +0000498#define SANITIZER_GROUP(NAME, ID, ALIAS) .Case(NAME, ID##Group)
Alexey Samsonovcf055962013-08-08 10:11:02 +0000499#include "clang/Basic/Sanitizers.def"
500 .Default(SanitizeKind());
Alexey Samsonovcf055962013-08-08 10:11:02 +0000501 return ParsedKind;
502}
503
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000504unsigned expandGroups(unsigned Kinds) {
Peter Collingbourne32701642013-11-01 18:16:25 +0000505#define SANITIZER(NAME, ID)
506#define SANITIZER_GROUP(NAME, ID, ALIAS) if (Kinds & ID##Group) Kinds |= ID;
507#include "clang/Basic/Sanitizers.def"
508 return Kinds;
509}
510
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000511unsigned parseArgValues(const Driver &D, const llvm::opt::Arg *A,
512 bool DiagnoseErrors) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000513 assert((A->getOption().matches(options::OPT_fsanitize_EQ) ||
Alexey Samsonov88459522015-01-12 22:39:12 +0000514 A->getOption().matches(options::OPT_fno_sanitize_EQ) ||
515 A->getOption().matches(options::OPT_fsanitize_recover_EQ) ||
516 A->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) &&
Alexey Samsonov799f7932014-12-19 02:35:16 +0000517 "Invalid argument in parseArgValues!");
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000518 unsigned Kinds = 0;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000519 for (unsigned I = 0, N = A->getNumValues(); I != N; ++I) {
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000520 const char *Value = A->getValue(I);
521 unsigned Kind;
522 // Special case: don't accept -fsanitize=all.
523 if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
524 0 == strcmp("all", Value))
525 Kind = 0;
526 else
527 Kind = parseValue(Value);
528
529 if (Kind)
530 Kinds |= Kind;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000531 else if (DiagnoseErrors)
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000532 D.Diag(clang::diag::err_drv_unsupported_option_argument)
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000533 << A->getOption().getName() << Value;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000534 }
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000535 return Kinds;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000536}
537
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000538std::string lastArgumentForMask(const Driver &D, const llvm::opt::ArgList &Args,
539 unsigned Mask) {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000540 for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(),
541 E = Args.rend();
542 I != E; ++I) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000543 const auto *Arg = *I;
544 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
545 unsigned AddKinds = expandGroups(parseArgValues(D, Arg, false));
546 if (AddKinds & Mask)
547 return describeSanitizeArg(Arg, Mask);
548 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
549 unsigned RemoveKinds = expandGroups(parseArgValues(D, Arg, false));
550 Mask &= ~RemoveKinds;
551 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000552 }
553 llvm_unreachable("arg list didn't provide expected value");
554}
555
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000556std::string describeSanitizeArg(const llvm::opt::Arg *A, unsigned Mask) {
557 assert(A->getOption().matches(options::OPT_fsanitize_EQ)
558 && "Invalid argument in describeSanitizerArg!");
Alexey Samsonovcf055962013-08-08 10:11:02 +0000559
Peter Collingbourne32701642013-11-01 18:16:25 +0000560 std::string Sanitizers;
561 for (unsigned I = 0, N = A->getNumValues(); I != N; ++I) {
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000562 if (expandGroups(parseValue(A->getValue(I))) & Mask) {
Peter Collingbourne32701642013-11-01 18:16:25 +0000563 if (!Sanitizers.empty())
564 Sanitizers += ",";
565 Sanitizers += A->getValue(I);
566 }
567 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000568
Peter Collingbourne32701642013-11-01 18:16:25 +0000569 assert(!Sanitizers.empty() && "arg didn't provide expected value");
570 return "-fsanitize=" + Sanitizers;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000571}