blob: 8e61aadbf3263f13a24ab8e697f2d68521ee1c8b [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,
Vedant Kumar42c17ec2017-03-14 01:56:34 +000034 SupportsCoverage =
35 Address | Memory | Leak | Undefined | Integer | Nullability | DataFlow,
36 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,
51 CoverageTraceBB = 1 << 4,
52 CoverageTraceCmp = 1 << 5,
Kostya Serebryany3b419712016-08-30 01:27:03 +000053 CoverageTraceDiv = 1 << 6,
54 CoverageTraceGep = 1 << 7,
55 Coverage8bitCounters = 1 << 8,
56 CoverageTracePC = 1 << 9,
Kostya Serebryany60cdd612016-09-14 01:39:49 +000057 CoverageTracePCGuard = 1 << 10,
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000058};
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000059
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000060/// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
Peter Collingbourne3eea6772015-05-11 21:39:14 +000061/// invalid components. Returns a SanitizerMask.
62static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
63 bool DiagnoseErrors);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000064
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000065/// Parse -f(no-)?sanitize-coverage= flag values, diagnosing any invalid
66/// components. Returns OR of members of \c CoverageFeature enumeration.
67static int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A);
68
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000069/// Produce an argument string from ArgList \p Args, which shows how it
70/// provides some sanitizer kind from \p Mask. For example, the argument list
71/// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt
72/// would produce "-fsanitize=vptr".
73static std::string lastArgumentForMask(const Driver &D,
74 const llvm::opt::ArgList &Args,
Peter Collingbourne3eea6772015-05-11 21:39:14 +000075 SanitizerMask Mask);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000076
77/// Produce an argument string from argument \p A, which shows how it provides
78/// a value in \p Mask. For instance, the argument
79/// "-fsanitize=address,alignment" with mask \c NeedsUbsanRt would produce
80/// "-fsanitize=alignment".
Peter Collingbourne3eea6772015-05-11 21:39:14 +000081static std::string describeSanitizeArg(const llvm::opt::Arg *A,
82 SanitizerMask Mask);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000083
Alexey Samsonov1e715a62014-11-16 20:53:53 +000084/// Produce a string containing comma-separated names of sanitizers in \p
85/// Sanitizers set.
86static std::string toString(const clang::SanitizerSet &Sanitizers);
87
Peter Collingbourne3eea6772015-05-11 21:39:14 +000088static bool getDefaultBlacklist(const Driver &D, SanitizerMask Kinds,
Alexey Samsonovecf380e2015-03-20 18:45:06 +000089 std::string &BLPath) {
90 const char *BlacklistFile = nullptr;
Peter Collingbourne3eea6772015-05-11 21:39:14 +000091 if (Kinds & Address)
Alexey Samsonovecf380e2015-03-20 18:45:06 +000092 BlacklistFile = "asan_blacklist.txt";
Peter Collingbourne3eea6772015-05-11 21:39:14 +000093 else if (Kinds & Memory)
Alexey Samsonovecf380e2015-03-20 18:45:06 +000094 BlacklistFile = "msan_blacklist.txt";
Peter Collingbourne3eea6772015-05-11 21:39:14 +000095 else if (Kinds & Thread)
Alexey Samsonovecf380e2015-03-20 18:45:06 +000096 BlacklistFile = "tsan_blacklist.txt";
Peter Collingbourne3eea6772015-05-11 21:39:14 +000097 else if (Kinds & DataFlow)
Alexey Samsonovecf380e2015-03-20 18:45:06 +000098 BlacklistFile = "dfsan_abilist.txt";
Peter Collingbourne6fccf952015-07-15 12:15:56 +000099 else if (Kinds & CFI)
100 BlacklistFile = "cfi_blacklist.txt";
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000101
102 if (BlacklistFile) {
103 clang::SmallString<64> Path(D.ResourceDir);
104 llvm::sys::path::append(Path, BlacklistFile);
105 BLPath = Path.str();
106 return true;
107 }
108 return false;
109}
110
Peter Collingbourne9881b782015-06-18 23:59:22 +0000111/// Sets group bits for every group that has at least one representative already
112/// enabled in \p Kinds.
113static SanitizerMask setGroupBits(SanitizerMask Kinds) {
114#define SANITIZER(NAME, ID)
115#define SANITIZER_GROUP(NAME, ID, ALIAS) \
116 if (Kinds & SanitizerKind::ID) \
117 Kinds |= SanitizerKind::ID##Group;
118#include "clang/Basic/Sanitizers.def"
119 return Kinds;
120}
121
122static SanitizerMask parseSanitizeTrapArgs(const Driver &D,
123 const llvm::opt::ArgList &Args) {
124 SanitizerMask TrapRemove = 0; // During the loop below, the accumulated set of
125 // sanitizers disabled by the current sanitizer
126 // argument or any argument after it.
127 SanitizerMask TrappingKinds = 0;
128 SanitizerMask TrappingSupportedWithGroups = setGroupBits(TrappingSupported);
129
130 for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
131 I != E; ++I) {
132 const auto *Arg = *I;
133 if (Arg->getOption().matches(options::OPT_fsanitize_trap_EQ)) {
134 Arg->claim();
135 SanitizerMask Add = parseArgValues(D, Arg, true);
136 Add &= ~TrapRemove;
137 if (SanitizerMask InvalidValues = Add & ~TrappingSupportedWithGroups) {
138 SanitizerSet S;
139 S.Mask = InvalidValues;
140 D.Diag(diag::err_drv_unsupported_option_argument) << "-fsanitize-trap"
141 << toString(S);
142 }
143 TrappingKinds |= expandSanitizerGroups(Add) & ~TrapRemove;
144 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) {
145 Arg->claim();
146 TrapRemove |= expandSanitizerGroups(parseArgValues(D, Arg, true));
147 } else if (Arg->getOption().matches(
148 options::OPT_fsanitize_undefined_trap_on_error)) {
149 Arg->claim();
150 TrappingKinds |=
151 expandSanitizerGroups(UndefinedGroup & ~TrapRemove) & ~TrapRemove;
152 } else if (Arg->getOption().matches(
153 options::OPT_fno_sanitize_undefined_trap_on_error)) {
154 Arg->claim();
155 TrapRemove |= expandSanitizerGroups(UndefinedGroup);
156 }
157 }
158
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000159 // Apply default trapping behavior.
160 TrappingKinds |= TrappingDefault & ~TrapRemove;
161
Peter Collingbourne9881b782015-06-18 23:59:22 +0000162 return TrappingKinds;
163}
164
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000165bool SanitizerArgs::needsUbsanRt() const {
Evgeniy Stepanov5b49eb42016-06-14 21:33:40 +0000166 return ((Sanitizers.Mask & NeedsUbsanRt & ~TrapSanitizers.Mask) ||
167 CoverageFeatures) &&
168 !Sanitizers.has(Address) && !Sanitizers.has(Memory) &&
Mike Aizatskyd1033f52016-12-08 22:25:01 +0000169 !Sanitizers.has(Thread) && !Sanitizers.has(DataFlow) &&
170 !Sanitizers.has(Leak) && !CfiCrossDso;
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000171}
172
173bool SanitizerArgs::needsCfiRt() const {
Evgeniy Stepanove3fb51c2015-12-16 00:38:42 +0000174 return !(Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso;
175}
176
177bool SanitizerArgs::needsCfiDiagRt() const {
178 return (Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso;
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000179}
180
Dmitry Vyukov43419a72014-11-21 12:19:01 +0000181bool SanitizerArgs::requiresPIE() const {
Evgeniy Stepanov71554fe2015-10-21 21:28:49 +0000182 return NeedPIE || (Sanitizers.Mask & RequiresPIE);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000183}
184
185bool SanitizerArgs::needsUnwindTables() const {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000186 return Sanitizers.Mask & NeedsUnwindTables;
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000187}
188
Peter Collingbourne32701642013-11-01 18:16:25 +0000189SanitizerArgs::SanitizerArgs(const ToolChain &TC,
190 const llvm::opt::ArgList &Args) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000191 SanitizerMask AllRemove = 0; // During the loop below, the accumulated set of
192 // sanitizers disabled by the current sanitizer
193 // argument or any argument after it.
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000194 SanitizerMask AllAddedKinds = 0; // Mask of all sanitizers ever enabled by
195 // -fsanitize= flags (directly or via group
196 // expansion), some of which may be disabled
197 // later. Used to carefully prune
198 // unused-argument diagnostics.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000199 SanitizerMask DiagnosedKinds = 0; // All Kinds we have diagnosed up to now.
200 // Used to deduplicate diagnostics.
201 SanitizerMask Kinds = 0;
Alexey Samsonov9b873092015-06-25 23:14:32 +0000202 const SanitizerMask Supported = setGroupBits(TC.getSupportedSanitizers());
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000203 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
204
Peter Collingbourne32701642013-11-01 18:16:25 +0000205 const Driver &D = TC.getDriver();
Peter Collingbourne9881b782015-06-18 23:59:22 +0000206 SanitizerMask TrappingKinds = parseSanitizeTrapArgs(D, Args);
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000207 SanitizerMask InvalidTrappingKinds = TrappingKinds & NotAllowedWithTrap;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000208
Peter Collingbourne32701642013-11-01 18:16:25 +0000209 for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
210 I != E; ++I) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000211 const auto *Arg = *I;
212 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
213 Arg->claim();
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000214 SanitizerMask Add = parseArgValues(D, Arg, true);
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000215 AllAddedKinds |= expandSanitizerGroups(Add);
Peter Collingbourne32701642013-11-01 18:16:25 +0000216
Alexey Samsonov799f7932014-12-19 02:35:16 +0000217 // Avoid diagnosing any sanitizer which is disabled later.
218 Add &= ~AllRemove;
219 // At this point we have not expanded groups, so any unsupported
220 // sanitizers in Add are those which have been explicitly enabled.
221 // Diagnose them.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000222 if (SanitizerMask KindsToDiagnose =
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000223 Add & InvalidTrappingKinds & ~DiagnosedKinds) {
Peter Collingbourne9881b782015-06-18 23:59:22 +0000224 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
225 D.Diag(diag::err_drv_argument_not_allowed_with)
226 << Desc << "-fsanitize-trap=undefined";
227 DiagnosedKinds |= KindsToDiagnose;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000228 }
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000229 Add &= ~InvalidTrappingKinds;
230 if (SanitizerMask KindsToDiagnose = Add & ~Supported & ~DiagnosedKinds) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000231 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
232 D.Diag(diag::err_drv_unsupported_opt_for_target)
233 << Desc << TC.getTriple().str();
234 DiagnosedKinds |= KindsToDiagnose;
235 }
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000236 Add &= Supported;
Peter Collingbourne32701642013-11-01 18:16:25 +0000237
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000238 // Test for -fno-rtti + explicit -fsanitizer=vptr before expanding groups
239 // so we don't error out if -fno-rtti and -fsanitize=undefined were
240 // passed.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000241 if (Add & Vptr &&
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000242 (RTTIMode == ToolChain::RM_DisabledImplicitly ||
243 RTTIMode == ToolChain::RM_DisabledExplicitly)) {
244 if (RTTIMode == ToolChain::RM_DisabledImplicitly)
245 // Warn about not having rtti enabled if the vptr sanitizer is
246 // explicitly enabled
247 D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default);
248 else {
249 const llvm::opt::Arg *NoRTTIArg = TC.getRTTIArg();
250 assert(NoRTTIArg &&
251 "RTTI disabled explicitly but we have no argument!");
252 D.Diag(diag::err_drv_argument_not_allowed_with)
253 << "-fsanitize=vptr" << NoRTTIArg->getAsString(Args);
254 }
255
256 // Take out the Vptr sanitizer from the enabled sanitizers
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000257 AllRemove |= Vptr;
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000258 }
259
Peter Collingbournebf59c342015-05-11 21:39:20 +0000260 Add = expandSanitizerGroups(Add);
Alexey Samsonov799f7932014-12-19 02:35:16 +0000261 // Group expansion may have enabled a sanitizer which is disabled later.
262 Add &= ~AllRemove;
263 // Silently discard any unsupported sanitizers implicitly enabled through
264 // group expansion.
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000265 Add &= ~InvalidTrappingKinds;
266 Add &= Supported;
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000267
Alexey Samsonov799f7932014-12-19 02:35:16 +0000268 Kinds |= Add;
269 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
270 Arg->claim();
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000271 SanitizerMask Remove = parseArgValues(D, Arg, true);
Peter Collingbournebf59c342015-05-11 21:39:20 +0000272 AllRemove |= expandSanitizerGroups(Remove);
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000273 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000274 }
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000275
Ed Schoutenfc79d2c2016-03-29 21:13:53 +0000276 // Enable toolchain specific default sanitizers if not explicitly disabled.
277 Kinds |= TC.getDefaultSanitizers() & ~AllRemove;
278
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000279 // We disable the vptr sanitizer if it was enabled by group expansion but RTTI
280 // is disabled.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000281 if ((Kinds & Vptr) &&
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000282 (RTTIMode == ToolChain::RM_DisabledImplicitly ||
283 RTTIMode == ToolChain::RM_DisabledExplicitly)) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000284 Kinds &= ~Vptr;
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000285 }
286
Alexey Samsonov907880e2015-06-19 19:57:46 +0000287 // Check that LTO is enabled if we need it.
Teresa Johnson945bc502015-10-15 20:35:53 +0000288 if ((Kinds & NeedsLTO) && !D.isUsingLTO()) {
Alexey Samsonov907880e2015-06-19 19:57:46 +0000289 D.Diag(diag::err_drv_argument_only_allowed_with)
290 << lastArgumentForMask(D, Args, Kinds & NeedsLTO) << "-flto";
291 }
292
Alexey Samsonov9b873092015-06-25 23:14:32 +0000293 // Report error if there are non-trapping sanitizers that require
294 // c++abi-specific parts of UBSan runtime, and they are not provided by the
295 // toolchain. We don't have a good way to check the latter, so we just
296 // check if the toolchan supports vptr.
297 if (~Supported & Vptr) {
Peter Collingbourne4bdceaa2015-07-08 21:08:05 +0000298 SanitizerMask KindsToDiagnose = Kinds & ~TrappingKinds & NeedsUbsanCxxRt;
299 // The runtime library supports the Microsoft C++ ABI, but only well enough
300 // for CFI. FIXME: Remove this once we support vptr on Windows.
301 if (TC.getTriple().isOSWindows())
302 KindsToDiagnose &= ~CFI;
303 if (KindsToDiagnose) {
Alexey Samsonov9b873092015-06-25 23:14:32 +0000304 SanitizerSet S;
305 S.Mask = KindsToDiagnose;
306 D.Diag(diag::err_drv_unsupported_opt_for_target)
307 << ("-fno-sanitize-trap=" + toString(S)) << TC.getTriple().str();
308 Kinds &= ~KindsToDiagnose;
309 }
310 }
311
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000312 // Warn about incompatible groups of sanitizers.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000313 std::pair<SanitizerMask, SanitizerMask> IncompatibleGroups[] = {
314 std::make_pair(Address, Thread), std::make_pair(Address, Memory),
315 std::make_pair(Thread, Memory), std::make_pair(Leak, Thread),
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000316 std::make_pair(Leak, Memory), std::make_pair(KernelAddress, Address),
317 std::make_pair(KernelAddress, Leak),
318 std::make_pair(KernelAddress, Thread),
Derek Bruening256c2e12016-04-21 21:32:04 +0000319 std::make_pair(KernelAddress, Memory),
320 std::make_pair(Efficiency, Address),
321 std::make_pair(Efficiency, Leak),
322 std::make_pair(Efficiency, Thread),
323 std::make_pair(Efficiency, Memory),
324 std::make_pair(Efficiency, KernelAddress)};
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000325 for (auto G : IncompatibleGroups) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000326 SanitizerMask Group = G.first;
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000327 if (Kinds & Group) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000328 if (SanitizerMask Incompatible = Kinds & G.second) {
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000329 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
330 << lastArgumentForMask(D, Args, Group)
331 << lastArgumentForMask(D, Args, Incompatible);
332 Kinds &= ~Incompatible;
333 }
334 }
335 }
336 // FIXME: Currently -fsanitize=leak is silently ignored in the presence of
337 // -fsanitize=address. Perhaps it should print an error, or perhaps
338 // -f(-no)sanitize=leak should change whether leak detection is enabled by
339 // default in ASan?
340
Alexey Samsonov88459522015-01-12 22:39:12 +0000341 // Parse -f(no-)?sanitize-recover flags.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000342 SanitizerMask RecoverableKinds = RecoverableByDefault;
343 SanitizerMask DiagnosedUnrecoverableKinds = 0;
Alexey Samsonov88459522015-01-12 22:39:12 +0000344 for (const auto *Arg : Args) {
Alexey Samsonovce2e77c2015-03-11 23:34:25 +0000345 const char *DeprecatedReplacement = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +0000346 if (Arg->getOption().matches(options::OPT_fsanitize_recover)) {
Kostya Serebryanyceb1add2016-05-04 20:21:47 +0000347 DeprecatedReplacement =
348 "-fsanitize-recover=undefined,integer' or '-fsanitize-recover=all";
Peter Collingbournebf59c342015-05-11 21:39:20 +0000349 RecoverableKinds |= expandSanitizerGroups(LegacyFsanitizeRecoverMask);
Alexey Samsonov88459522015-01-12 22:39:12 +0000350 Arg->claim();
351 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover)) {
Kostya Serebryanyceb1add2016-05-04 20:21:47 +0000352 DeprecatedReplacement = "-fno-sanitize-recover=undefined,integer' or "
353 "'-fno-sanitize-recover=all";
Peter Collingbournebf59c342015-05-11 21:39:20 +0000354 RecoverableKinds &= ~expandSanitizerGroups(LegacyFsanitizeRecoverMask);
Alexey Samsonov88459522015-01-12 22:39:12 +0000355 Arg->claim();
356 } else if (Arg->getOption().matches(options::OPT_fsanitize_recover_EQ)) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000357 SanitizerMask Add = parseArgValues(D, Arg, true);
Alexey Samsonov88459522015-01-12 22:39:12 +0000358 // Report error if user explicitly tries to recover from unrecoverable
359 // sanitizer.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000360 if (SanitizerMask KindsToDiagnose =
Alexey Samsonov88459522015-01-12 22:39:12 +0000361 Add & Unrecoverable & ~DiagnosedUnrecoverableKinds) {
362 SanitizerSet SetToDiagnose;
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000363 SetToDiagnose.Mask |= KindsToDiagnose;
Alexey Samsonov88459522015-01-12 22:39:12 +0000364 D.Diag(diag::err_drv_unsupported_option_argument)
365 << Arg->getOption().getName() << toString(SetToDiagnose);
366 DiagnosedUnrecoverableKinds |= KindsToDiagnose;
367 }
Peter Collingbournebf59c342015-05-11 21:39:20 +0000368 RecoverableKinds |= expandSanitizerGroups(Add);
Alexey Samsonov88459522015-01-12 22:39:12 +0000369 Arg->claim();
370 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000371 RecoverableKinds &= ~expandSanitizerGroups(parseArgValues(D, Arg, true));
Alexey Samsonov88459522015-01-12 22:39:12 +0000372 Arg->claim();
373 }
Alexey Samsonovce2e77c2015-03-11 23:34:25 +0000374 if (DeprecatedReplacement) {
375 D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
376 << DeprecatedReplacement;
377 }
Alexey Samsonov88459522015-01-12 22:39:12 +0000378 }
379 RecoverableKinds &= Kinds;
380 RecoverableKinds &= ~Unrecoverable;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000381
Peter Collingbourne9881b782015-06-18 23:59:22 +0000382 TrappingKinds &= Kinds;
383
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000384 // Setup blacklist files.
385 // Add default blacklist from resource directory.
386 {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000387 std::string BLPath;
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000388 if (getDefaultBlacklist(D, Kinds, BLPath) && llvm::sys::fs::exists(BLPath))
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000389 BlacklistFiles.push_back(BLPath);
390 }
391 // Parse -f(no-)sanitize-blacklist options.
392 for (const auto *Arg : Args) {
393 if (Arg->getOption().matches(options::OPT_fsanitize_blacklist)) {
394 Arg->claim();
395 std::string BLPath = Arg->getValue();
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000396 if (llvm::sys::fs::exists(BLPath)) {
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000397 BlacklistFiles.push_back(BLPath);
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000398 ExtraDeps.push_back(BLPath);
399 } else
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000400 D.Diag(clang::diag::err_drv_no_such_file) << BLPath;
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000401
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000402 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_blacklist)) {
403 Arg->claim();
404 BlacklistFiles.clear();
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000405 ExtraDeps.clear();
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000406 }
407 }
408 // Validate blacklists format.
409 {
410 std::string BLError;
411 std::unique_ptr<llvm::SpecialCaseList> SCL(
412 llvm::SpecialCaseList::create(BlacklistFiles, BLError));
413 if (!SCL.get())
414 D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000415 }
416
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000417 // Parse -f[no-]sanitize-memory-track-origins[=level] options.
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000418 if (AllAddedKinds & Memory) {
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000419 if (Arg *A =
420 Args.getLastArg(options::OPT_fsanitize_memory_track_origins_EQ,
421 options::OPT_fsanitize_memory_track_origins,
422 options::OPT_fno_sanitize_memory_track_origins)) {
423 if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) {
Evgeniy Stepanov6e09bca2015-02-26 15:59:30 +0000424 MsanTrackOrigins = 2;
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000425 } else if (A->getOption().matches(
426 options::OPT_fno_sanitize_memory_track_origins)) {
427 MsanTrackOrigins = 0;
428 } else {
429 StringRef S = A->getValue();
430 if (S.getAsInteger(0, MsanTrackOrigins) || MsanTrackOrigins < 0 ||
431 MsanTrackOrigins > 2) {
Nico Weberf2a39a72015-04-13 20:03:03 +0000432 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000433 }
434 }
435 }
Evgeniy Stepanov71554fe2015-10-21 21:28:49 +0000436 MsanUseAfterDtor =
437 Args.hasArg(options::OPT_fsanitize_memory_use_after_dtor);
438 NeedPIE |= !(TC.getTriple().isOSLinux() &&
439 TC.getTriple().getArch() == llvm::Triple::x86_64);
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000440 }
441
Evgeniy Stepanov8a2bedb2016-11-11 23:17:36 +0000442 if (AllAddedKinds & Thread) {
443 TsanMemoryAccess = Args.hasFlag(options::OPT_fsanitize_thread_memory_access,
444 options::OPT_fno_sanitize_thread_memory_access,
445 TsanMemoryAccess);
446 TsanFuncEntryExit = Args.hasFlag(options::OPT_fsanitize_thread_func_entry_exit,
447 options::OPT_fno_sanitize_thread_func_entry_exit,
448 TsanFuncEntryExit);
449 TsanAtomics = Args.hasFlag(options::OPT_fsanitize_thread_atomics,
450 options::OPT_fno_sanitize_thread_atomics,
451 TsanAtomics);
452 }
453
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000454 if (AllAddedKinds & CFI) {
455 CfiCrossDso = Args.hasFlag(options::OPT_fsanitize_cfi_cross_dso,
456 options::OPT_fno_sanitize_cfi_cross_dso, false);
457 // Without PIE, external function address may resolve to a PLT record, which
458 // can not be verified by the target module.
459 NeedPIE |= CfiCrossDso;
460 }
461
Peter Collingbournedc134532016-01-16 00:31:22 +0000462 Stats = Args.hasFlag(options::OPT_fsanitize_stats,
463 options::OPT_fno_sanitize_stats, false);
464
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000465 // Parse -f(no-)?sanitize-coverage flags if coverage is supported by the
466 // enabled sanitizers.
Kostya Serebryany52e86492016-02-18 00:49:23 +0000467 for (const auto *Arg : Args) {
468 if (Arg->getOption().matches(options::OPT_fsanitize_coverage)) {
469 int LegacySanitizeCoverage;
470 if (Arg->getNumValues() == 1 &&
471 !StringRef(Arg->getValue(0))
Kostya Serebryany9d1ed132017-04-19 19:57:16 +0000472 .getAsInteger(0, LegacySanitizeCoverage)) {
473 CoverageFeatures = 0;
474 Arg->claim();
475 if (LegacySanitizeCoverage != 0) {
Nico Weber4152f522016-02-18 19:32:54 +0000476 D.Diag(diag::warn_drv_deprecated_arg)
Kostya Serebryany9d1ed132017-04-19 19:57:16 +0000477 << Arg->getAsString(Args) << "-fsanitize-coverage=trace-pc-guard";
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000478 }
Kostya Serebryany52e86492016-02-18 00:49:23 +0000479 continue;
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000480 }
Kostya Serebryany52e86492016-02-18 00:49:23 +0000481 CoverageFeatures |= parseCoverageFeatures(D, Arg);
Evgeniy Stepanov5b49eb42016-06-14 21:33:40 +0000482
483 // Disable coverage and not claim the flags if there is at least one
484 // non-supporting sanitizer.
485 if (!(AllAddedKinds & ~setGroupBits(SupportsCoverage))) {
Kostya Serebryany52e86492016-02-18 00:49:23 +0000486 Arg->claim();
Kostya Serebryanyf5b25f82016-04-18 21:30:17 +0000487 } else {
488 CoverageFeatures = 0;
Kostya Serebryany52e86492016-02-18 00:49:23 +0000489 }
490 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_coverage)) {
491 Arg->claim();
492 CoverageFeatures &= ~parseCoverageFeatures(D, Arg);
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000493 }
494 }
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000495 // Choose at most one coverage type: function, bb, or edge.
496 if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageBB))
497 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
498 << "-fsanitize-coverage=func"
499 << "-fsanitize-coverage=bb";
500 if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageEdge))
501 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
502 << "-fsanitize-coverage=func"
503 << "-fsanitize-coverage=edge";
504 if ((CoverageFeatures & CoverageBB) && (CoverageFeatures & CoverageEdge))
505 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
506 << "-fsanitize-coverage=bb"
507 << "-fsanitize-coverage=edge";
508 // Basic block tracing and 8-bit counters require some type of coverage
509 // enabled.
510 int CoverageTypes = CoverageFunc | CoverageBB | CoverageEdge;
Kostya Serebryany1c0e9e92017-04-19 21:31:11 +0000511 if (CoverageFeatures & CoverageTraceBB)
512 D.Diag(clang::diag::warn_drv_deprecated_arg)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000513 << "-fsanitize-coverage=trace-bb"
Kostya Serebryany1c0e9e92017-04-19 21:31:11 +0000514 << "-fsanitize-coverage=trace-pc-guard";
515 if (CoverageFeatures & Coverage8bitCounters)
Kostya Serebryany1a02d8b2017-04-19 20:15:58 +0000516 D.Diag(clang::diag::warn_drv_deprecated_arg)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000517 << "-fsanitize-coverage=8bit-counters"
Kostya Serebryany1a02d8b2017-04-19 20:15:58 +0000518 << "-fsanitize-coverage=trace-pc-guard";
Kostya Serebryany52e86492016-02-18 00:49:23 +0000519 // trace-pc w/o func/bb/edge implies edge.
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000520 if ((CoverageFeatures & (CoverageTracePC | CoverageTracePCGuard)) &&
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000521 !(CoverageFeatures & CoverageTypes))
Kostya Serebryany52e86492016-02-18 00:49:23 +0000522 CoverageFeatures |= CoverageEdge;
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000523
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000524 if (AllAddedKinds & Address) {
Alexey Samsonovbdfa6c22014-04-01 13:31:10 +0000525 AsanSharedRuntime =
Evgeniy Stepanov14deb7b2015-10-08 21:21:44 +0000526 Args.hasArg(options::OPT_shared_libasan) || TC.getTriple().isAndroid();
Evgeniy Stepanov71554fe2015-10-21 21:28:49 +0000527 NeedPIE |= TC.getTriple().isAndroid();
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000528 if (Arg *A =
529 Args.getLastArg(options::OPT_fsanitize_address_field_padding)) {
530 StringRef S = A->getValue();
531 // Legal values are 0 and 1, 2, but in future we may add more levels.
532 if (S.getAsInteger(0, AsanFieldPadding) || AsanFieldPadding < 0 ||
533 AsanFieldPadding > 2) {
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000534 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000535 }
536 }
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000537
538 if (Arg *WindowsDebugRTArg =
539 Args.getLastArg(options::OPT__SLASH_MTd, options::OPT__SLASH_MT,
540 options::OPT__SLASH_MDd, options::OPT__SLASH_MD,
541 options::OPT__SLASH_LDd, options::OPT__SLASH_LD)) {
542 switch (WindowsDebugRTArg->getOption().getID()) {
543 case options::OPT__SLASH_MTd:
544 case options::OPT__SLASH_MDd:
545 case options::OPT__SLASH_LDd:
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000546 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000547 << WindowsDebugRTArg->getAsString(Args)
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000548 << lastArgumentForMask(D, Args, Address);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000549 D.Diag(clang::diag::note_drv_address_sanitizer_debug_runtime);
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000550 }
551 }
Alexey Samsonov90490af2014-08-08 22:47:17 +0000552
Vitaly Bukaa77ac1b2016-10-10 21:31:50 +0000553 if (Arg *A = Args.getLastArg(
554 options::OPT_fsanitize_address_use_after_scope,
555 options::OPT_fno_sanitize_address_use_after_scope)) {
556 AsanUseAfterScope = A->getOption().getID() ==
557 options::OPT_fsanitize_address_use_after_scope;
558 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000559 }
560
Alexey Samsonov90490af2014-08-08 22:47:17 +0000561 // Parse -link-cxx-sanitizer flag.
562 LinkCXXRuntimes =
563 Args.hasArg(options::OPT_fsanitize_link_cxx_runtime) || D.CCCIsCXX();
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000564
565 // Finally, initialize the set of available and recoverable sanitizers.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000566 Sanitizers.Mask |= Kinds;
567 RecoverableSanitizers.Mask |= RecoverableKinds;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000568 TrapSanitizers.Mask |= TrappingKinds;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000569}
570
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000571static std::string toString(const clang::SanitizerSet &Sanitizers) {
572 std::string Res;
573#define SANITIZER(NAME, ID) \
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000574 if (Sanitizers.has(ID)) { \
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000575 if (!Res.empty()) \
576 Res += ","; \
577 Res += NAME; \
578 }
579#include "clang/Basic/Sanitizers.def"
580 return Res;
581}
582
Peter Collingbournedc134532016-01-16 00:31:22 +0000583static void addIncludeLinkerOption(const ToolChain &TC,
584 const llvm::opt::ArgList &Args,
585 llvm::opt::ArgStringList &CmdArgs,
586 StringRef SymbolName) {
587 SmallString<64> LinkerOptionFlag;
588 LinkerOptionFlag = "--linker-option=/include:";
589 if (TC.getTriple().getArch() == llvm::Triple::x86) {
590 // Win32 mangles C function names with a '_' prefix.
591 LinkerOptionFlag += '_';
592 }
593 LinkerOptionFlag += SymbolName;
594 CmdArgs.push_back(Args.MakeArgString(LinkerOptionFlag));
595}
596
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000597void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args,
Peter Collingbourne581f4382015-07-02 01:48:12 +0000598 llvm::opt::ArgStringList &CmdArgs,
599 types::ID InputType) const {
Justin Lebar6efbc732016-09-15 23:44:13 +0000600 // NVPTX doesn't currently support sanitizers. Bailing out here means that
601 // e.g. -fsanitize=address applies only to host code, which is what we want
602 // for now.
603 if (TC.getTriple().isNVPTX())
604 return;
605
Kostya Serebryany52e86492016-02-18 00:49:23 +0000606 // Translate available CoverageFeatures to corresponding clang-cc1 flags.
607 // Do it even if Sanitizers.empty() since some forms of coverage don't require
608 // sanitizers.
609 std::pair<int, const char *> CoverageFlags[] = {
610 std::make_pair(CoverageFunc, "-fsanitize-coverage-type=1"),
611 std::make_pair(CoverageBB, "-fsanitize-coverage-type=2"),
612 std::make_pair(CoverageEdge, "-fsanitize-coverage-type=3"),
613 std::make_pair(CoverageIndirCall, "-fsanitize-coverage-indirect-calls"),
614 std::make_pair(CoverageTraceBB, "-fsanitize-coverage-trace-bb"),
615 std::make_pair(CoverageTraceCmp, "-fsanitize-coverage-trace-cmp"),
Kostya Serebryany3b419712016-08-30 01:27:03 +0000616 std::make_pair(CoverageTraceDiv, "-fsanitize-coverage-trace-div"),
617 std::make_pair(CoverageTraceGep, "-fsanitize-coverage-trace-gep"),
Kostya Serebryany52e86492016-02-18 00:49:23 +0000618 std::make_pair(Coverage8bitCounters, "-fsanitize-coverage-8bit-counters"),
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000619 std::make_pair(CoverageTracePC, "-fsanitize-coverage-trace-pc"),
620 std::make_pair(CoverageTracePCGuard, "-fsanitize-coverage-trace-pc-guard")};
Kostya Serebryany52e86492016-02-18 00:49:23 +0000621 for (auto F : CoverageFlags) {
622 if (CoverageFeatures & F.first)
623 CmdArgs.push_back(Args.MakeArgString(F.second));
624 }
625
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000626 if (TC.getTriple().isOSWindows() && needsUbsanRt()) {
627 // Instruct the code generator to embed linker directives in the object file
628 // that cause the required runtime libraries to be linked.
629 CmdArgs.push_back(Args.MakeArgString(
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000630 "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000631 if (types::isCXX(InputType))
632 CmdArgs.push_back(Args.MakeArgString(
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000633 "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone_cxx")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000634 }
635 if (TC.getTriple().isOSWindows() && needsStatsRt()) {
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000636 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
637 TC.getCompilerRT(Args, "stats_client")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000638
639 // The main executable must export the stats runtime.
640 // FIXME: Only exporting from the main executable (e.g. based on whether the
641 // translation unit defines main()) would save a little space, but having
642 // multiple copies of the runtime shouldn't hurt.
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000643 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
644 TC.getCompilerRT(Args, "stats")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000645 addIncludeLinkerOption(TC, Args, CmdArgs, "__sanitizer_stats_register");
646 }
647
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000648 if (Sanitizers.empty())
Alexey Samsonovcf055962013-08-08 10:11:02 +0000649 return;
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000650 CmdArgs.push_back(Args.MakeArgString("-fsanitize=" + toString(Sanitizers)));
651
Alexey Samsonov88459522015-01-12 22:39:12 +0000652 if (!RecoverableSanitizers.empty())
653 CmdArgs.push_back(Args.MakeArgString("-fsanitize-recover=" +
654 toString(RecoverableSanitizers)));
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000655
Peter Collingbourne9881b782015-06-18 23:59:22 +0000656 if (!TrapSanitizers.empty())
657 CmdArgs.push_back(
658 Args.MakeArgString("-fsanitize-trap=" + toString(TrapSanitizers)));
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000659
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000660 for (const auto &BLPath : BlacklistFiles) {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000661 SmallString<64> BlacklistOpt("-fsanitize-blacklist=");
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000662 BlacklistOpt += BLPath;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000663 CmdArgs.push_back(Args.MakeArgString(BlacklistOpt));
664 }
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000665 for (const auto &Dep : ExtraDeps) {
666 SmallString<64> ExtraDepOpt("-fdepfile-entry=");
667 ExtraDepOpt += Dep;
668 CmdArgs.push_back(Args.MakeArgString(ExtraDepOpt));
669 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000670
671 if (MsanTrackOrigins)
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000672 CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins=" +
673 llvm::utostr(MsanTrackOrigins)));
Evgeniy Stepanov45be9e02015-07-10 20:07:16 +0000674
675 if (MsanUseAfterDtor)
676 CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-use-after-dtor"));
677
Evgeniy Stepanov8a2bedb2016-11-11 23:17:36 +0000678 // FIXME: Pass these parameters as function attributes, not as -llvm flags.
679 if (!TsanMemoryAccess) {
680 CmdArgs.push_back("-mllvm");
681 CmdArgs.push_back("-tsan-instrument-memory-accesses=0");
682 CmdArgs.push_back("-mllvm");
683 CmdArgs.push_back("-tsan-instrument-memintrinsics=0");
684 }
685 if (!TsanFuncEntryExit) {
686 CmdArgs.push_back("-mllvm");
687 CmdArgs.push_back("-tsan-instrument-func-entry-exit=0");
688 }
689 if (!TsanAtomics) {
690 CmdArgs.push_back("-mllvm");
691 CmdArgs.push_back("-tsan-instrument-atomics=0");
692 }
693
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000694 if (CfiCrossDso)
695 CmdArgs.push_back(Args.MakeArgString("-fsanitize-cfi-cross-dso"));
696
Peter Collingbournedc134532016-01-16 00:31:22 +0000697 if (Stats)
698 CmdArgs.push_back(Args.MakeArgString("-fsanitize-stats"));
699
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000700 if (AsanFieldPadding)
701 CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-field-padding=" +
702 llvm::utostr(AsanFieldPadding)));
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000703
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000704 if (AsanUseAfterScope)
705 CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-use-after-scope"));
706
Sergey Matveev2ba87782015-02-17 15:09:33 +0000707 // MSan: Workaround for PR16386.
708 // ASan: This is mainly to help LSan with cases such as
709 // https://code.google.com/p/address-sanitizer/issues/detail?id=373
710 // We can't make this conditional on -fsanitize=leak, as that flag shouldn't
711 // affect compilation.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000712 if (Sanitizers.has(Memory) || Sanitizers.has(Address))
Alexey Samsonovcf055962013-08-08 10:11:02 +0000713 CmdArgs.push_back(Args.MakeArgString("-fno-assume-sane-operator-new"));
Peter Collingbourne581f4382015-07-02 01:48:12 +0000714
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000715 // Require -fvisibility= flag on non-Windows when compiling if vptr CFI is
716 // enabled.
717 if (Sanitizers.hasOneOf(CFIClasses) && !TC.getTriple().isOSWindows() &&
718 !Args.hasArg(options::OPT_fvisibility_EQ)) {
719 TC.getDriver().Diag(clang::diag::err_drv_argument_only_allowed_with)
720 << lastArgumentForMask(TC.getDriver(), Args,
721 Sanitizers.Mask & CFIClasses)
722 << "-fvisibility=";
723 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000724}
725
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000726SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
727 bool DiagnoseErrors) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000728 assert((A->getOption().matches(options::OPT_fsanitize_EQ) ||
Alexey Samsonov88459522015-01-12 22:39:12 +0000729 A->getOption().matches(options::OPT_fno_sanitize_EQ) ||
730 A->getOption().matches(options::OPT_fsanitize_recover_EQ) ||
Peter Collingbourne9881b782015-06-18 23:59:22 +0000731 A->getOption().matches(options::OPT_fno_sanitize_recover_EQ) ||
732 A->getOption().matches(options::OPT_fsanitize_trap_EQ) ||
733 A->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) &&
Alexey Samsonov799f7932014-12-19 02:35:16 +0000734 "Invalid argument in parseArgValues!");
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000735 SanitizerMask Kinds = 0;
Alexey Samsonov83791e22015-03-03 22:15:32 +0000736 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
737 const char *Value = A->getValue(i);
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000738 SanitizerMask Kind;
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000739 // Special case: don't accept -fsanitize=all.
740 if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
741 0 == strcmp("all", Value))
742 Kind = 0;
Derek Bruening256c2e12016-04-21 21:32:04 +0000743 // Similarly, don't accept -fsanitize=efficiency-all.
744 else if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
745 0 == strcmp("efficiency-all", Value))
746 Kind = 0;
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000747 else
Peter Collingbournebf59c342015-05-11 21:39:20 +0000748 Kind = parseSanitizerValue(Value, /*AllowGroups=*/true);
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000749
750 if (Kind)
751 Kinds |= Kind;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000752 else if (DiagnoseErrors)
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000753 D.Diag(clang::diag::err_drv_unsupported_option_argument)
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000754 << A->getOption().getName() << Value;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000755 }
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000756 return Kinds;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000757}
758
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000759int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A) {
760 assert(A->getOption().matches(options::OPT_fsanitize_coverage) ||
761 A->getOption().matches(options::OPT_fno_sanitize_coverage));
762 int Features = 0;
763 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
764 const char *Value = A->getValue(i);
765 int F = llvm::StringSwitch<int>(Value)
766 .Case("func", CoverageFunc)
767 .Case("bb", CoverageBB)
768 .Case("edge", CoverageEdge)
769 .Case("indirect-calls", CoverageIndirCall)
770 .Case("trace-bb", CoverageTraceBB)
771 .Case("trace-cmp", CoverageTraceCmp)
Kostya Serebryany3b419712016-08-30 01:27:03 +0000772 .Case("trace-div", CoverageTraceDiv)
773 .Case("trace-gep", CoverageTraceGep)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000774 .Case("8bit-counters", Coverage8bitCounters)
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000775 .Case("trace-pc", CoverageTracePC)
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000776 .Case("trace-pc-guard", CoverageTracePCGuard)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000777 .Default(0);
778 if (F == 0)
779 D.Diag(clang::diag::err_drv_unsupported_option_argument)
780 << A->getOption().getName() << Value;
781 Features |= F;
782 }
783 return Features;
784}
785
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000786std::string lastArgumentForMask(const Driver &D, const llvm::opt::ArgList &Args,
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000787 SanitizerMask Mask) {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000788 for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(),
789 E = Args.rend();
790 I != E; ++I) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000791 const auto *Arg = *I;
792 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000793 SanitizerMask AddKinds =
794 expandSanitizerGroups(parseArgValues(D, Arg, false));
Alexey Samsonov799f7932014-12-19 02:35:16 +0000795 if (AddKinds & Mask)
796 return describeSanitizeArg(Arg, Mask);
797 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000798 SanitizerMask RemoveKinds =
799 expandSanitizerGroups(parseArgValues(D, Arg, false));
Alexey Samsonov799f7932014-12-19 02:35:16 +0000800 Mask &= ~RemoveKinds;
801 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000802 }
803 llvm_unreachable("arg list didn't provide expected value");
804}
805
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000806std::string describeSanitizeArg(const llvm::opt::Arg *A, SanitizerMask Mask) {
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000807 assert(A->getOption().matches(options::OPT_fsanitize_EQ)
808 && "Invalid argument in describeSanitizerArg!");
Alexey Samsonovcf055962013-08-08 10:11:02 +0000809
Peter Collingbourne32701642013-11-01 18:16:25 +0000810 std::string Sanitizers;
Alexey Samsonov83791e22015-03-03 22:15:32 +0000811 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000812 if (expandSanitizerGroups(
813 parseSanitizerValue(A->getValue(i), /*AllowGroups=*/true)) &
814 Mask) {
Peter Collingbourne32701642013-11-01 18:16:25 +0000815 if (!Sanitizers.empty())
816 Sanitizers += ",";
Alexey Samsonov83791e22015-03-03 22:15:32 +0000817 Sanitizers += A->getValue(i);
Peter Collingbourne32701642013-11-01 18:16:25 +0000818 }
819 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000820
Peter Collingbourne32701642013-11-01 18:16:25 +0000821 assert(!Sanitizers.empty() && "arg didn't provide expected value");
822 return "-fsanitize=" + Sanitizers;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000823}