blob: 91dad40152ea8f6c6a71d7a3b421fb04528ea94e [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"
David L. Jonesf561aba2017-03-08 01:02:16 +000010#include "ToolChains/CommonArgs.h"
Peter Collingbournebf59c342015-05-11 21:39:20 +000011#include "clang/Basic/Sanitizers.h"
Alexey Samsonovcf055962013-08-08 10:11:02 +000012#include "clang/Driver/Driver.h"
13#include "clang/Driver/DriverDiagnostic.h"
14#include "clang/Driver/Options.h"
15#include "clang/Driver/ToolChain.h"
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +000016#include "llvm/ADT/StringExtras.h"
Alexey Samsonovcf055962013-08-08 10:11:02 +000017#include "llvm/ADT/StringSwitch.h"
18#include "llvm/Support/FileSystem.h"
19#include "llvm/Support/Path.h"
Alexey Samsonovb7dd3292014-07-09 19:40:08 +000020#include "llvm/Support/SpecialCaseList.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000021#include <memory>
Alexey Samsonovcf055962013-08-08 10:11:02 +000022
Peter Collingbourne3eea6772015-05-11 21:39:14 +000023using namespace clang;
24using namespace clang::SanitizerKind;
Alexey Samsonovcf055962013-08-08 10:11:02 +000025using namespace clang::driver;
26using namespace llvm::opt;
27
Peter Collingbourne3eea6772015-05-11 21:39:14 +000028enum : SanitizerMask {
Vedant Kumar42c17ec2017-03-14 01:56:34 +000029 NeedsUbsanRt = Undefined | Integer | Nullability | CFI,
Alexey Samsonov9b873092015-06-25 23:14:32 +000030 NeedsUbsanCxxRt = Vptr | CFI,
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000031 NotAllowedWithTrap = Vptr,
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +000032 NotAllowedWithMinimalRuntime = Vptr,
Kostya Kortchinsky8acdc982017-11-03 17:04:13 +000033 RequiresPIE = DataFlow | Scudo,
Evgeniy Stepanov12817e52017-12-09 01:32:07 +000034 NeedsUnwindTables = Address | HWAddress | Thread | Memory | DataFlow,
35 SupportsCoverage = Address | HWAddress | KernelAddress | Memory | Leak |
36 Undefined | Integer | Nullability | DataFlow | Fuzzer |
37 FuzzerNoLink,
Vedant Kumar42c17ec2017-03-14 01:56:34 +000038 RecoverableByDefault = Undefined | Integer | Nullability,
Yury Gribov5bfeca12015-11-11 10:45:48 +000039 Unrecoverable = Unreachable | Return,
Peter Collingbournea4ccff32015-02-20 20:30:56 +000040 LegacyFsanitizeRecoverMask = Undefined | Integer,
Peter Collingbourne1a7488a2015-04-02 00:23:30 +000041 NeedsLTO = CFI,
Vedant Kumar42c17ec2017-03-14 01:56:34 +000042 TrappingSupported = (Undefined & ~Vptr) | UnsignedIntegerOverflow |
43 Nullability | LocalBounds | CFI,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +000044 TrappingDefault = CFI,
Peter Collingbourne3afb2662016-04-28 17:09:37 +000045 CFIClasses = CFIVCall | CFINVCall | CFIDerivedCast | CFIUnrelatedCast,
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +000046 CompatibleWithMinimalRuntime = TrappingSupported,
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000047};
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000048
49enum CoverageFeature {
50 CoverageFunc = 1 << 0,
51 CoverageBB = 1 << 1,
52 CoverageEdge = 1 << 2,
53 CoverageIndirCall = 1 << 3,
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000054 CoverageTraceBB = 1 << 4, // Deprecated.
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000055 CoverageTraceCmp = 1 << 5,
Kostya Serebryany3b419712016-08-30 01:27:03 +000056 CoverageTraceDiv = 1 << 6,
57 CoverageTraceGep = 1 << 7,
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000058 Coverage8bitCounters = 1 << 8, // Deprecated.
Kostya Serebryany3b419712016-08-30 01:27:03 +000059 CoverageTracePC = 1 << 9,
Kostya Serebryany60cdd612016-09-14 01:39:49 +000060 CoverageTracePCGuard = 1 << 10,
Kostya Serebryany50fb6182017-05-05 23:28:18 +000061 CoverageNoPrune = 1 << 11,
Kostya Serebryany61457762017-07-28 00:10:10 +000062 CoverageInline8bitCounters = 1 << 12,
63 CoveragePCTable = 1 << 13,
Matt Morehouse5c7fc762017-08-18 18:43:30 +000064 CoverageStackDepth = 1 << 14,
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000065};
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000066
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000067/// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
Peter Collingbourne3eea6772015-05-11 21:39:14 +000068/// invalid components. Returns a SanitizerMask.
69static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
70 bool DiagnoseErrors);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000071
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000072/// Parse -f(no-)?sanitize-coverage= flag values, diagnosing any invalid
73/// components. Returns OR of members of \c CoverageFeature enumeration.
74static int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A);
75
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000076/// Produce an argument string from ArgList \p Args, which shows how it
77/// provides some sanitizer kind from \p Mask. For example, the argument list
78/// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt
79/// would produce "-fsanitize=vptr".
80static std::string lastArgumentForMask(const Driver &D,
81 const llvm::opt::ArgList &Args,
Peter Collingbourne3eea6772015-05-11 21:39:14 +000082 SanitizerMask Mask);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000083
84/// Produce an argument string from argument \p A, which shows how it provides
85/// a value in \p Mask. For instance, the argument
86/// "-fsanitize=address,alignment" with mask \c NeedsUbsanRt would produce
87/// "-fsanitize=alignment".
Peter Collingbourne3eea6772015-05-11 21:39:14 +000088static std::string describeSanitizeArg(const llvm::opt::Arg *A,
89 SanitizerMask Mask);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000090
Alexey Samsonov1e715a62014-11-16 20:53:53 +000091/// Produce a string containing comma-separated names of sanitizers in \p
92/// Sanitizers set.
93static std::string toString(const clang::SanitizerSet &Sanitizers);
94
Richard Smith6cd48612018-02-20 23:17:41 +000095static void addDefaultBlacklists(const Driver &D, SanitizerMask Kinds,
96 std::vector<std::string> &BlacklistFiles) {
97 struct Blacklist {
98 const char *File;
99 SanitizerMask Mask;
100 } Blacklists[] = {{"asan_blacklist.txt", Address},
101 {"hwasan_blacklist.txt", HWAddress},
102 {"msan_blacklist.txt", Memory},
103 {"tsan_blacklist.txt", Thread},
104 {"dfsan_abilist.txt", DataFlow},
105 {"cfi_blacklist.txt", CFI},
106 {"ubsan_blacklist.txt", Undefined | Integer | Nullability}};
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000107
Richard Smith6cd48612018-02-20 23:17:41 +0000108 for (auto BL : Blacklists) {
109 if (!(Kinds & BL.Mask))
110 continue;
111
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000112 clang::SmallString<64> Path(D.ResourceDir);
Richard Smith6cd48612018-02-20 23:17:41 +0000113 llvm::sys::path::append(Path, "share", BL.File);
114 if (llvm::sys::fs::exists(Path))
115 BlacklistFiles.push_back(Path.str());
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000116 }
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000117}
118
Peter Collingbourne9881b782015-06-18 23:59:22 +0000119/// Sets group bits for every group that has at least one representative already
120/// enabled in \p Kinds.
121static SanitizerMask setGroupBits(SanitizerMask Kinds) {
122#define SANITIZER(NAME, ID)
123#define SANITIZER_GROUP(NAME, ID, ALIAS) \
124 if (Kinds & SanitizerKind::ID) \
125 Kinds |= SanitizerKind::ID##Group;
126#include "clang/Basic/Sanitizers.def"
127 return Kinds;
128}
129
130static SanitizerMask parseSanitizeTrapArgs(const Driver &D,
131 const llvm::opt::ArgList &Args) {
132 SanitizerMask TrapRemove = 0; // During the loop below, the accumulated set of
133 // sanitizers disabled by the current sanitizer
134 // argument or any argument after it.
135 SanitizerMask TrappingKinds = 0;
136 SanitizerMask TrappingSupportedWithGroups = setGroupBits(TrappingSupported);
137
138 for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
139 I != E; ++I) {
140 const auto *Arg = *I;
141 if (Arg->getOption().matches(options::OPT_fsanitize_trap_EQ)) {
142 Arg->claim();
143 SanitizerMask Add = parseArgValues(D, Arg, true);
144 Add &= ~TrapRemove;
145 if (SanitizerMask InvalidValues = Add & ~TrappingSupportedWithGroups) {
146 SanitizerSet S;
147 S.Mask = InvalidValues;
148 D.Diag(diag::err_drv_unsupported_option_argument) << "-fsanitize-trap"
149 << toString(S);
150 }
151 TrappingKinds |= expandSanitizerGroups(Add) & ~TrapRemove;
152 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) {
153 Arg->claim();
154 TrapRemove |= expandSanitizerGroups(parseArgValues(D, Arg, true));
155 } else if (Arg->getOption().matches(
156 options::OPT_fsanitize_undefined_trap_on_error)) {
157 Arg->claim();
158 TrappingKinds |=
159 expandSanitizerGroups(UndefinedGroup & ~TrapRemove) & ~TrapRemove;
160 } else if (Arg->getOption().matches(
161 options::OPT_fno_sanitize_undefined_trap_on_error)) {
162 Arg->claim();
163 TrapRemove |= expandSanitizerGroups(UndefinedGroup);
164 }
165 }
166
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000167 // Apply default trapping behavior.
168 TrappingKinds |= TrappingDefault & ~TrapRemove;
169
Peter Collingbourne9881b782015-06-18 23:59:22 +0000170 return TrappingKinds;
171}
172
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000173bool SanitizerArgs::needsUbsanRt() const {
Evgeniy Stepanovd5d36a12017-10-16 18:02:57 +0000174 // All of these include ubsan.
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000175 if (needsAsanRt() || needsMsanRt() || needsHwasanRt() || needsTsanRt() ||
176 needsDfsanRt() || needsLsanRt() || needsCfiDiagRt() || needsScudoRt())
Evgeniy Stepanovd5d36a12017-10-16 18:02:57 +0000177 return false;
178
179 return (Sanitizers.Mask & NeedsUbsanRt & ~TrapSanitizers.Mask) ||
180 CoverageFeatures;
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000181}
182
183bool SanitizerArgs::needsCfiRt() const {
Evgeniy Stepanovd5d36a12017-10-16 18:02:57 +0000184 return !(Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso &&
185 !ImplicitCfiRuntime;
Evgeniy Stepanove3fb51c2015-12-16 00:38:42 +0000186}
187
188bool SanitizerArgs::needsCfiDiagRt() const {
Evgeniy Stepanovd5d36a12017-10-16 18:02:57 +0000189 return (Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso &&
190 !ImplicitCfiRuntime;
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000191}
192
Dmitry Vyukov43419a72014-11-21 12:19:01 +0000193bool SanitizerArgs::requiresPIE() const {
Evgeniy Stepanov71554fe2015-10-21 21:28:49 +0000194 return NeedPIE || (Sanitizers.Mask & RequiresPIE);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000195}
196
197bool SanitizerArgs::needsUnwindTables() const {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000198 return Sanitizers.Mask & NeedsUnwindTables;
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000199}
200
Peter Collingbourne32701642013-11-01 18:16:25 +0000201SanitizerArgs::SanitizerArgs(const ToolChain &TC,
202 const llvm::opt::ArgList &Args) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000203 SanitizerMask AllRemove = 0; // During the loop below, the accumulated set of
204 // sanitizers disabled by the current sanitizer
205 // argument or any argument after it.
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000206 SanitizerMask AllAddedKinds = 0; // Mask of all sanitizers ever enabled by
207 // -fsanitize= flags (directly or via group
208 // expansion), some of which may be disabled
209 // later. Used to carefully prune
210 // unused-argument diagnostics.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000211 SanitizerMask DiagnosedKinds = 0; // All Kinds we have diagnosed up to now.
212 // Used to deduplicate diagnostics.
213 SanitizerMask Kinds = 0;
Alexey Samsonov9b873092015-06-25 23:14:32 +0000214 const SanitizerMask Supported = setGroupBits(TC.getSupportedSanitizers());
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000215 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
216
Peter Collingbourne32701642013-11-01 18:16:25 +0000217 const Driver &D = TC.getDriver();
Peter Collingbourne9881b782015-06-18 23:59:22 +0000218 SanitizerMask TrappingKinds = parseSanitizeTrapArgs(D, Args);
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000219 SanitizerMask InvalidTrappingKinds = TrappingKinds & NotAllowedWithTrap;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000220
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +0000221 MinimalRuntime =
222 Args.hasFlag(options::OPT_fsanitize_minimal_runtime,
223 options::OPT_fno_sanitize_minimal_runtime, MinimalRuntime);
224
Vedant Kumar7aacb652017-06-23 23:15:24 +0000225 // The object size sanitizer should not be enabled at -O0.
226 Arg *OptLevel = Args.getLastArg(options::OPT_O_Group);
227 bool RemoveObjectSizeAtO0 =
228 !OptLevel || OptLevel->getOption().matches(options::OPT_O0);
229
Peter Collingbourne32701642013-11-01 18:16:25 +0000230 for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
231 I != E; ++I) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000232 const auto *Arg = *I;
233 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
234 Arg->claim();
Vedant Kumar7aacb652017-06-23 23:15:24 +0000235 SanitizerMask Add = parseArgValues(D, Arg, /*AllowGroups=*/true);
236
237 if (RemoveObjectSizeAtO0) {
238 AllRemove |= SanitizerKind::ObjectSize;
239
240 // The user explicitly enabled the object size sanitizer. Warn that
241 // that this does nothing at -O0.
242 if (Add & SanitizerKind::ObjectSize)
243 D.Diag(diag::warn_drv_object_size_disabled_O0)
244 << Arg->getAsString(Args);
245 }
246
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000247 AllAddedKinds |= expandSanitizerGroups(Add);
Peter Collingbourne32701642013-11-01 18:16:25 +0000248
Alexey Samsonov799f7932014-12-19 02:35:16 +0000249 // Avoid diagnosing any sanitizer which is disabled later.
250 Add &= ~AllRemove;
251 // At this point we have not expanded groups, so any unsupported
252 // sanitizers in Add are those which have been explicitly enabled.
253 // Diagnose them.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000254 if (SanitizerMask KindsToDiagnose =
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000255 Add & InvalidTrappingKinds & ~DiagnosedKinds) {
Peter Collingbourne9881b782015-06-18 23:59:22 +0000256 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
257 D.Diag(diag::err_drv_argument_not_allowed_with)
258 << Desc << "-fsanitize-trap=undefined";
259 DiagnosedKinds |= KindsToDiagnose;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000260 }
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000261 Add &= ~InvalidTrappingKinds;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +0000262
263 if (MinimalRuntime) {
264 if (SanitizerMask KindsToDiagnose =
265 Add & NotAllowedWithMinimalRuntime & ~DiagnosedKinds) {
266 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
267 D.Diag(diag::err_drv_argument_not_allowed_with)
268 << Desc << "-fsanitize-minimal-runtime";
269 DiagnosedKinds |= KindsToDiagnose;
270 }
271 Add &= ~NotAllowedWithMinimalRuntime;
272 }
273
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000274 if (SanitizerMask KindsToDiagnose = Add & ~Supported & ~DiagnosedKinds) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000275 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
276 D.Diag(diag::err_drv_unsupported_opt_for_target)
277 << Desc << TC.getTriple().str();
278 DiagnosedKinds |= KindsToDiagnose;
279 }
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000280 Add &= Supported;
Peter Collingbourne32701642013-11-01 18:16:25 +0000281
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000282 // Test for -fno-rtti + explicit -fsanitizer=vptr before expanding groups
283 // so we don't error out if -fno-rtti and -fsanitize=undefined were
284 // passed.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000285 if (Add & Vptr &&
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000286 (RTTIMode == ToolChain::RM_DisabledImplicitly ||
287 RTTIMode == ToolChain::RM_DisabledExplicitly)) {
288 if (RTTIMode == ToolChain::RM_DisabledImplicitly)
289 // Warn about not having rtti enabled if the vptr sanitizer is
290 // explicitly enabled
291 D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default);
292 else {
293 const llvm::opt::Arg *NoRTTIArg = TC.getRTTIArg();
294 assert(NoRTTIArg &&
295 "RTTI disabled explicitly but we have no argument!");
296 D.Diag(diag::err_drv_argument_not_allowed_with)
297 << "-fsanitize=vptr" << NoRTTIArg->getAsString(Args);
298 }
299
300 // Take out the Vptr sanitizer from the enabled sanitizers
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000301 AllRemove |= Vptr;
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000302 }
303
Peter Collingbournebf59c342015-05-11 21:39:20 +0000304 Add = expandSanitizerGroups(Add);
Alexey Samsonov799f7932014-12-19 02:35:16 +0000305 // Group expansion may have enabled a sanitizer which is disabled later.
306 Add &= ~AllRemove;
307 // Silently discard any unsupported sanitizers implicitly enabled through
308 // group expansion.
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000309 Add &= ~InvalidTrappingKinds;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +0000310 if (MinimalRuntime) {
311 Add &= ~NotAllowedWithMinimalRuntime;
312 }
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000313 Add &= Supported;
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000314
George Karpenkovf2fc5b02017-04-24 18:23:24 +0000315 if (Add & Fuzzer)
George Karpenkov33613f62017-08-11 17:22:58 +0000316 Add |= FuzzerNoLink;
317
Matt Morehouse6ec75952017-08-25 22:01:21 +0000318 // Enable coverage if the fuzzing flag is set.
Matt Morehouse034126e2017-08-30 22:49:31 +0000319 if (Add & FuzzerNoLink) {
Kostya Serebryanya5231352017-09-01 18:34:36 +0000320 CoverageFeatures |= CoverageInline8bitCounters | CoverageIndirCall |
Matt Morehouse6ec75952017-08-25 22:01:21 +0000321 CoverageTraceCmp | CoveragePCTable;
Matt Morehouse034126e2017-08-30 22:49:31 +0000322 // Due to TLS differences, stack depth tracking is only enabled on Linux
323 if (TC.getTriple().isOSLinux())
324 CoverageFeatures |= CoverageStackDepth;
325 }
George Karpenkovf2fc5b02017-04-24 18:23:24 +0000326
Alexey Samsonov799f7932014-12-19 02:35:16 +0000327 Kinds |= Add;
328 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
329 Arg->claim();
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000330 SanitizerMask Remove = parseArgValues(D, Arg, true);
Peter Collingbournebf59c342015-05-11 21:39:20 +0000331 AllRemove |= expandSanitizerGroups(Remove);
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000332 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000333 }
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000334
Petr Hoseka14b4602018-03-07 01:27:03 +0000335 std::pair<SanitizerMask, SanitizerMask> IncompatibleGroups[] = {
336 std::make_pair(Address, Thread | Memory),
337 std::make_pair(Thread, Memory),
338 std::make_pair(Leak, Thread | Memory),
339 std::make_pair(KernelAddress, Address | Leak | Thread | Memory),
340 std::make_pair(HWAddress, Address | Thread | Memory | KernelAddress),
341 std::make_pair(Efficiency, Address | HWAddress | Leak | Thread | Memory |
342 KernelAddress),
343 std::make_pair(Scudo, Address | HWAddress | Leak | Thread | Memory |
344 KernelAddress | Efficiency),
345 std::make_pair(SafeStack, Address | HWAddress | Leak | Thread | Memory |
346 KernelAddress | Efficiency)};
347
Ed Schoutenfc79d2c2016-03-29 21:13:53 +0000348 // Enable toolchain specific default sanitizers if not explicitly disabled.
Petr Hoseka14b4602018-03-07 01:27:03 +0000349 SanitizerMask Default = TC.getDefaultSanitizers() & ~AllRemove;
350
Petr Hosek8b8d6bf2018-03-12 00:23:37 +0000351 // Disable default sanitizers that are incompatible with explicitly requested
352 // ones.
Petr Hoseka14b4602018-03-07 01:27:03 +0000353 for (auto G : IncompatibleGroups) {
354 SanitizerMask Group = G.first;
355 if ((Default & Group) && (Kinds & G.second))
356 Default &= ~Group;
357 }
358
359 Kinds |= Default;
Ed Schoutenfc79d2c2016-03-29 21:13:53 +0000360
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000361 // We disable the vptr sanitizer if it was enabled by group expansion but RTTI
362 // is disabled.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000363 if ((Kinds & Vptr) &&
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000364 (RTTIMode == ToolChain::RM_DisabledImplicitly ||
365 RTTIMode == ToolChain::RM_DisabledExplicitly)) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000366 Kinds &= ~Vptr;
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000367 }
368
Alexey Samsonov907880e2015-06-19 19:57:46 +0000369 // Check that LTO is enabled if we need it.
Teresa Johnson945bc502015-10-15 20:35:53 +0000370 if ((Kinds & NeedsLTO) && !D.isUsingLTO()) {
Alexey Samsonov907880e2015-06-19 19:57:46 +0000371 D.Diag(diag::err_drv_argument_only_allowed_with)
372 << lastArgumentForMask(D, Args, Kinds & NeedsLTO) << "-flto";
373 }
374
Alexey Samsonov9b873092015-06-25 23:14:32 +0000375 // Report error if there are non-trapping sanitizers that require
376 // c++abi-specific parts of UBSan runtime, and they are not provided by the
377 // toolchain. We don't have a good way to check the latter, so we just
378 // check if the toolchan supports vptr.
379 if (~Supported & Vptr) {
Peter Collingbourne4bdceaa2015-07-08 21:08:05 +0000380 SanitizerMask KindsToDiagnose = Kinds & ~TrappingKinds & NeedsUbsanCxxRt;
381 // The runtime library supports the Microsoft C++ ABI, but only well enough
382 // for CFI. FIXME: Remove this once we support vptr on Windows.
383 if (TC.getTriple().isOSWindows())
384 KindsToDiagnose &= ~CFI;
385 if (KindsToDiagnose) {
Alexey Samsonov9b873092015-06-25 23:14:32 +0000386 SanitizerSet S;
387 S.Mask = KindsToDiagnose;
388 D.Diag(diag::err_drv_unsupported_opt_for_target)
389 << ("-fno-sanitize-trap=" + toString(S)) << TC.getTriple().str();
390 Kinds &= ~KindsToDiagnose;
391 }
392 }
393
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000394 // Warn about incompatible groups of sanitizers.
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000395 for (auto G : IncompatibleGroups) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000396 SanitizerMask Group = G.first;
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000397 if (Kinds & Group) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000398 if (SanitizerMask Incompatible = Kinds & G.second) {
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000399 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
400 << lastArgumentForMask(D, Args, Group)
401 << lastArgumentForMask(D, Args, Incompatible);
402 Kinds &= ~Incompatible;
403 }
404 }
405 }
406 // FIXME: Currently -fsanitize=leak is silently ignored in the presence of
407 // -fsanitize=address. Perhaps it should print an error, or perhaps
408 // -f(-no)sanitize=leak should change whether leak detection is enabled by
409 // default in ASan?
410
Alexey Samsonov88459522015-01-12 22:39:12 +0000411 // Parse -f(no-)?sanitize-recover flags.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000412 SanitizerMask RecoverableKinds = RecoverableByDefault;
413 SanitizerMask DiagnosedUnrecoverableKinds = 0;
Alexey Samsonov88459522015-01-12 22:39:12 +0000414 for (const auto *Arg : Args) {
Alexey Samsonovce2e77c2015-03-11 23:34:25 +0000415 const char *DeprecatedReplacement = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +0000416 if (Arg->getOption().matches(options::OPT_fsanitize_recover)) {
Kostya Serebryanyceb1add2016-05-04 20:21:47 +0000417 DeprecatedReplacement =
418 "-fsanitize-recover=undefined,integer' or '-fsanitize-recover=all";
Peter Collingbournebf59c342015-05-11 21:39:20 +0000419 RecoverableKinds |= expandSanitizerGroups(LegacyFsanitizeRecoverMask);
Alexey Samsonov88459522015-01-12 22:39:12 +0000420 Arg->claim();
421 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover)) {
Kostya Serebryanyceb1add2016-05-04 20:21:47 +0000422 DeprecatedReplacement = "-fno-sanitize-recover=undefined,integer' or "
423 "'-fno-sanitize-recover=all";
Peter Collingbournebf59c342015-05-11 21:39:20 +0000424 RecoverableKinds &= ~expandSanitizerGroups(LegacyFsanitizeRecoverMask);
Alexey Samsonov88459522015-01-12 22:39:12 +0000425 Arg->claim();
426 } else if (Arg->getOption().matches(options::OPT_fsanitize_recover_EQ)) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000427 SanitizerMask Add = parseArgValues(D, Arg, true);
Alexey Samsonov88459522015-01-12 22:39:12 +0000428 // Report error if user explicitly tries to recover from unrecoverable
429 // sanitizer.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000430 if (SanitizerMask KindsToDiagnose =
Alexey Samsonov88459522015-01-12 22:39:12 +0000431 Add & Unrecoverable & ~DiagnosedUnrecoverableKinds) {
432 SanitizerSet SetToDiagnose;
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000433 SetToDiagnose.Mask |= KindsToDiagnose;
Alexey Samsonov88459522015-01-12 22:39:12 +0000434 D.Diag(diag::err_drv_unsupported_option_argument)
435 << Arg->getOption().getName() << toString(SetToDiagnose);
436 DiagnosedUnrecoverableKinds |= KindsToDiagnose;
437 }
Peter Collingbournebf59c342015-05-11 21:39:20 +0000438 RecoverableKinds |= expandSanitizerGroups(Add);
Alexey Samsonov88459522015-01-12 22:39:12 +0000439 Arg->claim();
440 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000441 RecoverableKinds &= ~expandSanitizerGroups(parseArgValues(D, Arg, true));
Alexey Samsonov88459522015-01-12 22:39:12 +0000442 Arg->claim();
443 }
Alexey Samsonovce2e77c2015-03-11 23:34:25 +0000444 if (DeprecatedReplacement) {
445 D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
446 << DeprecatedReplacement;
447 }
Alexey Samsonov88459522015-01-12 22:39:12 +0000448 }
449 RecoverableKinds &= Kinds;
450 RecoverableKinds &= ~Unrecoverable;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000451
Peter Collingbourne9881b782015-06-18 23:59:22 +0000452 TrappingKinds &= Kinds;
Vedant Kumarfae4f7c2017-12-21 00:10:24 +0000453 RecoverableKinds &= ~TrappingKinds;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000454
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000455 // Setup blacklist files.
456 // Add default blacklist from resource directory.
Richard Smith6cd48612018-02-20 23:17:41 +0000457 addDefaultBlacklists(D, Kinds, BlacklistFiles);
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000458 // Parse -f(no-)sanitize-blacklist options.
459 for (const auto *Arg : Args) {
460 if (Arg->getOption().matches(options::OPT_fsanitize_blacklist)) {
461 Arg->claim();
462 std::string BLPath = Arg->getValue();
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000463 if (llvm::sys::fs::exists(BLPath)) {
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000464 BlacklistFiles.push_back(BLPath);
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000465 ExtraDeps.push_back(BLPath);
Richard Smith6cd48612018-02-20 23:17:41 +0000466 } else {
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000467 D.Diag(clang::diag::err_drv_no_such_file) << BLPath;
Richard Smith6cd48612018-02-20 23:17:41 +0000468 }
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000469 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_blacklist)) {
470 Arg->claim();
471 BlacklistFiles.clear();
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000472 ExtraDeps.clear();
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000473 }
474 }
475 // Validate blacklists format.
476 {
477 std::string BLError;
478 std::unique_ptr<llvm::SpecialCaseList> SCL(
479 llvm::SpecialCaseList::create(BlacklistFiles, BLError));
480 if (!SCL.get())
481 D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000482 }
483
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000484 // Parse -f[no-]sanitize-memory-track-origins[=level] options.
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000485 if (AllAddedKinds & Memory) {
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000486 if (Arg *A =
487 Args.getLastArg(options::OPT_fsanitize_memory_track_origins_EQ,
488 options::OPT_fsanitize_memory_track_origins,
489 options::OPT_fno_sanitize_memory_track_origins)) {
490 if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) {
Evgeniy Stepanov6e09bca2015-02-26 15:59:30 +0000491 MsanTrackOrigins = 2;
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000492 } else if (A->getOption().matches(
493 options::OPT_fno_sanitize_memory_track_origins)) {
494 MsanTrackOrigins = 0;
495 } else {
496 StringRef S = A->getValue();
497 if (S.getAsInteger(0, MsanTrackOrigins) || MsanTrackOrigins < 0 ||
498 MsanTrackOrigins > 2) {
Nico Weberf2a39a72015-04-13 20:03:03 +0000499 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000500 }
501 }
502 }
Evgeniy Stepanov71554fe2015-10-21 21:28:49 +0000503 MsanUseAfterDtor =
Matt Morehousebb26f862017-09-14 23:14:37 +0000504 Args.hasFlag(options::OPT_fsanitize_memory_use_after_dtor,
505 options::OPT_fno_sanitize_memory_use_after_dtor,
Matt Morehouse175625c2017-09-14 23:53:56 +0000506 MsanUseAfterDtor);
Evgeniy Stepanov71554fe2015-10-21 21:28:49 +0000507 NeedPIE |= !(TC.getTriple().isOSLinux() &&
508 TC.getTriple().getArch() == llvm::Triple::x86_64);
Matt Morehouse175625c2017-09-14 23:53:56 +0000509 } else {
510 MsanUseAfterDtor = false;
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000511 }
512
Evgeniy Stepanov8a2bedb2016-11-11 23:17:36 +0000513 if (AllAddedKinds & Thread) {
514 TsanMemoryAccess = Args.hasFlag(options::OPT_fsanitize_thread_memory_access,
515 options::OPT_fno_sanitize_thread_memory_access,
516 TsanMemoryAccess);
517 TsanFuncEntryExit = Args.hasFlag(options::OPT_fsanitize_thread_func_entry_exit,
518 options::OPT_fno_sanitize_thread_func_entry_exit,
519 TsanFuncEntryExit);
520 TsanAtomics = Args.hasFlag(options::OPT_fsanitize_thread_atomics,
521 options::OPT_fno_sanitize_thread_atomics,
522 TsanAtomics);
523 }
524
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000525 if (AllAddedKinds & CFI) {
526 CfiCrossDso = Args.hasFlag(options::OPT_fsanitize_cfi_cross_dso,
527 options::OPT_fno_sanitize_cfi_cross_dso, false);
528 // Without PIE, external function address may resolve to a PLT record, which
529 // can not be verified by the target module.
530 NeedPIE |= CfiCrossDso;
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +0000531 CfiICallGeneralizePointers =
532 Args.hasArg(options::OPT_fsanitize_cfi_icall_generalize_pointers);
533
534 if (CfiCrossDso && CfiICallGeneralizePointers)
535 D.Diag(diag::err_drv_argument_not_allowed_with)
536 << "-fsanitize-cfi-cross-dso"
537 << "-fsanitize-cfi-icall-generalize-pointers";
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000538 }
539
Peter Collingbournedc134532016-01-16 00:31:22 +0000540 Stats = Args.hasFlag(options::OPT_fsanitize_stats,
541 options::OPT_fno_sanitize_stats, false);
542
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +0000543 if (MinimalRuntime) {
544 SanitizerMask IncompatibleMask =
545 Kinds & ~setGroupBits(CompatibleWithMinimalRuntime);
546 if (IncompatibleMask)
547 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
548 << "-fsanitize-minimal-runtime"
549 << lastArgumentForMask(D, Args, IncompatibleMask);
550
551 SanitizerMask NonTrappingCfi = Kinds & CFI & ~TrappingKinds;
552 if (NonTrappingCfi)
553 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
554 << "fsanitize-minimal-runtime"
555 << "fsanitize-trap=cfi";
556 }
557
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000558 // Parse -f(no-)?sanitize-coverage flags if coverage is supported by the
559 // enabled sanitizers.
Kostya Serebryany52e86492016-02-18 00:49:23 +0000560 for (const auto *Arg : Args) {
561 if (Arg->getOption().matches(options::OPT_fsanitize_coverage)) {
562 int LegacySanitizeCoverage;
563 if (Arg->getNumValues() == 1 &&
564 !StringRef(Arg->getValue(0))
Kostya Serebryany9d1ed132017-04-19 19:57:16 +0000565 .getAsInteger(0, LegacySanitizeCoverage)) {
566 CoverageFeatures = 0;
567 Arg->claim();
568 if (LegacySanitizeCoverage != 0) {
Nico Weber4152f522016-02-18 19:32:54 +0000569 D.Diag(diag::warn_drv_deprecated_arg)
Kostya Serebryany9d1ed132017-04-19 19:57:16 +0000570 << Arg->getAsString(Args) << "-fsanitize-coverage=trace-pc-guard";
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000571 }
Kostya Serebryany52e86492016-02-18 00:49:23 +0000572 continue;
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000573 }
Kostya Serebryany52e86492016-02-18 00:49:23 +0000574 CoverageFeatures |= parseCoverageFeatures(D, Arg);
Evgeniy Stepanov5b49eb42016-06-14 21:33:40 +0000575
576 // Disable coverage and not claim the flags if there is at least one
577 // non-supporting sanitizer.
Petr Hosekeb4127f2017-07-21 01:17:49 +0000578 if (!(AllAddedKinds & ~AllRemove & ~setGroupBits(SupportsCoverage))) {
Kostya Serebryany52e86492016-02-18 00:49:23 +0000579 Arg->claim();
Kostya Serebryanyf5b25f82016-04-18 21:30:17 +0000580 } else {
581 CoverageFeatures = 0;
Kostya Serebryany52e86492016-02-18 00:49:23 +0000582 }
583 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_coverage)) {
584 Arg->claim();
585 CoverageFeatures &= ~parseCoverageFeatures(D, Arg);
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000586 }
587 }
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000588 // Choose at most one coverage type: function, bb, or edge.
589 if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageBB))
590 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
591 << "-fsanitize-coverage=func"
592 << "-fsanitize-coverage=bb";
593 if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageEdge))
594 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
595 << "-fsanitize-coverage=func"
596 << "-fsanitize-coverage=edge";
597 if ((CoverageFeatures & CoverageBB) && (CoverageFeatures & CoverageEdge))
598 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
599 << "-fsanitize-coverage=bb"
600 << "-fsanitize-coverage=edge";
601 // Basic block tracing and 8-bit counters require some type of coverage
602 // enabled.
Kostya Serebryany1c0e9e92017-04-19 21:31:11 +0000603 if (CoverageFeatures & CoverageTraceBB)
604 D.Diag(clang::diag::warn_drv_deprecated_arg)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000605 << "-fsanitize-coverage=trace-bb"
Kostya Serebryany1c0e9e92017-04-19 21:31:11 +0000606 << "-fsanitize-coverage=trace-pc-guard";
607 if (CoverageFeatures & Coverage8bitCounters)
Kostya Serebryany1a02d8b2017-04-19 20:15:58 +0000608 D.Diag(clang::diag::warn_drv_deprecated_arg)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000609 << "-fsanitize-coverage=8bit-counters"
Kostya Serebryany1a02d8b2017-04-19 20:15:58 +0000610 << "-fsanitize-coverage=trace-pc-guard";
Kostya Serebryany8955efc2017-05-03 01:27:28 +0000611
612 int InsertionPointTypes = CoverageFunc | CoverageBB | CoverageEdge;
Kostya Serebryany9f338dc2017-08-08 20:20:40 +0000613 int InstrumentationTypes =
614 CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters;
Kostya Serebryany8955efc2017-05-03 01:27:28 +0000615 if ((CoverageFeatures & InsertionPointTypes) &&
Kostya Serebryany9f338dc2017-08-08 20:20:40 +0000616 !(CoverageFeatures & InstrumentationTypes)) {
Kostya Serebryany8955efc2017-05-03 01:27:28 +0000617 D.Diag(clang::diag::warn_drv_deprecated_arg)
618 << "-fsanitize-coverage=[func|bb|edge]"
619 << "-fsanitize-coverage=[func|bb|edge],[trace-pc-guard|trace-pc]";
620 }
621
Kostya Serebryany52e86492016-02-18 00:49:23 +0000622 // trace-pc w/o func/bb/edge implies edge.
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000623 if (!(CoverageFeatures & InsertionPointTypes)) {
624 if (CoverageFeatures &
625 (CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters))
626 CoverageFeatures |= CoverageEdge;
627
628 if (CoverageFeatures & CoverageStackDepth)
629 CoverageFeatures |= CoverageFunc;
630 }
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000631
Evgeniy Stepanov0876cfb2017-10-05 20:14:00 +0000632 SharedRuntime =
633 Args.hasFlag(options::OPT_shared_libsan, options::OPT_static_libsan,
Vedant Kumar358d6422017-10-07 01:42:09 +0000634 TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia() ||
635 TC.getTriple().isOSDarwin());
Evgeniy Stepanov0876cfb2017-10-05 20:14:00 +0000636
Evgeniy Stepanovd5d36a12017-10-16 18:02:57 +0000637 ImplicitCfiRuntime = TC.getTriple().isAndroid();
638
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000639 if (AllAddedKinds & Address) {
Evgeniy Stepanov117627c2017-10-25 20:39:22 +0000640 NeedPIE |= TC.getTriple().isOSFuchsia();
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000641 if (Arg *A =
642 Args.getLastArg(options::OPT_fsanitize_address_field_padding)) {
643 StringRef S = A->getValue();
644 // Legal values are 0 and 1, 2, but in future we may add more levels.
645 if (S.getAsInteger(0, AsanFieldPadding) || AsanFieldPadding < 0 ||
646 AsanFieldPadding > 2) {
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000647 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000648 }
649 }
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000650
651 if (Arg *WindowsDebugRTArg =
652 Args.getLastArg(options::OPT__SLASH_MTd, options::OPT__SLASH_MT,
653 options::OPT__SLASH_MDd, options::OPT__SLASH_MD,
654 options::OPT__SLASH_LDd, options::OPT__SLASH_LD)) {
655 switch (WindowsDebugRTArg->getOption().getID()) {
656 case options::OPT__SLASH_MTd:
657 case options::OPT__SLASH_MDd:
658 case options::OPT__SLASH_LDd:
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000659 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000660 << WindowsDebugRTArg->getAsString(Args)
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000661 << lastArgumentForMask(D, Args, Address);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000662 D.Diag(clang::diag::note_drv_address_sanitizer_debug_runtime);
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000663 }
664 }
Alexey Samsonov90490af2014-08-08 22:47:17 +0000665
Vedant Kumara9d8be62017-05-08 21:11:55 +0000666 AsanUseAfterScope = Args.hasFlag(
667 options::OPT_fsanitize_address_use_after_scope,
668 options::OPT_fno_sanitize_address_use_after_scope, AsanUseAfterScope);
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000669
670 // As a workaround for a bug in gold 2.26 and earlier, dead stripping of
671 // globals in ASan is disabled by default on ELF targets.
672 // See https://sourceware.org/bugzilla/show_bug.cgi?id=19002
673 AsanGlobalsDeadStripping =
Petr Hosekb31582b2017-08-03 23:02:22 +0000674 !TC.getTriple().isOSBinFormatELF() || TC.getTriple().isOSFuchsia() ||
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000675 Args.hasArg(options::OPT_fsanitize_address_globals_dead_stripping);
Vedant Kumara9d8be62017-05-08 21:11:55 +0000676 } else {
677 AsanUseAfterScope = false;
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000678 }
679
Petr Hosek766288b2017-08-16 19:06:05 +0000680 if (AllAddedKinds & SafeStack) {
681 // SafeStack runtime is built into the system on Fuchsia.
682 SafeStackRuntime = !TC.getTriple().isOSFuchsia();
683 }
684
Alexey Samsonov90490af2014-08-08 22:47:17 +0000685 // Parse -link-cxx-sanitizer flag.
686 LinkCXXRuntimes =
687 Args.hasArg(options::OPT_fsanitize_link_cxx_runtime) || D.CCCIsCXX();
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000688
689 // Finally, initialize the set of available and recoverable sanitizers.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000690 Sanitizers.Mask |= Kinds;
691 RecoverableSanitizers.Mask |= RecoverableKinds;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000692 TrapSanitizers.Mask |= TrappingKinds;
Vedant Kumarfae4f7c2017-12-21 00:10:24 +0000693 assert(!(RecoverableKinds & TrappingKinds) &&
694 "Overlap between recoverable and trapping sanitizers");
Alexey Samsonovcf055962013-08-08 10:11:02 +0000695}
696
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000697static std::string toString(const clang::SanitizerSet &Sanitizers) {
698 std::string Res;
699#define SANITIZER(NAME, ID) \
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000700 if (Sanitizers.has(ID)) { \
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000701 if (!Res.empty()) \
702 Res += ","; \
703 Res += NAME; \
704 }
705#include "clang/Basic/Sanitizers.def"
706 return Res;
707}
708
Peter Collingbournedc134532016-01-16 00:31:22 +0000709static void addIncludeLinkerOption(const ToolChain &TC,
710 const llvm::opt::ArgList &Args,
711 llvm::opt::ArgStringList &CmdArgs,
712 StringRef SymbolName) {
713 SmallString<64> LinkerOptionFlag;
714 LinkerOptionFlag = "--linker-option=/include:";
715 if (TC.getTriple().getArch() == llvm::Triple::x86) {
716 // Win32 mangles C function names with a '_' prefix.
717 LinkerOptionFlag += '_';
718 }
719 LinkerOptionFlag += SymbolName;
720 CmdArgs.push_back(Args.MakeArgString(LinkerOptionFlag));
721}
722
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000723void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args,
Peter Collingbourne581f4382015-07-02 01:48:12 +0000724 llvm::opt::ArgStringList &CmdArgs,
725 types::ID InputType) const {
Justin Lebar6efbc732016-09-15 23:44:13 +0000726 // NVPTX doesn't currently support sanitizers. Bailing out here means that
727 // e.g. -fsanitize=address applies only to host code, which is what we want
728 // for now.
729 if (TC.getTriple().isNVPTX())
730 return;
731
Kostya Serebryany52e86492016-02-18 00:49:23 +0000732 // Translate available CoverageFeatures to corresponding clang-cc1 flags.
733 // Do it even if Sanitizers.empty() since some forms of coverage don't require
734 // sanitizers.
735 std::pair<int, const char *> CoverageFlags[] = {
736 std::make_pair(CoverageFunc, "-fsanitize-coverage-type=1"),
737 std::make_pair(CoverageBB, "-fsanitize-coverage-type=2"),
738 std::make_pair(CoverageEdge, "-fsanitize-coverage-type=3"),
739 std::make_pair(CoverageIndirCall, "-fsanitize-coverage-indirect-calls"),
740 std::make_pair(CoverageTraceBB, "-fsanitize-coverage-trace-bb"),
741 std::make_pair(CoverageTraceCmp, "-fsanitize-coverage-trace-cmp"),
Kostya Serebryany3b419712016-08-30 01:27:03 +0000742 std::make_pair(CoverageTraceDiv, "-fsanitize-coverage-trace-div"),
743 std::make_pair(CoverageTraceGep, "-fsanitize-coverage-trace-gep"),
Kostya Serebryany52e86492016-02-18 00:49:23 +0000744 std::make_pair(Coverage8bitCounters, "-fsanitize-coverage-8bit-counters"),
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000745 std::make_pair(CoverageTracePC, "-fsanitize-coverage-trace-pc"),
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000746 std::make_pair(CoverageTracePCGuard, "-fsanitize-coverage-trace-pc-guard"),
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000747 std::make_pair(CoverageInline8bitCounters, "-fsanitize-coverage-inline-8bit-counters"),
Kostya Serebryany61457762017-07-28 00:10:10 +0000748 std::make_pair(CoveragePCTable, "-fsanitize-coverage-pc-table"),
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000749 std::make_pair(CoverageNoPrune, "-fsanitize-coverage-no-prune"),
750 std::make_pair(CoverageStackDepth, "-fsanitize-coverage-stack-depth")};
Kostya Serebryany52e86492016-02-18 00:49:23 +0000751 for (auto F : CoverageFlags) {
752 if (CoverageFeatures & F.first)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000753 CmdArgs.push_back(F.second);
Kostya Serebryany52e86492016-02-18 00:49:23 +0000754 }
755
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000756 if (TC.getTriple().isOSWindows() && needsUbsanRt()) {
757 // Instruct the code generator to embed linker directives in the object file
758 // that cause the required runtime libraries to be linked.
759 CmdArgs.push_back(Args.MakeArgString(
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000760 "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000761 if (types::isCXX(InputType))
762 CmdArgs.push_back(Args.MakeArgString(
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000763 "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone_cxx")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000764 }
765 if (TC.getTriple().isOSWindows() && needsStatsRt()) {
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000766 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
767 TC.getCompilerRT(Args, "stats_client")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000768
769 // The main executable must export the stats runtime.
770 // FIXME: Only exporting from the main executable (e.g. based on whether the
771 // translation unit defines main()) would save a little space, but having
772 // multiple copies of the runtime shouldn't hurt.
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000773 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
774 TC.getCompilerRT(Args, "stats")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000775 addIncludeLinkerOption(TC, Args, CmdArgs, "__sanitizer_stats_register");
776 }
777
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000778 if (Sanitizers.empty())
Alexey Samsonovcf055962013-08-08 10:11:02 +0000779 return;
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000780 CmdArgs.push_back(Args.MakeArgString("-fsanitize=" + toString(Sanitizers)));
781
Alexey Samsonov88459522015-01-12 22:39:12 +0000782 if (!RecoverableSanitizers.empty())
783 CmdArgs.push_back(Args.MakeArgString("-fsanitize-recover=" +
784 toString(RecoverableSanitizers)));
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000785
Peter Collingbourne9881b782015-06-18 23:59:22 +0000786 if (!TrapSanitizers.empty())
787 CmdArgs.push_back(
788 Args.MakeArgString("-fsanitize-trap=" + toString(TrapSanitizers)));
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000789
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000790 for (const auto &BLPath : BlacklistFiles) {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000791 SmallString<64> BlacklistOpt("-fsanitize-blacklist=");
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000792 BlacklistOpt += BLPath;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000793 CmdArgs.push_back(Args.MakeArgString(BlacklistOpt));
794 }
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000795 for (const auto &Dep : ExtraDeps) {
796 SmallString<64> ExtraDepOpt("-fdepfile-entry=");
797 ExtraDepOpt += Dep;
798 CmdArgs.push_back(Args.MakeArgString(ExtraDepOpt));
799 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000800
801 if (MsanTrackOrigins)
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000802 CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins=" +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +0000803 Twine(MsanTrackOrigins)));
Evgeniy Stepanov45be9e02015-07-10 20:07:16 +0000804
805 if (MsanUseAfterDtor)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000806 CmdArgs.push_back("-fsanitize-memory-use-after-dtor");
Evgeniy Stepanov45be9e02015-07-10 20:07:16 +0000807
Evgeniy Stepanov8a2bedb2016-11-11 23:17:36 +0000808 // FIXME: Pass these parameters as function attributes, not as -llvm flags.
809 if (!TsanMemoryAccess) {
810 CmdArgs.push_back("-mllvm");
811 CmdArgs.push_back("-tsan-instrument-memory-accesses=0");
812 CmdArgs.push_back("-mllvm");
813 CmdArgs.push_back("-tsan-instrument-memintrinsics=0");
814 }
815 if (!TsanFuncEntryExit) {
816 CmdArgs.push_back("-mllvm");
817 CmdArgs.push_back("-tsan-instrument-func-entry-exit=0");
818 }
819 if (!TsanAtomics) {
820 CmdArgs.push_back("-mllvm");
821 CmdArgs.push_back("-tsan-instrument-atomics=0");
822 }
823
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000824 if (CfiCrossDso)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000825 CmdArgs.push_back("-fsanitize-cfi-cross-dso");
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000826
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +0000827 if (CfiICallGeneralizePointers)
828 CmdArgs.push_back("-fsanitize-cfi-icall-generalize-pointers");
829
Peter Collingbournedc134532016-01-16 00:31:22 +0000830 if (Stats)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000831 CmdArgs.push_back("-fsanitize-stats");
Peter Collingbournedc134532016-01-16 00:31:22 +0000832
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +0000833 if (MinimalRuntime)
834 CmdArgs.push_back("-fsanitize-minimal-runtime");
835
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000836 if (AsanFieldPadding)
837 CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-field-padding=" +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +0000838 Twine(AsanFieldPadding)));
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000839
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000840 if (AsanUseAfterScope)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000841 CmdArgs.push_back("-fsanitize-address-use-after-scope");
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000842
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000843 if (AsanGlobalsDeadStripping)
844 CmdArgs.push_back("-fsanitize-address-globals-dead-stripping");
845
Sergey Matveev2ba87782015-02-17 15:09:33 +0000846 // MSan: Workaround for PR16386.
847 // ASan: This is mainly to help LSan with cases such as
Hans Wennborg5fd1f172017-11-13 23:27:54 +0000848 // https://github.com/google/sanitizers/issues/373
Sergey Matveev2ba87782015-02-17 15:09:33 +0000849 // We can't make this conditional on -fsanitize=leak, as that flag shouldn't
850 // affect compilation.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000851 if (Sanitizers.has(Memory) || Sanitizers.has(Address))
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000852 CmdArgs.push_back("-fno-assume-sane-operator-new");
Peter Collingbourne581f4382015-07-02 01:48:12 +0000853
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000854 // Require -fvisibility= flag on non-Windows when compiling if vptr CFI is
855 // enabled.
856 if (Sanitizers.hasOneOf(CFIClasses) && !TC.getTriple().isOSWindows() &&
857 !Args.hasArg(options::OPT_fvisibility_EQ)) {
858 TC.getDriver().Diag(clang::diag::err_drv_argument_only_allowed_with)
859 << lastArgumentForMask(TC.getDriver(), Args,
860 Sanitizers.Mask & CFIClasses)
861 << "-fvisibility=";
862 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000863}
864
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000865SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
866 bool DiagnoseErrors) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000867 assert((A->getOption().matches(options::OPT_fsanitize_EQ) ||
Alexey Samsonov88459522015-01-12 22:39:12 +0000868 A->getOption().matches(options::OPT_fno_sanitize_EQ) ||
869 A->getOption().matches(options::OPT_fsanitize_recover_EQ) ||
Peter Collingbourne9881b782015-06-18 23:59:22 +0000870 A->getOption().matches(options::OPT_fno_sanitize_recover_EQ) ||
871 A->getOption().matches(options::OPT_fsanitize_trap_EQ) ||
872 A->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) &&
Alexey Samsonov799f7932014-12-19 02:35:16 +0000873 "Invalid argument in parseArgValues!");
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000874 SanitizerMask Kinds = 0;
Alexey Samsonov83791e22015-03-03 22:15:32 +0000875 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
876 const char *Value = A->getValue(i);
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000877 SanitizerMask Kind;
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000878 // Special case: don't accept -fsanitize=all.
879 if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
880 0 == strcmp("all", Value))
881 Kind = 0;
Derek Bruening256c2e12016-04-21 21:32:04 +0000882 // Similarly, don't accept -fsanitize=efficiency-all.
883 else if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
884 0 == strcmp("efficiency-all", Value))
885 Kind = 0;
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000886 else
Peter Collingbournebf59c342015-05-11 21:39:20 +0000887 Kind = parseSanitizerValue(Value, /*AllowGroups=*/true);
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000888
889 if (Kind)
890 Kinds |= Kind;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000891 else if (DiagnoseErrors)
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000892 D.Diag(clang::diag::err_drv_unsupported_option_argument)
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000893 << A->getOption().getName() << Value;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000894 }
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000895 return Kinds;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000896}
897
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000898int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A) {
899 assert(A->getOption().matches(options::OPT_fsanitize_coverage) ||
900 A->getOption().matches(options::OPT_fno_sanitize_coverage));
901 int Features = 0;
902 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
903 const char *Value = A->getValue(i);
904 int F = llvm::StringSwitch<int>(Value)
905 .Case("func", CoverageFunc)
906 .Case("bb", CoverageBB)
907 .Case("edge", CoverageEdge)
908 .Case("indirect-calls", CoverageIndirCall)
909 .Case("trace-bb", CoverageTraceBB)
910 .Case("trace-cmp", CoverageTraceCmp)
Kostya Serebryany3b419712016-08-30 01:27:03 +0000911 .Case("trace-div", CoverageTraceDiv)
912 .Case("trace-gep", CoverageTraceGep)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000913 .Case("8bit-counters", Coverage8bitCounters)
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000914 .Case("trace-pc", CoverageTracePC)
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000915 .Case("trace-pc-guard", CoverageTracePCGuard)
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000916 .Case("no-prune", CoverageNoPrune)
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000917 .Case("inline-8bit-counters", CoverageInline8bitCounters)
Kostya Serebryany61457762017-07-28 00:10:10 +0000918 .Case("pc-table", CoveragePCTable)
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000919 .Case("stack-depth", CoverageStackDepth)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000920 .Default(0);
921 if (F == 0)
922 D.Diag(clang::diag::err_drv_unsupported_option_argument)
923 << A->getOption().getName() << Value;
924 Features |= F;
925 }
926 return Features;
927}
928
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000929std::string lastArgumentForMask(const Driver &D, const llvm::opt::ArgList &Args,
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000930 SanitizerMask Mask) {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000931 for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(),
932 E = Args.rend();
933 I != E; ++I) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000934 const auto *Arg = *I;
935 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000936 SanitizerMask AddKinds =
937 expandSanitizerGroups(parseArgValues(D, Arg, false));
Alexey Samsonov799f7932014-12-19 02:35:16 +0000938 if (AddKinds & Mask)
939 return describeSanitizeArg(Arg, Mask);
940 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000941 SanitizerMask RemoveKinds =
942 expandSanitizerGroups(parseArgValues(D, Arg, false));
Alexey Samsonov799f7932014-12-19 02:35:16 +0000943 Mask &= ~RemoveKinds;
944 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000945 }
946 llvm_unreachable("arg list didn't provide expected value");
947}
948
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000949std::string describeSanitizeArg(const llvm::opt::Arg *A, SanitizerMask Mask) {
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000950 assert(A->getOption().matches(options::OPT_fsanitize_EQ)
951 && "Invalid argument in describeSanitizerArg!");
Alexey Samsonovcf055962013-08-08 10:11:02 +0000952
Peter Collingbourne32701642013-11-01 18:16:25 +0000953 std::string Sanitizers;
Alexey Samsonov83791e22015-03-03 22:15:32 +0000954 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000955 if (expandSanitizerGroups(
956 parseSanitizerValue(A->getValue(i), /*AllowGroups=*/true)) &
957 Mask) {
Peter Collingbourne32701642013-11-01 18:16:25 +0000958 if (!Sanitizers.empty())
959 Sanitizers += ",";
Alexey Samsonov83791e22015-03-03 22:15:32 +0000960 Sanitizers += A->getValue(i);
Peter Collingbourne32701642013-11-01 18:16:25 +0000961 }
962 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000963
Peter Collingbourne32701642013-11-01 18:16:25 +0000964 assert(!Sanitizers.empty() && "arg didn't provide expected value");
965 return "-fsanitize=" + Sanitizers;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000966}