blob: d6a9c35eda7853212481eb42dab2ff28561629c8 [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 Stepanov71554fe2015-10-21 21:28:49 +000032 RequiresPIE = DataFlow,
Kostya Serebryany2d88f3d2015-01-06 01:02:48 +000033 NeedsUnwindTables = Address | Thread | Memory | DataFlow,
Alexander Potapenkodc5b95b2017-06-08 16:24:21 +000034 SupportsCoverage = Address | KernelAddress | Memory | Leak | Undefined |
35 Integer | Nullability | DataFlow,
Vedant Kumar42c17ec2017-03-14 01:56:34 +000036 RecoverableByDefault = Undefined | Integer | Nullability,
Yury Gribov5bfeca12015-11-11 10:45:48 +000037 Unrecoverable = Unreachable | Return,
Peter Collingbournea4ccff32015-02-20 20:30:56 +000038 LegacyFsanitizeRecoverMask = Undefined | Integer,
Peter Collingbourne1a7488a2015-04-02 00:23:30 +000039 NeedsLTO = CFI,
Vedant Kumar42c17ec2017-03-14 01:56:34 +000040 TrappingSupported = (Undefined & ~Vptr) | UnsignedIntegerOverflow |
41 Nullability | LocalBounds | CFI,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +000042 TrappingDefault = CFI,
Peter Collingbourne3afb2662016-04-28 17:09:37 +000043 CFIClasses = CFIVCall | CFINVCall | CFIDerivedCast | CFIUnrelatedCast,
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000044};
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000045
46enum CoverageFeature {
47 CoverageFunc = 1 << 0,
48 CoverageBB = 1 << 1,
49 CoverageEdge = 1 << 2,
50 CoverageIndirCall = 1 << 3,
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000051 CoverageTraceBB = 1 << 4, // Deprecated.
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000052 CoverageTraceCmp = 1 << 5,
Kostya Serebryany3b419712016-08-30 01:27:03 +000053 CoverageTraceDiv = 1 << 6,
54 CoverageTraceGep = 1 << 7,
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000055 Coverage8bitCounters = 1 << 8, // Deprecated.
Kostya Serebryany3b419712016-08-30 01:27:03 +000056 CoverageTracePC = 1 << 9,
Kostya Serebryany60cdd612016-09-14 01:39:49 +000057 CoverageTracePCGuard = 1 << 10,
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000058 CoverageInline8bitCounters = 1 << 12,
Kostya Serebryany50fb6182017-05-05 23:28:18 +000059 CoverageNoPrune = 1 << 11,
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000060};
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000061
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000062/// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
Peter Collingbourne3eea6772015-05-11 21:39:14 +000063/// invalid components. Returns a SanitizerMask.
64static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
65 bool DiagnoseErrors);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000066
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000067/// Parse -f(no-)?sanitize-coverage= flag values, diagnosing any invalid
68/// components. Returns OR of members of \c CoverageFeature enumeration.
69static int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A);
70
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000071/// Produce an argument string from ArgList \p Args, which shows how it
72/// provides some sanitizer kind from \p Mask. For example, the argument list
73/// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt
74/// would produce "-fsanitize=vptr".
75static std::string lastArgumentForMask(const Driver &D,
76 const llvm::opt::ArgList &Args,
Peter Collingbourne3eea6772015-05-11 21:39:14 +000077 SanitizerMask Mask);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000078
79/// Produce an argument string from argument \p A, which shows how it provides
80/// a value in \p Mask. For instance, the argument
81/// "-fsanitize=address,alignment" with mask \c NeedsUbsanRt would produce
82/// "-fsanitize=alignment".
Peter Collingbourne3eea6772015-05-11 21:39:14 +000083static std::string describeSanitizeArg(const llvm::opt::Arg *A,
84 SanitizerMask Mask);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000085
Alexey Samsonov1e715a62014-11-16 20:53:53 +000086/// Produce a string containing comma-separated names of sanitizers in \p
87/// Sanitizers set.
88static std::string toString(const clang::SanitizerSet &Sanitizers);
89
Peter Collingbourne3eea6772015-05-11 21:39:14 +000090static bool getDefaultBlacklist(const Driver &D, SanitizerMask Kinds,
Alexey Samsonovecf380e2015-03-20 18:45:06 +000091 std::string &BLPath) {
92 const char *BlacklistFile = nullptr;
Peter Collingbourne3eea6772015-05-11 21:39:14 +000093 if (Kinds & Address)
Alexey Samsonovecf380e2015-03-20 18:45:06 +000094 BlacklistFile = "asan_blacklist.txt";
Peter Collingbourne3eea6772015-05-11 21:39:14 +000095 else if (Kinds & Memory)
Alexey Samsonovecf380e2015-03-20 18:45:06 +000096 BlacklistFile = "msan_blacklist.txt";
Peter Collingbourne3eea6772015-05-11 21:39:14 +000097 else if (Kinds & Thread)
Alexey Samsonovecf380e2015-03-20 18:45:06 +000098 BlacklistFile = "tsan_blacklist.txt";
Peter Collingbourne3eea6772015-05-11 21:39:14 +000099 else if (Kinds & DataFlow)
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000100 BlacklistFile = "dfsan_abilist.txt";
Peter Collingbourne6fccf952015-07-15 12:15:56 +0000101 else if (Kinds & CFI)
102 BlacklistFile = "cfi_blacklist.txt";
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000103
104 if (BlacklistFile) {
105 clang::SmallString<64> Path(D.ResourceDir);
106 llvm::sys::path::append(Path, BlacklistFile);
107 BLPath = Path.str();
108 return true;
109 }
110 return false;
111}
112
Peter Collingbourne9881b782015-06-18 23:59:22 +0000113/// Sets group bits for every group that has at least one representative already
114/// enabled in \p Kinds.
115static SanitizerMask setGroupBits(SanitizerMask Kinds) {
116#define SANITIZER(NAME, ID)
117#define SANITIZER_GROUP(NAME, ID, ALIAS) \
118 if (Kinds & SanitizerKind::ID) \
119 Kinds |= SanitizerKind::ID##Group;
120#include "clang/Basic/Sanitizers.def"
121 return Kinds;
122}
123
124static SanitizerMask parseSanitizeTrapArgs(const Driver &D,
125 const llvm::opt::ArgList &Args) {
126 SanitizerMask TrapRemove = 0; // During the loop below, the accumulated set of
127 // sanitizers disabled by the current sanitizer
128 // argument or any argument after it.
129 SanitizerMask TrappingKinds = 0;
130 SanitizerMask TrappingSupportedWithGroups = setGroupBits(TrappingSupported);
131
132 for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
133 I != E; ++I) {
134 const auto *Arg = *I;
135 if (Arg->getOption().matches(options::OPT_fsanitize_trap_EQ)) {
136 Arg->claim();
137 SanitizerMask Add = parseArgValues(D, Arg, true);
138 Add &= ~TrapRemove;
139 if (SanitizerMask InvalidValues = Add & ~TrappingSupportedWithGroups) {
140 SanitizerSet S;
141 S.Mask = InvalidValues;
142 D.Diag(diag::err_drv_unsupported_option_argument) << "-fsanitize-trap"
143 << toString(S);
144 }
145 TrappingKinds |= expandSanitizerGroups(Add) & ~TrapRemove;
146 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) {
147 Arg->claim();
148 TrapRemove |= expandSanitizerGroups(parseArgValues(D, Arg, true));
149 } else if (Arg->getOption().matches(
150 options::OPT_fsanitize_undefined_trap_on_error)) {
151 Arg->claim();
152 TrappingKinds |=
153 expandSanitizerGroups(UndefinedGroup & ~TrapRemove) & ~TrapRemove;
154 } else if (Arg->getOption().matches(
155 options::OPT_fno_sanitize_undefined_trap_on_error)) {
156 Arg->claim();
157 TrapRemove |= expandSanitizerGroups(UndefinedGroup);
158 }
159 }
160
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000161 // Apply default trapping behavior.
162 TrappingKinds |= TrappingDefault & ~TrapRemove;
163
Peter Collingbourne9881b782015-06-18 23:59:22 +0000164 return TrappingKinds;
165}
166
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000167bool SanitizerArgs::needsUbsanRt() const {
Evgeniy Stepanov5b49eb42016-06-14 21:33:40 +0000168 return ((Sanitizers.Mask & NeedsUbsanRt & ~TrapSanitizers.Mask) ||
169 CoverageFeatures) &&
170 !Sanitizers.has(Address) && !Sanitizers.has(Memory) &&
Mike Aizatskyd1033f52016-12-08 22:25:01 +0000171 !Sanitizers.has(Thread) && !Sanitizers.has(DataFlow) &&
172 !Sanitizers.has(Leak) && !CfiCrossDso;
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000173}
174
175bool SanitizerArgs::needsCfiRt() const {
Evgeniy Stepanove3fb51c2015-12-16 00:38:42 +0000176 return !(Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso;
177}
178
179bool SanitizerArgs::needsCfiDiagRt() const {
180 return (Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso;
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000181}
182
Dmitry Vyukov43419a72014-11-21 12:19:01 +0000183bool SanitizerArgs::requiresPIE() const {
Evgeniy Stepanov71554fe2015-10-21 21:28:49 +0000184 return NeedPIE || (Sanitizers.Mask & RequiresPIE);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000185}
186
187bool SanitizerArgs::needsUnwindTables() const {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000188 return Sanitizers.Mask & NeedsUnwindTables;
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000189}
190
Peter Collingbourne32701642013-11-01 18:16:25 +0000191SanitizerArgs::SanitizerArgs(const ToolChain &TC,
192 const llvm::opt::ArgList &Args) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000193 SanitizerMask AllRemove = 0; // During the loop below, the accumulated set of
194 // sanitizers disabled by the current sanitizer
195 // argument or any argument after it.
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000196 SanitizerMask AllAddedKinds = 0; // Mask of all sanitizers ever enabled by
197 // -fsanitize= flags (directly or via group
198 // expansion), some of which may be disabled
199 // later. Used to carefully prune
200 // unused-argument diagnostics.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000201 SanitizerMask DiagnosedKinds = 0; // All Kinds we have diagnosed up to now.
202 // Used to deduplicate diagnostics.
203 SanitizerMask Kinds = 0;
Alexey Samsonov9b873092015-06-25 23:14:32 +0000204 const SanitizerMask Supported = setGroupBits(TC.getSupportedSanitizers());
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000205 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
206
Peter Collingbourne32701642013-11-01 18:16:25 +0000207 const Driver &D = TC.getDriver();
Peter Collingbourne9881b782015-06-18 23:59:22 +0000208 SanitizerMask TrappingKinds = parseSanitizeTrapArgs(D, Args);
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000209 SanitizerMask InvalidTrappingKinds = TrappingKinds & NotAllowedWithTrap;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000210
Peter Collingbourne32701642013-11-01 18:16:25 +0000211 for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
212 I != E; ++I) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000213 const auto *Arg = *I;
214 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
215 Arg->claim();
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000216 SanitizerMask Add = parseArgValues(D, Arg, true);
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000217 AllAddedKinds |= expandSanitizerGroups(Add);
Peter Collingbourne32701642013-11-01 18:16:25 +0000218
Alexey Samsonov799f7932014-12-19 02:35:16 +0000219 // Avoid diagnosing any sanitizer which is disabled later.
220 Add &= ~AllRemove;
221 // At this point we have not expanded groups, so any unsupported
222 // sanitizers in Add are those which have been explicitly enabled.
223 // Diagnose them.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000224 if (SanitizerMask KindsToDiagnose =
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000225 Add & InvalidTrappingKinds & ~DiagnosedKinds) {
Peter Collingbourne9881b782015-06-18 23:59:22 +0000226 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
227 D.Diag(diag::err_drv_argument_not_allowed_with)
228 << Desc << "-fsanitize-trap=undefined";
229 DiagnosedKinds |= KindsToDiagnose;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000230 }
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000231 Add &= ~InvalidTrappingKinds;
232 if (SanitizerMask KindsToDiagnose = Add & ~Supported & ~DiagnosedKinds) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000233 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
234 D.Diag(diag::err_drv_unsupported_opt_for_target)
235 << Desc << TC.getTriple().str();
236 DiagnosedKinds |= KindsToDiagnose;
237 }
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000238 Add &= Supported;
Peter Collingbourne32701642013-11-01 18:16:25 +0000239
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000240 // Test for -fno-rtti + explicit -fsanitizer=vptr before expanding groups
241 // so we don't error out if -fno-rtti and -fsanitize=undefined were
242 // passed.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000243 if (Add & Vptr &&
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000244 (RTTIMode == ToolChain::RM_DisabledImplicitly ||
245 RTTIMode == ToolChain::RM_DisabledExplicitly)) {
246 if (RTTIMode == ToolChain::RM_DisabledImplicitly)
247 // Warn about not having rtti enabled if the vptr sanitizer is
248 // explicitly enabled
249 D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default);
250 else {
251 const llvm::opt::Arg *NoRTTIArg = TC.getRTTIArg();
252 assert(NoRTTIArg &&
253 "RTTI disabled explicitly but we have no argument!");
254 D.Diag(diag::err_drv_argument_not_allowed_with)
255 << "-fsanitize=vptr" << NoRTTIArg->getAsString(Args);
256 }
257
258 // Take out the Vptr sanitizer from the enabled sanitizers
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000259 AllRemove |= Vptr;
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000260 }
261
Peter Collingbournebf59c342015-05-11 21:39:20 +0000262 Add = expandSanitizerGroups(Add);
Alexey Samsonov799f7932014-12-19 02:35:16 +0000263 // Group expansion may have enabled a sanitizer which is disabled later.
264 Add &= ~AllRemove;
265 // Silently discard any unsupported sanitizers implicitly enabled through
266 // group expansion.
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000267 Add &= ~InvalidTrappingKinds;
268 Add &= Supported;
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000269
George Karpenkovf2fc5b02017-04-24 18:23:24 +0000270 // Enable coverage if the fuzzing flag is set.
271 if (Add & Fuzzer)
272 CoverageFeatures |= CoverageTracePCGuard | CoverageIndirCall | CoverageTraceCmp;
273
Alexey Samsonov799f7932014-12-19 02:35:16 +0000274 Kinds |= Add;
275 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
276 Arg->claim();
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000277 SanitizerMask Remove = parseArgValues(D, Arg, true);
Peter Collingbournebf59c342015-05-11 21:39:20 +0000278 AllRemove |= expandSanitizerGroups(Remove);
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000279 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000280 }
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000281
Ed Schoutenfc79d2c2016-03-29 21:13:53 +0000282 // Enable toolchain specific default sanitizers if not explicitly disabled.
283 Kinds |= TC.getDefaultSanitizers() & ~AllRemove;
284
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000285 // We disable the vptr sanitizer if it was enabled by group expansion but RTTI
286 // is disabled.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000287 if ((Kinds & Vptr) &&
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000288 (RTTIMode == ToolChain::RM_DisabledImplicitly ||
289 RTTIMode == ToolChain::RM_DisabledExplicitly)) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000290 Kinds &= ~Vptr;
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000291 }
292
Alexey Samsonov907880e2015-06-19 19:57:46 +0000293 // Check that LTO is enabled if we need it.
Teresa Johnson945bc502015-10-15 20:35:53 +0000294 if ((Kinds & NeedsLTO) && !D.isUsingLTO()) {
Alexey Samsonov907880e2015-06-19 19:57:46 +0000295 D.Diag(diag::err_drv_argument_only_allowed_with)
296 << lastArgumentForMask(D, Args, Kinds & NeedsLTO) << "-flto";
297 }
298
Alexey Samsonov9b873092015-06-25 23:14:32 +0000299 // Report error if there are non-trapping sanitizers that require
300 // c++abi-specific parts of UBSan runtime, and they are not provided by the
301 // toolchain. We don't have a good way to check the latter, so we just
302 // check if the toolchan supports vptr.
303 if (~Supported & Vptr) {
Peter Collingbourne4bdceaa2015-07-08 21:08:05 +0000304 SanitizerMask KindsToDiagnose = Kinds & ~TrappingKinds & NeedsUbsanCxxRt;
305 // The runtime library supports the Microsoft C++ ABI, but only well enough
306 // for CFI. FIXME: Remove this once we support vptr on Windows.
307 if (TC.getTriple().isOSWindows())
308 KindsToDiagnose &= ~CFI;
309 if (KindsToDiagnose) {
Alexey Samsonov9b873092015-06-25 23:14:32 +0000310 SanitizerSet S;
311 S.Mask = KindsToDiagnose;
312 D.Diag(diag::err_drv_unsupported_opt_for_target)
313 << ("-fno-sanitize-trap=" + toString(S)) << TC.getTriple().str();
314 Kinds &= ~KindsToDiagnose;
315 }
316 }
317
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000318 // Warn about incompatible groups of sanitizers.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000319 std::pair<SanitizerMask, SanitizerMask> IncompatibleGroups[] = {
320 std::make_pair(Address, Thread), std::make_pair(Address, Memory),
321 std::make_pair(Thread, Memory), std::make_pair(Leak, Thread),
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000322 std::make_pair(Leak, Memory), std::make_pair(KernelAddress, Address),
323 std::make_pair(KernelAddress, Leak),
324 std::make_pair(KernelAddress, Thread),
Derek Bruening256c2e12016-04-21 21:32:04 +0000325 std::make_pair(KernelAddress, Memory),
326 std::make_pair(Efficiency, Address),
327 std::make_pair(Efficiency, Leak),
328 std::make_pair(Efficiency, Thread),
329 std::make_pair(Efficiency, Memory),
330 std::make_pair(Efficiency, KernelAddress)};
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000331 for (auto G : IncompatibleGroups) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000332 SanitizerMask Group = G.first;
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000333 if (Kinds & Group) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000334 if (SanitizerMask Incompatible = Kinds & G.second) {
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000335 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
336 << lastArgumentForMask(D, Args, Group)
337 << lastArgumentForMask(D, Args, Incompatible);
338 Kinds &= ~Incompatible;
339 }
340 }
341 }
342 // FIXME: Currently -fsanitize=leak is silently ignored in the presence of
343 // -fsanitize=address. Perhaps it should print an error, or perhaps
344 // -f(-no)sanitize=leak should change whether leak detection is enabled by
345 // default in ASan?
346
Alexey Samsonov88459522015-01-12 22:39:12 +0000347 // Parse -f(no-)?sanitize-recover flags.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000348 SanitizerMask RecoverableKinds = RecoverableByDefault;
349 SanitizerMask DiagnosedUnrecoverableKinds = 0;
Alexey Samsonov88459522015-01-12 22:39:12 +0000350 for (const auto *Arg : Args) {
Alexey Samsonovce2e77c2015-03-11 23:34:25 +0000351 const char *DeprecatedReplacement = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +0000352 if (Arg->getOption().matches(options::OPT_fsanitize_recover)) {
Kostya Serebryanyceb1add2016-05-04 20:21:47 +0000353 DeprecatedReplacement =
354 "-fsanitize-recover=undefined,integer' or '-fsanitize-recover=all";
Peter Collingbournebf59c342015-05-11 21:39:20 +0000355 RecoverableKinds |= expandSanitizerGroups(LegacyFsanitizeRecoverMask);
Alexey Samsonov88459522015-01-12 22:39:12 +0000356 Arg->claim();
357 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover)) {
Kostya Serebryanyceb1add2016-05-04 20:21:47 +0000358 DeprecatedReplacement = "-fno-sanitize-recover=undefined,integer' or "
359 "'-fno-sanitize-recover=all";
Peter Collingbournebf59c342015-05-11 21:39:20 +0000360 RecoverableKinds &= ~expandSanitizerGroups(LegacyFsanitizeRecoverMask);
Alexey Samsonov88459522015-01-12 22:39:12 +0000361 Arg->claim();
362 } else if (Arg->getOption().matches(options::OPT_fsanitize_recover_EQ)) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000363 SanitizerMask Add = parseArgValues(D, Arg, true);
Alexey Samsonov88459522015-01-12 22:39:12 +0000364 // Report error if user explicitly tries to recover from unrecoverable
365 // sanitizer.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000366 if (SanitizerMask KindsToDiagnose =
Alexey Samsonov88459522015-01-12 22:39:12 +0000367 Add & Unrecoverable & ~DiagnosedUnrecoverableKinds) {
368 SanitizerSet SetToDiagnose;
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000369 SetToDiagnose.Mask |= KindsToDiagnose;
Alexey Samsonov88459522015-01-12 22:39:12 +0000370 D.Diag(diag::err_drv_unsupported_option_argument)
371 << Arg->getOption().getName() << toString(SetToDiagnose);
372 DiagnosedUnrecoverableKinds |= KindsToDiagnose;
373 }
Peter Collingbournebf59c342015-05-11 21:39:20 +0000374 RecoverableKinds |= expandSanitizerGroups(Add);
Alexey Samsonov88459522015-01-12 22:39:12 +0000375 Arg->claim();
376 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000377 RecoverableKinds &= ~expandSanitizerGroups(parseArgValues(D, Arg, true));
Alexey Samsonov88459522015-01-12 22:39:12 +0000378 Arg->claim();
379 }
Alexey Samsonovce2e77c2015-03-11 23:34:25 +0000380 if (DeprecatedReplacement) {
381 D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
382 << DeprecatedReplacement;
383 }
Alexey Samsonov88459522015-01-12 22:39:12 +0000384 }
385 RecoverableKinds &= Kinds;
386 RecoverableKinds &= ~Unrecoverable;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000387
Peter Collingbourne9881b782015-06-18 23:59:22 +0000388 TrappingKinds &= Kinds;
389
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000390 // Setup blacklist files.
391 // Add default blacklist from resource directory.
392 {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000393 std::string BLPath;
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000394 if (getDefaultBlacklist(D, Kinds, BLPath) && llvm::sys::fs::exists(BLPath))
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000395 BlacklistFiles.push_back(BLPath);
396 }
397 // Parse -f(no-)sanitize-blacklist options.
398 for (const auto *Arg : Args) {
399 if (Arg->getOption().matches(options::OPT_fsanitize_blacklist)) {
400 Arg->claim();
401 std::string BLPath = Arg->getValue();
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000402 if (llvm::sys::fs::exists(BLPath)) {
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000403 BlacklistFiles.push_back(BLPath);
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000404 ExtraDeps.push_back(BLPath);
405 } else
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000406 D.Diag(clang::diag::err_drv_no_such_file) << BLPath;
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000407
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000408 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_blacklist)) {
409 Arg->claim();
410 BlacklistFiles.clear();
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000411 ExtraDeps.clear();
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000412 }
413 }
414 // Validate blacklists format.
415 {
416 std::string BLError;
417 std::unique_ptr<llvm::SpecialCaseList> SCL(
418 llvm::SpecialCaseList::create(BlacklistFiles, BLError));
419 if (!SCL.get())
420 D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000421 }
422
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000423 // Parse -f[no-]sanitize-memory-track-origins[=level] options.
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000424 if (AllAddedKinds & Memory) {
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000425 if (Arg *A =
426 Args.getLastArg(options::OPT_fsanitize_memory_track_origins_EQ,
427 options::OPT_fsanitize_memory_track_origins,
428 options::OPT_fno_sanitize_memory_track_origins)) {
429 if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) {
Evgeniy Stepanov6e09bca2015-02-26 15:59:30 +0000430 MsanTrackOrigins = 2;
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000431 } else if (A->getOption().matches(
432 options::OPT_fno_sanitize_memory_track_origins)) {
433 MsanTrackOrigins = 0;
434 } else {
435 StringRef S = A->getValue();
436 if (S.getAsInteger(0, MsanTrackOrigins) || MsanTrackOrigins < 0 ||
437 MsanTrackOrigins > 2) {
Nico Weberf2a39a72015-04-13 20:03:03 +0000438 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000439 }
440 }
441 }
Evgeniy Stepanov71554fe2015-10-21 21:28:49 +0000442 MsanUseAfterDtor =
443 Args.hasArg(options::OPT_fsanitize_memory_use_after_dtor);
444 NeedPIE |= !(TC.getTriple().isOSLinux() &&
445 TC.getTriple().getArch() == llvm::Triple::x86_64);
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000446 }
447
Evgeniy Stepanov8a2bedb2016-11-11 23:17:36 +0000448 if (AllAddedKinds & Thread) {
449 TsanMemoryAccess = Args.hasFlag(options::OPT_fsanitize_thread_memory_access,
450 options::OPT_fno_sanitize_thread_memory_access,
451 TsanMemoryAccess);
452 TsanFuncEntryExit = Args.hasFlag(options::OPT_fsanitize_thread_func_entry_exit,
453 options::OPT_fno_sanitize_thread_func_entry_exit,
454 TsanFuncEntryExit);
455 TsanAtomics = Args.hasFlag(options::OPT_fsanitize_thread_atomics,
456 options::OPT_fno_sanitize_thread_atomics,
457 TsanAtomics);
458 }
459
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000460 if (AllAddedKinds & CFI) {
461 CfiCrossDso = Args.hasFlag(options::OPT_fsanitize_cfi_cross_dso,
462 options::OPT_fno_sanitize_cfi_cross_dso, false);
463 // Without PIE, external function address may resolve to a PLT record, which
464 // can not be verified by the target module.
465 NeedPIE |= CfiCrossDso;
466 }
467
Peter Collingbournedc134532016-01-16 00:31:22 +0000468 Stats = Args.hasFlag(options::OPT_fsanitize_stats,
469 options::OPT_fno_sanitize_stats, false);
470
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000471 // Parse -f(no-)?sanitize-coverage flags if coverage is supported by the
472 // enabled sanitizers.
Kostya Serebryany52e86492016-02-18 00:49:23 +0000473 for (const auto *Arg : Args) {
474 if (Arg->getOption().matches(options::OPT_fsanitize_coverage)) {
475 int LegacySanitizeCoverage;
476 if (Arg->getNumValues() == 1 &&
477 !StringRef(Arg->getValue(0))
Kostya Serebryany9d1ed132017-04-19 19:57:16 +0000478 .getAsInteger(0, LegacySanitizeCoverage)) {
479 CoverageFeatures = 0;
480 Arg->claim();
481 if (LegacySanitizeCoverage != 0) {
Nico Weber4152f522016-02-18 19:32:54 +0000482 D.Diag(diag::warn_drv_deprecated_arg)
Kostya Serebryany9d1ed132017-04-19 19:57:16 +0000483 << Arg->getAsString(Args) << "-fsanitize-coverage=trace-pc-guard";
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000484 }
Kostya Serebryany52e86492016-02-18 00:49:23 +0000485 continue;
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000486 }
Kostya Serebryany52e86492016-02-18 00:49:23 +0000487 CoverageFeatures |= parseCoverageFeatures(D, Arg);
Evgeniy Stepanov5b49eb42016-06-14 21:33:40 +0000488
489 // Disable coverage and not claim the flags if there is at least one
490 // non-supporting sanitizer.
491 if (!(AllAddedKinds & ~setGroupBits(SupportsCoverage))) {
Kostya Serebryany52e86492016-02-18 00:49:23 +0000492 Arg->claim();
Kostya Serebryanyf5b25f82016-04-18 21:30:17 +0000493 } else {
494 CoverageFeatures = 0;
Kostya Serebryany52e86492016-02-18 00:49:23 +0000495 }
496 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_coverage)) {
497 Arg->claim();
498 CoverageFeatures &= ~parseCoverageFeatures(D, Arg);
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000499 }
500 }
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000501 // Choose at most one coverage type: function, bb, or edge.
502 if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageBB))
503 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
504 << "-fsanitize-coverage=func"
505 << "-fsanitize-coverage=bb";
506 if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageEdge))
507 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
508 << "-fsanitize-coverage=func"
509 << "-fsanitize-coverage=edge";
510 if ((CoverageFeatures & CoverageBB) && (CoverageFeatures & CoverageEdge))
511 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
512 << "-fsanitize-coverage=bb"
513 << "-fsanitize-coverage=edge";
514 // Basic block tracing and 8-bit counters require some type of coverage
515 // enabled.
Kostya Serebryany1c0e9e92017-04-19 21:31:11 +0000516 if (CoverageFeatures & CoverageTraceBB)
517 D.Diag(clang::diag::warn_drv_deprecated_arg)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000518 << "-fsanitize-coverage=trace-bb"
Kostya Serebryany1c0e9e92017-04-19 21:31:11 +0000519 << "-fsanitize-coverage=trace-pc-guard";
520 if (CoverageFeatures & Coverage8bitCounters)
Kostya Serebryany1a02d8b2017-04-19 20:15:58 +0000521 D.Diag(clang::diag::warn_drv_deprecated_arg)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000522 << "-fsanitize-coverage=8bit-counters"
Kostya Serebryany1a02d8b2017-04-19 20:15:58 +0000523 << "-fsanitize-coverage=trace-pc-guard";
Kostya Serebryany8955efc2017-05-03 01:27:28 +0000524
525 int InsertionPointTypes = CoverageFunc | CoverageBB | CoverageEdge;
526 if ((CoverageFeatures & InsertionPointTypes) &&
527 !(CoverageFeatures &(CoverageTracePC | CoverageTracePCGuard))) {
528 D.Diag(clang::diag::warn_drv_deprecated_arg)
529 << "-fsanitize-coverage=[func|bb|edge]"
530 << "-fsanitize-coverage=[func|bb|edge],[trace-pc-guard|trace-pc]";
531 }
532
Kostya Serebryany52e86492016-02-18 00:49:23 +0000533 // trace-pc w/o func/bb/edge implies edge.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000534 if ((CoverageFeatures &
535 (CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters)) &&
Kostya Serebryany8955efc2017-05-03 01:27:28 +0000536 !(CoverageFeatures & InsertionPointTypes))
Kostya Serebryany52e86492016-02-18 00:49:23 +0000537 CoverageFeatures |= CoverageEdge;
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000538
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000539 if (AllAddedKinds & Address) {
Alexey Samsonovbdfa6c22014-04-01 13:31:10 +0000540 AsanSharedRuntime =
Evgeniy Stepanov14deb7b2015-10-08 21:21:44 +0000541 Args.hasArg(options::OPT_shared_libasan) || TC.getTriple().isAndroid();
Evgeniy Stepanov71554fe2015-10-21 21:28:49 +0000542 NeedPIE |= TC.getTriple().isAndroid();
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000543 if (Arg *A =
544 Args.getLastArg(options::OPT_fsanitize_address_field_padding)) {
545 StringRef S = A->getValue();
546 // Legal values are 0 and 1, 2, but in future we may add more levels.
547 if (S.getAsInteger(0, AsanFieldPadding) || AsanFieldPadding < 0 ||
548 AsanFieldPadding > 2) {
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000549 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000550 }
551 }
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000552
553 if (Arg *WindowsDebugRTArg =
554 Args.getLastArg(options::OPT__SLASH_MTd, options::OPT__SLASH_MT,
555 options::OPT__SLASH_MDd, options::OPT__SLASH_MD,
556 options::OPT__SLASH_LDd, options::OPT__SLASH_LD)) {
557 switch (WindowsDebugRTArg->getOption().getID()) {
558 case options::OPT__SLASH_MTd:
559 case options::OPT__SLASH_MDd:
560 case options::OPT__SLASH_LDd:
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000561 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000562 << WindowsDebugRTArg->getAsString(Args)
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000563 << lastArgumentForMask(D, Args, Address);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000564 D.Diag(clang::diag::note_drv_address_sanitizer_debug_runtime);
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000565 }
566 }
Alexey Samsonov90490af2014-08-08 22:47:17 +0000567
Vedant Kumara9d8be62017-05-08 21:11:55 +0000568 AsanUseAfterScope = Args.hasFlag(
569 options::OPT_fsanitize_address_use_after_scope,
570 options::OPT_fno_sanitize_address_use_after_scope, AsanUseAfterScope);
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000571
572 // As a workaround for a bug in gold 2.26 and earlier, dead stripping of
573 // globals in ASan is disabled by default on ELF targets.
574 // See https://sourceware.org/bugzilla/show_bug.cgi?id=19002
575 AsanGlobalsDeadStripping =
576 !TC.getTriple().isOSBinFormatELF() ||
577 Args.hasArg(options::OPT_fsanitize_address_globals_dead_stripping);
Vedant Kumara9d8be62017-05-08 21:11:55 +0000578 } else {
579 AsanUseAfterScope = false;
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000580 }
581
Alexey Samsonov90490af2014-08-08 22:47:17 +0000582 // Parse -link-cxx-sanitizer flag.
583 LinkCXXRuntimes =
584 Args.hasArg(options::OPT_fsanitize_link_cxx_runtime) || D.CCCIsCXX();
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000585
586 // Finally, initialize the set of available and recoverable sanitizers.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000587 Sanitizers.Mask |= Kinds;
588 RecoverableSanitizers.Mask |= RecoverableKinds;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000589 TrapSanitizers.Mask |= TrappingKinds;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000590}
591
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000592static std::string toString(const clang::SanitizerSet &Sanitizers) {
593 std::string Res;
594#define SANITIZER(NAME, ID) \
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000595 if (Sanitizers.has(ID)) { \
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000596 if (!Res.empty()) \
597 Res += ","; \
598 Res += NAME; \
599 }
600#include "clang/Basic/Sanitizers.def"
601 return Res;
602}
603
Peter Collingbournedc134532016-01-16 00:31:22 +0000604static void addIncludeLinkerOption(const ToolChain &TC,
605 const llvm::opt::ArgList &Args,
606 llvm::opt::ArgStringList &CmdArgs,
607 StringRef SymbolName) {
608 SmallString<64> LinkerOptionFlag;
609 LinkerOptionFlag = "--linker-option=/include:";
610 if (TC.getTriple().getArch() == llvm::Triple::x86) {
611 // Win32 mangles C function names with a '_' prefix.
612 LinkerOptionFlag += '_';
613 }
614 LinkerOptionFlag += SymbolName;
615 CmdArgs.push_back(Args.MakeArgString(LinkerOptionFlag));
616}
617
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000618void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args,
Peter Collingbourne581f4382015-07-02 01:48:12 +0000619 llvm::opt::ArgStringList &CmdArgs,
620 types::ID InputType) const {
Justin Lebar6efbc732016-09-15 23:44:13 +0000621 // NVPTX doesn't currently support sanitizers. Bailing out here means that
622 // e.g. -fsanitize=address applies only to host code, which is what we want
623 // for now.
624 if (TC.getTriple().isNVPTX())
625 return;
626
Kostya Serebryany52e86492016-02-18 00:49:23 +0000627 // Translate available CoverageFeatures to corresponding clang-cc1 flags.
628 // Do it even if Sanitizers.empty() since some forms of coverage don't require
629 // sanitizers.
630 std::pair<int, const char *> CoverageFlags[] = {
631 std::make_pair(CoverageFunc, "-fsanitize-coverage-type=1"),
632 std::make_pair(CoverageBB, "-fsanitize-coverage-type=2"),
633 std::make_pair(CoverageEdge, "-fsanitize-coverage-type=3"),
634 std::make_pair(CoverageIndirCall, "-fsanitize-coverage-indirect-calls"),
635 std::make_pair(CoverageTraceBB, "-fsanitize-coverage-trace-bb"),
636 std::make_pair(CoverageTraceCmp, "-fsanitize-coverage-trace-cmp"),
Kostya Serebryany3b419712016-08-30 01:27:03 +0000637 std::make_pair(CoverageTraceDiv, "-fsanitize-coverage-trace-div"),
638 std::make_pair(CoverageTraceGep, "-fsanitize-coverage-trace-gep"),
Kostya Serebryany52e86492016-02-18 00:49:23 +0000639 std::make_pair(Coverage8bitCounters, "-fsanitize-coverage-8bit-counters"),
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000640 std::make_pair(CoverageTracePC, "-fsanitize-coverage-trace-pc"),
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000641 std::make_pair(CoverageTracePCGuard, "-fsanitize-coverage-trace-pc-guard"),
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000642 std::make_pair(CoverageInline8bitCounters, "-fsanitize-coverage-inline-8bit-counters"),
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000643 std::make_pair(CoverageNoPrune, "-fsanitize-coverage-no-prune")};
Kostya Serebryany52e86492016-02-18 00:49:23 +0000644 for (auto F : CoverageFlags) {
645 if (CoverageFeatures & F.first)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000646 CmdArgs.push_back(F.second);
Kostya Serebryany52e86492016-02-18 00:49:23 +0000647 }
648
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000649 if (TC.getTriple().isOSWindows() && needsUbsanRt()) {
650 // Instruct the code generator to embed linker directives in the object file
651 // that cause the required runtime libraries to be linked.
652 CmdArgs.push_back(Args.MakeArgString(
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000653 "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000654 if (types::isCXX(InputType))
655 CmdArgs.push_back(Args.MakeArgString(
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000656 "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone_cxx")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000657 }
658 if (TC.getTriple().isOSWindows() && needsStatsRt()) {
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000659 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
660 TC.getCompilerRT(Args, "stats_client")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000661
662 // The main executable must export the stats runtime.
663 // FIXME: Only exporting from the main executable (e.g. based on whether the
664 // translation unit defines main()) would save a little space, but having
665 // multiple copies of the runtime shouldn't hurt.
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000666 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
667 TC.getCompilerRT(Args, "stats")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000668 addIncludeLinkerOption(TC, Args, CmdArgs, "__sanitizer_stats_register");
669 }
670
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000671 if (Sanitizers.empty())
Alexey Samsonovcf055962013-08-08 10:11:02 +0000672 return;
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000673 CmdArgs.push_back(Args.MakeArgString("-fsanitize=" + toString(Sanitizers)));
674
Alexey Samsonov88459522015-01-12 22:39:12 +0000675 if (!RecoverableSanitizers.empty())
676 CmdArgs.push_back(Args.MakeArgString("-fsanitize-recover=" +
677 toString(RecoverableSanitizers)));
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000678
Peter Collingbourne9881b782015-06-18 23:59:22 +0000679 if (!TrapSanitizers.empty())
680 CmdArgs.push_back(
681 Args.MakeArgString("-fsanitize-trap=" + toString(TrapSanitizers)));
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000682
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000683 for (const auto &BLPath : BlacklistFiles) {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000684 SmallString<64> BlacklistOpt("-fsanitize-blacklist=");
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000685 BlacklistOpt += BLPath;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000686 CmdArgs.push_back(Args.MakeArgString(BlacklistOpt));
687 }
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000688 for (const auto &Dep : ExtraDeps) {
689 SmallString<64> ExtraDepOpt("-fdepfile-entry=");
690 ExtraDepOpt += Dep;
691 CmdArgs.push_back(Args.MakeArgString(ExtraDepOpt));
692 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000693
694 if (MsanTrackOrigins)
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000695 CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins=" +
696 llvm::utostr(MsanTrackOrigins)));
Evgeniy Stepanov45be9e02015-07-10 20:07:16 +0000697
698 if (MsanUseAfterDtor)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000699 CmdArgs.push_back("-fsanitize-memory-use-after-dtor");
Evgeniy Stepanov45be9e02015-07-10 20:07:16 +0000700
Evgeniy Stepanov8a2bedb2016-11-11 23:17:36 +0000701 // FIXME: Pass these parameters as function attributes, not as -llvm flags.
702 if (!TsanMemoryAccess) {
703 CmdArgs.push_back("-mllvm");
704 CmdArgs.push_back("-tsan-instrument-memory-accesses=0");
705 CmdArgs.push_back("-mllvm");
706 CmdArgs.push_back("-tsan-instrument-memintrinsics=0");
707 }
708 if (!TsanFuncEntryExit) {
709 CmdArgs.push_back("-mllvm");
710 CmdArgs.push_back("-tsan-instrument-func-entry-exit=0");
711 }
712 if (!TsanAtomics) {
713 CmdArgs.push_back("-mllvm");
714 CmdArgs.push_back("-tsan-instrument-atomics=0");
715 }
716
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000717 if (CfiCrossDso)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000718 CmdArgs.push_back("-fsanitize-cfi-cross-dso");
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000719
Peter Collingbournedc134532016-01-16 00:31:22 +0000720 if (Stats)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000721 CmdArgs.push_back("-fsanitize-stats");
Peter Collingbournedc134532016-01-16 00:31:22 +0000722
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000723 if (AsanFieldPadding)
724 CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-field-padding=" +
725 llvm::utostr(AsanFieldPadding)));
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000726
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000727 if (AsanUseAfterScope)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000728 CmdArgs.push_back("-fsanitize-address-use-after-scope");
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000729
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000730 if (AsanGlobalsDeadStripping)
731 CmdArgs.push_back("-fsanitize-address-globals-dead-stripping");
732
Sergey Matveev2ba87782015-02-17 15:09:33 +0000733 // MSan: Workaround for PR16386.
734 // ASan: This is mainly to help LSan with cases such as
735 // https://code.google.com/p/address-sanitizer/issues/detail?id=373
736 // We can't make this conditional on -fsanitize=leak, as that flag shouldn't
737 // affect compilation.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000738 if (Sanitizers.has(Memory) || Sanitizers.has(Address))
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000739 CmdArgs.push_back("-fno-assume-sane-operator-new");
Peter Collingbourne581f4382015-07-02 01:48:12 +0000740
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000741 // Require -fvisibility= flag on non-Windows when compiling if vptr CFI is
742 // enabled.
743 if (Sanitizers.hasOneOf(CFIClasses) && !TC.getTriple().isOSWindows() &&
744 !Args.hasArg(options::OPT_fvisibility_EQ)) {
745 TC.getDriver().Diag(clang::diag::err_drv_argument_only_allowed_with)
746 << lastArgumentForMask(TC.getDriver(), Args,
747 Sanitizers.Mask & CFIClasses)
748 << "-fvisibility=";
749 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000750}
751
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000752SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
753 bool DiagnoseErrors) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000754 assert((A->getOption().matches(options::OPT_fsanitize_EQ) ||
Alexey Samsonov88459522015-01-12 22:39:12 +0000755 A->getOption().matches(options::OPT_fno_sanitize_EQ) ||
756 A->getOption().matches(options::OPT_fsanitize_recover_EQ) ||
Peter Collingbourne9881b782015-06-18 23:59:22 +0000757 A->getOption().matches(options::OPT_fno_sanitize_recover_EQ) ||
758 A->getOption().matches(options::OPT_fsanitize_trap_EQ) ||
759 A->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) &&
Alexey Samsonov799f7932014-12-19 02:35:16 +0000760 "Invalid argument in parseArgValues!");
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000761 SanitizerMask Kinds = 0;
Alexey Samsonov83791e22015-03-03 22:15:32 +0000762 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
763 const char *Value = A->getValue(i);
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000764 SanitizerMask Kind;
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000765 // Special case: don't accept -fsanitize=all.
766 if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
767 0 == strcmp("all", Value))
768 Kind = 0;
Derek Bruening256c2e12016-04-21 21:32:04 +0000769 // Similarly, don't accept -fsanitize=efficiency-all.
770 else if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
771 0 == strcmp("efficiency-all", Value))
772 Kind = 0;
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000773 else
Peter Collingbournebf59c342015-05-11 21:39:20 +0000774 Kind = parseSanitizerValue(Value, /*AllowGroups=*/true);
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000775
776 if (Kind)
777 Kinds |= Kind;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000778 else if (DiagnoseErrors)
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000779 D.Diag(clang::diag::err_drv_unsupported_option_argument)
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000780 << A->getOption().getName() << Value;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000781 }
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000782 return Kinds;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000783}
784
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000785int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A) {
786 assert(A->getOption().matches(options::OPT_fsanitize_coverage) ||
787 A->getOption().matches(options::OPT_fno_sanitize_coverage));
788 int Features = 0;
789 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
790 const char *Value = A->getValue(i);
791 int F = llvm::StringSwitch<int>(Value)
792 .Case("func", CoverageFunc)
793 .Case("bb", CoverageBB)
794 .Case("edge", CoverageEdge)
795 .Case("indirect-calls", CoverageIndirCall)
796 .Case("trace-bb", CoverageTraceBB)
797 .Case("trace-cmp", CoverageTraceCmp)
Kostya Serebryany3b419712016-08-30 01:27:03 +0000798 .Case("trace-div", CoverageTraceDiv)
799 .Case("trace-gep", CoverageTraceGep)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000800 .Case("8bit-counters", Coverage8bitCounters)
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000801 .Case("trace-pc", CoverageTracePC)
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000802 .Case("trace-pc-guard", CoverageTracePCGuard)
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000803 .Case("no-prune", CoverageNoPrune)
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000804 .Case("inline-8bit-counters", CoverageInline8bitCounters)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000805 .Default(0);
806 if (F == 0)
807 D.Diag(clang::diag::err_drv_unsupported_option_argument)
808 << A->getOption().getName() << Value;
809 Features |= F;
810 }
811 return Features;
812}
813
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000814std::string lastArgumentForMask(const Driver &D, const llvm::opt::ArgList &Args,
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000815 SanitizerMask Mask) {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000816 for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(),
817 E = Args.rend();
818 I != E; ++I) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000819 const auto *Arg = *I;
820 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000821 SanitizerMask AddKinds =
822 expandSanitizerGroups(parseArgValues(D, Arg, false));
Alexey Samsonov799f7932014-12-19 02:35:16 +0000823 if (AddKinds & Mask)
824 return describeSanitizeArg(Arg, Mask);
825 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000826 SanitizerMask RemoveKinds =
827 expandSanitizerGroups(parseArgValues(D, Arg, false));
Alexey Samsonov799f7932014-12-19 02:35:16 +0000828 Mask &= ~RemoveKinds;
829 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000830 }
831 llvm_unreachable("arg list didn't provide expected value");
832}
833
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000834std::string describeSanitizeArg(const llvm::opt::Arg *A, SanitizerMask Mask) {
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000835 assert(A->getOption().matches(options::OPT_fsanitize_EQ)
836 && "Invalid argument in describeSanitizerArg!");
Alexey Samsonovcf055962013-08-08 10:11:02 +0000837
Peter Collingbourne32701642013-11-01 18:16:25 +0000838 std::string Sanitizers;
Alexey Samsonov83791e22015-03-03 22:15:32 +0000839 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000840 if (expandSanitizerGroups(
841 parseSanitizerValue(A->getValue(i), /*AllowGroups=*/true)) &
842 Mask) {
Peter Collingbourne32701642013-11-01 18:16:25 +0000843 if (!Sanitizers.empty())
844 Sanitizers += ",";
Alexey Samsonov83791e22015-03-03 22:15:32 +0000845 Sanitizers += A->getValue(i);
Peter Collingbourne32701642013-11-01 18:16:25 +0000846 }
847 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000848
Peter Collingbourne32701642013-11-01 18:16:25 +0000849 assert(!Sanitizers.empty() && "arg didn't provide expected value");
850 return "-fsanitize=" + Sanitizers;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000851}