blob: 16a3672472da4fa3a0380295cb2390e561339325 [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"
Peter Collingbourne581f4382015-07-02 01:48:12 +000010#include "Tools.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 {
Peter Collingbourne6708c4a2015-06-19 01:51:54 +000029 NeedsUbsanRt = Undefined | Integer | 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,
Kostya Serebryany6fe5fcb2015-03-20 00:06:52 +000034 SupportsCoverage = Address | Memory | Leak | Undefined | Integer | DataFlow,
Alexey Samsonov88459522015-01-12 22:39:12 +000035 RecoverableByDefault = Undefined | Integer,
Yury Gribov5bfeca12015-11-11 10:45:48 +000036 Unrecoverable = Unreachable | Return,
Peter Collingbournea4ccff32015-02-20 20:30:56 +000037 LegacyFsanitizeRecoverMask = Undefined | Integer,
Peter Collingbourne1a7488a2015-04-02 00:23:30 +000038 NeedsLTO = CFI,
Peter Collingbourne9881b782015-06-18 23:59:22 +000039 TrappingSupported =
Peter Collingbourne6708c4a2015-06-19 01:51:54 +000040 (Undefined & ~Vptr) | UnsignedIntegerOverflow | LocalBounds | CFI,
41 TrappingDefault = CFI,
Peter Collingbourne3afb2662016-04-28 17:09:37 +000042 CFIClasses = CFIVCall | CFINVCall | CFIDerivedCast | CFIUnrelatedCast,
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000043};
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000044
45enum CoverageFeature {
46 CoverageFunc = 1 << 0,
47 CoverageBB = 1 << 1,
48 CoverageEdge = 1 << 2,
49 CoverageIndirCall = 1 << 3,
50 CoverageTraceBB = 1 << 4,
51 CoverageTraceCmp = 1 << 5,
Kostya Serebryany3b419712016-08-30 01:27:03 +000052 CoverageTraceDiv = 1 << 6,
53 CoverageTraceGep = 1 << 7,
54 Coverage8bitCounters = 1 << 8,
55 CoverageTracePC = 1 << 9,
Kostya Serebryany60cdd612016-09-14 01:39:49 +000056 CoverageTracePCGuard = 1 << 10,
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000057};
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000058
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000059/// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
Peter Collingbourne3eea6772015-05-11 21:39:14 +000060/// invalid components. Returns a SanitizerMask.
61static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
62 bool DiagnoseErrors);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000063
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000064/// Parse -f(no-)?sanitize-coverage= flag values, diagnosing any invalid
65/// components. Returns OR of members of \c CoverageFeature enumeration.
66static int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A);
67
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000068/// Produce an argument string from ArgList \p Args, which shows how it
69/// provides some sanitizer kind from \p Mask. For example, the argument list
70/// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt
71/// would produce "-fsanitize=vptr".
72static std::string lastArgumentForMask(const Driver &D,
73 const llvm::opt::ArgList &Args,
Peter Collingbourne3eea6772015-05-11 21:39:14 +000074 SanitizerMask Mask);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000075
76/// Produce an argument string from argument \p A, which shows how it provides
77/// a value in \p Mask. For instance, the argument
78/// "-fsanitize=address,alignment" with mask \c NeedsUbsanRt would produce
79/// "-fsanitize=alignment".
Peter Collingbourne3eea6772015-05-11 21:39:14 +000080static std::string describeSanitizeArg(const llvm::opt::Arg *A,
81 SanitizerMask Mask);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000082
Alexey Samsonov1e715a62014-11-16 20:53:53 +000083/// Produce a string containing comma-separated names of sanitizers in \p
84/// Sanitizers set.
85static std::string toString(const clang::SanitizerSet &Sanitizers);
86
Peter Collingbourne3eea6772015-05-11 21:39:14 +000087static bool getDefaultBlacklist(const Driver &D, SanitizerMask Kinds,
Alexey Samsonovecf380e2015-03-20 18:45:06 +000088 std::string &BLPath) {
89 const char *BlacklistFile = nullptr;
Peter Collingbourne3eea6772015-05-11 21:39:14 +000090 if (Kinds & Address)
Alexey Samsonovecf380e2015-03-20 18:45:06 +000091 BlacklistFile = "asan_blacklist.txt";
Peter Collingbourne3eea6772015-05-11 21:39:14 +000092 else if (Kinds & Memory)
Alexey Samsonovecf380e2015-03-20 18:45:06 +000093 BlacklistFile = "msan_blacklist.txt";
Peter Collingbourne3eea6772015-05-11 21:39:14 +000094 else if (Kinds & Thread)
Alexey Samsonovecf380e2015-03-20 18:45:06 +000095 BlacklistFile = "tsan_blacklist.txt";
Peter Collingbourne3eea6772015-05-11 21:39:14 +000096 else if (Kinds & DataFlow)
Alexey Samsonovecf380e2015-03-20 18:45:06 +000097 BlacklistFile = "dfsan_abilist.txt";
Peter Collingbourne6fccf952015-07-15 12:15:56 +000098 else if (Kinds & CFI)
99 BlacklistFile = "cfi_blacklist.txt";
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000100
101 if (BlacklistFile) {
102 clang::SmallString<64> Path(D.ResourceDir);
103 llvm::sys::path::append(Path, BlacklistFile);
104 BLPath = Path.str();
105 return true;
106 }
107 return false;
108}
109
Peter Collingbourne9881b782015-06-18 23:59:22 +0000110/// Sets group bits for every group that has at least one representative already
111/// enabled in \p Kinds.
112static SanitizerMask setGroupBits(SanitizerMask Kinds) {
113#define SANITIZER(NAME, ID)
114#define SANITIZER_GROUP(NAME, ID, ALIAS) \
115 if (Kinds & SanitizerKind::ID) \
116 Kinds |= SanitizerKind::ID##Group;
117#include "clang/Basic/Sanitizers.def"
118 return Kinds;
119}
120
121static SanitizerMask parseSanitizeTrapArgs(const Driver &D,
122 const llvm::opt::ArgList &Args) {
123 SanitizerMask TrapRemove = 0; // During the loop below, the accumulated set of
124 // sanitizers disabled by the current sanitizer
125 // argument or any argument after it.
126 SanitizerMask TrappingKinds = 0;
127 SanitizerMask TrappingSupportedWithGroups = setGroupBits(TrappingSupported);
128
129 for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
130 I != E; ++I) {
131 const auto *Arg = *I;
132 if (Arg->getOption().matches(options::OPT_fsanitize_trap_EQ)) {
133 Arg->claim();
134 SanitizerMask Add = parseArgValues(D, Arg, true);
135 Add &= ~TrapRemove;
136 if (SanitizerMask InvalidValues = Add & ~TrappingSupportedWithGroups) {
137 SanitizerSet S;
138 S.Mask = InvalidValues;
139 D.Diag(diag::err_drv_unsupported_option_argument) << "-fsanitize-trap"
140 << toString(S);
141 }
142 TrappingKinds |= expandSanitizerGroups(Add) & ~TrapRemove;
143 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) {
144 Arg->claim();
145 TrapRemove |= expandSanitizerGroups(parseArgValues(D, Arg, true));
146 } else if (Arg->getOption().matches(
147 options::OPT_fsanitize_undefined_trap_on_error)) {
148 Arg->claim();
149 TrappingKinds |=
150 expandSanitizerGroups(UndefinedGroup & ~TrapRemove) & ~TrapRemove;
151 } else if (Arg->getOption().matches(
152 options::OPT_fno_sanitize_undefined_trap_on_error)) {
153 Arg->claim();
154 TrapRemove |= expandSanitizerGroups(UndefinedGroup);
155 }
156 }
157
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000158 // Apply default trapping behavior.
159 TrappingKinds |= TrappingDefault & ~TrapRemove;
160
Peter Collingbourne9881b782015-06-18 23:59:22 +0000161 return TrappingKinds;
162}
163
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000164bool SanitizerArgs::needsUbsanRt() const {
Evgeniy Stepanov5b49eb42016-06-14 21:33:40 +0000165 return ((Sanitizers.Mask & NeedsUbsanRt & ~TrapSanitizers.Mask) ||
166 CoverageFeatures) &&
167 !Sanitizers.has(Address) && !Sanitizers.has(Memory) &&
Evgeniy Stepanovaac94b12016-06-15 23:05:21 +0000168 !Sanitizers.has(Thread) && !Sanitizers.has(DataFlow) && !CfiCrossDso;
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000169}
170
171bool SanitizerArgs::needsCfiRt() const {
Evgeniy Stepanove3fb51c2015-12-16 00:38:42 +0000172 return !(Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso;
173}
174
175bool SanitizerArgs::needsCfiDiagRt() const {
176 return (Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso;
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000177}
178
Dmitry Vyukov43419a72014-11-21 12:19:01 +0000179bool SanitizerArgs::requiresPIE() const {
Evgeniy Stepanov71554fe2015-10-21 21:28:49 +0000180 return NeedPIE || (Sanitizers.Mask & RequiresPIE);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000181}
182
183bool SanitizerArgs::needsUnwindTables() const {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000184 return Sanitizers.Mask & NeedsUnwindTables;
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000185}
186
Peter Collingbourne32701642013-11-01 18:16:25 +0000187SanitizerArgs::SanitizerArgs(const ToolChain &TC,
188 const llvm::opt::ArgList &Args) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000189 SanitizerMask AllRemove = 0; // During the loop below, the accumulated set of
190 // sanitizers disabled by the current sanitizer
191 // argument or any argument after it.
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000192 SanitizerMask AllAddedKinds = 0; // Mask of all sanitizers ever enabled by
193 // -fsanitize= flags (directly or via group
194 // expansion), some of which may be disabled
195 // later. Used to carefully prune
196 // unused-argument diagnostics.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000197 SanitizerMask DiagnosedKinds = 0; // All Kinds we have diagnosed up to now.
198 // Used to deduplicate diagnostics.
199 SanitizerMask Kinds = 0;
Alexey Samsonov9b873092015-06-25 23:14:32 +0000200 const SanitizerMask Supported = setGroupBits(TC.getSupportedSanitizers());
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000201 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
202
Peter Collingbourne32701642013-11-01 18:16:25 +0000203 const Driver &D = TC.getDriver();
Peter Collingbourne9881b782015-06-18 23:59:22 +0000204 SanitizerMask TrappingKinds = parseSanitizeTrapArgs(D, Args);
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000205 SanitizerMask InvalidTrappingKinds = TrappingKinds & NotAllowedWithTrap;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000206
Peter Collingbourne32701642013-11-01 18:16:25 +0000207 for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
208 I != E; ++I) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000209 const auto *Arg = *I;
210 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
211 Arg->claim();
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000212 SanitizerMask Add = parseArgValues(D, Arg, true);
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000213 AllAddedKinds |= expandSanitizerGroups(Add);
Peter Collingbourne32701642013-11-01 18:16:25 +0000214
Alexey Samsonov799f7932014-12-19 02:35:16 +0000215 // Avoid diagnosing any sanitizer which is disabled later.
216 Add &= ~AllRemove;
217 // At this point we have not expanded groups, so any unsupported
218 // sanitizers in Add are those which have been explicitly enabled.
219 // Diagnose them.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000220 if (SanitizerMask KindsToDiagnose =
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000221 Add & InvalidTrappingKinds & ~DiagnosedKinds) {
Peter Collingbourne9881b782015-06-18 23:59:22 +0000222 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
223 D.Diag(diag::err_drv_argument_not_allowed_with)
224 << Desc << "-fsanitize-trap=undefined";
225 DiagnosedKinds |= KindsToDiagnose;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000226 }
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000227 Add &= ~InvalidTrappingKinds;
228 if (SanitizerMask KindsToDiagnose = Add & ~Supported & ~DiagnosedKinds) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000229 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
230 D.Diag(diag::err_drv_unsupported_opt_for_target)
231 << Desc << TC.getTriple().str();
232 DiagnosedKinds |= KindsToDiagnose;
233 }
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000234 Add &= Supported;
Peter Collingbourne32701642013-11-01 18:16:25 +0000235
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000236 // Test for -fno-rtti + explicit -fsanitizer=vptr before expanding groups
237 // so we don't error out if -fno-rtti and -fsanitize=undefined were
238 // passed.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000239 if (Add & Vptr &&
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000240 (RTTIMode == ToolChain::RM_DisabledImplicitly ||
241 RTTIMode == ToolChain::RM_DisabledExplicitly)) {
242 if (RTTIMode == ToolChain::RM_DisabledImplicitly)
243 // Warn about not having rtti enabled if the vptr sanitizer is
244 // explicitly enabled
245 D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default);
246 else {
247 const llvm::opt::Arg *NoRTTIArg = TC.getRTTIArg();
248 assert(NoRTTIArg &&
249 "RTTI disabled explicitly but we have no argument!");
250 D.Diag(diag::err_drv_argument_not_allowed_with)
251 << "-fsanitize=vptr" << NoRTTIArg->getAsString(Args);
252 }
253
254 // Take out the Vptr sanitizer from the enabled sanitizers
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000255 AllRemove |= Vptr;
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000256 }
257
Peter Collingbournebf59c342015-05-11 21:39:20 +0000258 Add = expandSanitizerGroups(Add);
Alexey Samsonov799f7932014-12-19 02:35:16 +0000259 // Group expansion may have enabled a sanitizer which is disabled later.
260 Add &= ~AllRemove;
261 // Silently discard any unsupported sanitizers implicitly enabled through
262 // group expansion.
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000263 Add &= ~InvalidTrappingKinds;
264 Add &= Supported;
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000265
Alexey Samsonov799f7932014-12-19 02:35:16 +0000266 Kinds |= Add;
267 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
268 Arg->claim();
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000269 SanitizerMask Remove = parseArgValues(D, Arg, true);
Peter Collingbournebf59c342015-05-11 21:39:20 +0000270 AllRemove |= expandSanitizerGroups(Remove);
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000271 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000272 }
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000273
Ed Schoutenfc79d2c2016-03-29 21:13:53 +0000274 // Enable toolchain specific default sanitizers if not explicitly disabled.
275 Kinds |= TC.getDefaultSanitizers() & ~AllRemove;
276
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000277 // We disable the vptr sanitizer if it was enabled by group expansion but RTTI
278 // is disabled.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000279 if ((Kinds & Vptr) &&
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000280 (RTTIMode == ToolChain::RM_DisabledImplicitly ||
281 RTTIMode == ToolChain::RM_DisabledExplicitly)) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000282 Kinds &= ~Vptr;
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000283 }
284
Alexey Samsonov907880e2015-06-19 19:57:46 +0000285 // Check that LTO is enabled if we need it.
Teresa Johnson945bc502015-10-15 20:35:53 +0000286 if ((Kinds & NeedsLTO) && !D.isUsingLTO()) {
Alexey Samsonov907880e2015-06-19 19:57:46 +0000287 D.Diag(diag::err_drv_argument_only_allowed_with)
288 << lastArgumentForMask(D, Args, Kinds & NeedsLTO) << "-flto";
289 }
290
Alexey Samsonov9b873092015-06-25 23:14:32 +0000291 // Report error if there are non-trapping sanitizers that require
292 // c++abi-specific parts of UBSan runtime, and they are not provided by the
293 // toolchain. We don't have a good way to check the latter, so we just
294 // check if the toolchan supports vptr.
295 if (~Supported & Vptr) {
Peter Collingbourne4bdceaa2015-07-08 21:08:05 +0000296 SanitizerMask KindsToDiagnose = Kinds & ~TrappingKinds & NeedsUbsanCxxRt;
297 // The runtime library supports the Microsoft C++ ABI, but only well enough
298 // for CFI. FIXME: Remove this once we support vptr on Windows.
299 if (TC.getTriple().isOSWindows())
300 KindsToDiagnose &= ~CFI;
301 if (KindsToDiagnose) {
Alexey Samsonov9b873092015-06-25 23:14:32 +0000302 SanitizerSet S;
303 S.Mask = KindsToDiagnose;
304 D.Diag(diag::err_drv_unsupported_opt_for_target)
305 << ("-fno-sanitize-trap=" + toString(S)) << TC.getTriple().str();
306 Kinds &= ~KindsToDiagnose;
307 }
308 }
309
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000310 // Warn about incompatible groups of sanitizers.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000311 std::pair<SanitizerMask, SanitizerMask> IncompatibleGroups[] = {
312 std::make_pair(Address, Thread), std::make_pair(Address, Memory),
313 std::make_pair(Thread, Memory), std::make_pair(Leak, Thread),
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000314 std::make_pair(Leak, Memory), std::make_pair(KernelAddress, Address),
315 std::make_pair(KernelAddress, Leak),
316 std::make_pair(KernelAddress, Thread),
Derek Bruening256c2e12016-04-21 21:32:04 +0000317 std::make_pair(KernelAddress, Memory),
318 std::make_pair(Efficiency, Address),
319 std::make_pair(Efficiency, Leak),
320 std::make_pair(Efficiency, Thread),
321 std::make_pair(Efficiency, Memory),
322 std::make_pair(Efficiency, KernelAddress)};
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000323 for (auto G : IncompatibleGroups) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000324 SanitizerMask Group = G.first;
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000325 if (Kinds & Group) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000326 if (SanitizerMask Incompatible = Kinds & G.second) {
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000327 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
328 << lastArgumentForMask(D, Args, Group)
329 << lastArgumentForMask(D, Args, Incompatible);
330 Kinds &= ~Incompatible;
331 }
332 }
333 }
334 // FIXME: Currently -fsanitize=leak is silently ignored in the presence of
335 // -fsanitize=address. Perhaps it should print an error, or perhaps
336 // -f(-no)sanitize=leak should change whether leak detection is enabled by
337 // default in ASan?
338
Alexey Samsonov88459522015-01-12 22:39:12 +0000339 // Parse -f(no-)?sanitize-recover flags.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000340 SanitizerMask RecoverableKinds = RecoverableByDefault;
341 SanitizerMask DiagnosedUnrecoverableKinds = 0;
Alexey Samsonov88459522015-01-12 22:39:12 +0000342 for (const auto *Arg : Args) {
Alexey Samsonovce2e77c2015-03-11 23:34:25 +0000343 const char *DeprecatedReplacement = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +0000344 if (Arg->getOption().matches(options::OPT_fsanitize_recover)) {
Kostya Serebryanyceb1add2016-05-04 20:21:47 +0000345 DeprecatedReplacement =
346 "-fsanitize-recover=undefined,integer' or '-fsanitize-recover=all";
Peter Collingbournebf59c342015-05-11 21:39:20 +0000347 RecoverableKinds |= expandSanitizerGroups(LegacyFsanitizeRecoverMask);
Alexey Samsonov88459522015-01-12 22:39:12 +0000348 Arg->claim();
349 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover)) {
Kostya Serebryanyceb1add2016-05-04 20:21:47 +0000350 DeprecatedReplacement = "-fno-sanitize-recover=undefined,integer' or "
351 "'-fno-sanitize-recover=all";
Peter Collingbournebf59c342015-05-11 21:39:20 +0000352 RecoverableKinds &= ~expandSanitizerGroups(LegacyFsanitizeRecoverMask);
Alexey Samsonov88459522015-01-12 22:39:12 +0000353 Arg->claim();
354 } else if (Arg->getOption().matches(options::OPT_fsanitize_recover_EQ)) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000355 SanitizerMask Add = parseArgValues(D, Arg, true);
Alexey Samsonov88459522015-01-12 22:39:12 +0000356 // Report error if user explicitly tries to recover from unrecoverable
357 // sanitizer.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000358 if (SanitizerMask KindsToDiagnose =
Alexey Samsonov88459522015-01-12 22:39:12 +0000359 Add & Unrecoverable & ~DiagnosedUnrecoverableKinds) {
360 SanitizerSet SetToDiagnose;
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000361 SetToDiagnose.Mask |= KindsToDiagnose;
Alexey Samsonov88459522015-01-12 22:39:12 +0000362 D.Diag(diag::err_drv_unsupported_option_argument)
363 << Arg->getOption().getName() << toString(SetToDiagnose);
364 DiagnosedUnrecoverableKinds |= KindsToDiagnose;
365 }
Peter Collingbournebf59c342015-05-11 21:39:20 +0000366 RecoverableKinds |= expandSanitizerGroups(Add);
Alexey Samsonov88459522015-01-12 22:39:12 +0000367 Arg->claim();
368 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000369 RecoverableKinds &= ~expandSanitizerGroups(parseArgValues(D, Arg, true));
Alexey Samsonov88459522015-01-12 22:39:12 +0000370 Arg->claim();
371 }
Alexey Samsonovce2e77c2015-03-11 23:34:25 +0000372 if (DeprecatedReplacement) {
373 D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
374 << DeprecatedReplacement;
375 }
Alexey Samsonov88459522015-01-12 22:39:12 +0000376 }
377 RecoverableKinds &= Kinds;
378 RecoverableKinds &= ~Unrecoverable;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000379
Peter Collingbourne9881b782015-06-18 23:59:22 +0000380 TrappingKinds &= Kinds;
381
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000382 // Setup blacklist files.
383 // Add default blacklist from resource directory.
384 {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000385 std::string BLPath;
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000386 if (getDefaultBlacklist(D, Kinds, BLPath) && llvm::sys::fs::exists(BLPath))
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000387 BlacklistFiles.push_back(BLPath);
388 }
389 // Parse -f(no-)sanitize-blacklist options.
390 for (const auto *Arg : Args) {
391 if (Arg->getOption().matches(options::OPT_fsanitize_blacklist)) {
392 Arg->claim();
393 std::string BLPath = Arg->getValue();
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000394 if (llvm::sys::fs::exists(BLPath)) {
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000395 BlacklistFiles.push_back(BLPath);
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000396 ExtraDeps.push_back(BLPath);
397 } else
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000398 D.Diag(clang::diag::err_drv_no_such_file) << BLPath;
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000399
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000400 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_blacklist)) {
401 Arg->claim();
402 BlacklistFiles.clear();
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000403 ExtraDeps.clear();
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000404 }
405 }
406 // Validate blacklists format.
407 {
408 std::string BLError;
409 std::unique_ptr<llvm::SpecialCaseList> SCL(
410 llvm::SpecialCaseList::create(BlacklistFiles, BLError));
411 if (!SCL.get())
412 D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000413 }
414
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000415 // Parse -f[no-]sanitize-memory-track-origins[=level] options.
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000416 if (AllAddedKinds & Memory) {
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000417 if (Arg *A =
418 Args.getLastArg(options::OPT_fsanitize_memory_track_origins_EQ,
419 options::OPT_fsanitize_memory_track_origins,
420 options::OPT_fno_sanitize_memory_track_origins)) {
421 if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) {
Evgeniy Stepanov6e09bca2015-02-26 15:59:30 +0000422 MsanTrackOrigins = 2;
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000423 } else if (A->getOption().matches(
424 options::OPT_fno_sanitize_memory_track_origins)) {
425 MsanTrackOrigins = 0;
426 } else {
427 StringRef S = A->getValue();
428 if (S.getAsInteger(0, MsanTrackOrigins) || MsanTrackOrigins < 0 ||
429 MsanTrackOrigins > 2) {
Nico Weberf2a39a72015-04-13 20:03:03 +0000430 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000431 }
432 }
433 }
Evgeniy Stepanov71554fe2015-10-21 21:28:49 +0000434 MsanUseAfterDtor =
435 Args.hasArg(options::OPT_fsanitize_memory_use_after_dtor);
436 NeedPIE |= !(TC.getTriple().isOSLinux() &&
437 TC.getTriple().getArch() == llvm::Triple::x86_64);
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000438 }
439
Evgeniy Stepanov8a2bedb2016-11-11 23:17:36 +0000440 if (AllAddedKinds & Thread) {
441 TsanMemoryAccess = Args.hasFlag(options::OPT_fsanitize_thread_memory_access,
442 options::OPT_fno_sanitize_thread_memory_access,
443 TsanMemoryAccess);
444 TsanFuncEntryExit = Args.hasFlag(options::OPT_fsanitize_thread_func_entry_exit,
445 options::OPT_fno_sanitize_thread_func_entry_exit,
446 TsanFuncEntryExit);
447 TsanAtomics = Args.hasFlag(options::OPT_fsanitize_thread_atomics,
448 options::OPT_fno_sanitize_thread_atomics,
449 TsanAtomics);
450 }
451
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000452 if (AllAddedKinds & CFI) {
453 CfiCrossDso = Args.hasFlag(options::OPT_fsanitize_cfi_cross_dso,
454 options::OPT_fno_sanitize_cfi_cross_dso, false);
455 // Without PIE, external function address may resolve to a PLT record, which
456 // can not be verified by the target module.
457 NeedPIE |= CfiCrossDso;
458 }
459
Peter Collingbournedc134532016-01-16 00:31:22 +0000460 Stats = Args.hasFlag(options::OPT_fsanitize_stats,
461 options::OPT_fno_sanitize_stats, false);
462
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000463 // Parse -f(no-)?sanitize-coverage flags if coverage is supported by the
464 // enabled sanitizers.
Kostya Serebryany52e86492016-02-18 00:49:23 +0000465 for (const auto *Arg : Args) {
466 if (Arg->getOption().matches(options::OPT_fsanitize_coverage)) {
467 int LegacySanitizeCoverage;
468 if (Arg->getNumValues() == 1 &&
469 !StringRef(Arg->getValue(0))
470 .getAsInteger(0, LegacySanitizeCoverage) &&
471 LegacySanitizeCoverage >= 0 && LegacySanitizeCoverage <= 4) {
Kostya Serebryany52e86492016-02-18 00:49:23 +0000472 switch (LegacySanitizeCoverage) {
473 case 0:
474 CoverageFeatures = 0;
Kostya Serebryany578787a2016-03-02 19:16:54 +0000475 Arg->claim();
Kostya Serebryany52e86492016-02-18 00:49:23 +0000476 break;
477 case 1:
Nico Weber4152f522016-02-18 19:32:54 +0000478 D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
479 << "-fsanitize-coverage=func";
Kostya Serebryany52e86492016-02-18 00:49:23 +0000480 CoverageFeatures = CoverageFunc;
481 break;
482 case 2:
Nico Weber4152f522016-02-18 19:32:54 +0000483 D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
484 << "-fsanitize-coverage=bb";
Kostya Serebryany52e86492016-02-18 00:49:23 +0000485 CoverageFeatures = CoverageBB;
486 break;
487 case 3:
Nico Weber4152f522016-02-18 19:32:54 +0000488 D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
489 << "-fsanitize-coverage=edge";
Kostya Serebryany52e86492016-02-18 00:49:23 +0000490 CoverageFeatures = CoverageEdge;
491 break;
492 case 4:
Nico Weber4152f522016-02-18 19:32:54 +0000493 D.Diag(diag::warn_drv_deprecated_arg)
494 << Arg->getAsString(Args)
495 << "-fsanitize-coverage=edge,indirect-calls";
Kostya Serebryany52e86492016-02-18 00:49:23 +0000496 CoverageFeatures = CoverageEdge | CoverageIndirCall;
497 break;
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000498 }
Kostya Serebryany52e86492016-02-18 00:49:23 +0000499 continue;
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000500 }
Kostya Serebryany52e86492016-02-18 00:49:23 +0000501 CoverageFeatures |= parseCoverageFeatures(D, Arg);
Evgeniy Stepanov5b49eb42016-06-14 21:33:40 +0000502
503 // Disable coverage and not claim the flags if there is at least one
504 // non-supporting sanitizer.
505 if (!(AllAddedKinds & ~setGroupBits(SupportsCoverage))) {
Kostya Serebryany52e86492016-02-18 00:49:23 +0000506 Arg->claim();
Kostya Serebryanyf5b25f82016-04-18 21:30:17 +0000507 } else {
508 CoverageFeatures = 0;
Kostya Serebryany52e86492016-02-18 00:49:23 +0000509 }
510 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_coverage)) {
511 Arg->claim();
512 CoverageFeatures &= ~parseCoverageFeatures(D, Arg);
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000513 }
514 }
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000515 // Choose at most one coverage type: function, bb, or edge.
516 if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageBB))
517 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
518 << "-fsanitize-coverage=func"
519 << "-fsanitize-coverage=bb";
520 if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageEdge))
521 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
522 << "-fsanitize-coverage=func"
523 << "-fsanitize-coverage=edge";
524 if ((CoverageFeatures & CoverageBB) && (CoverageFeatures & CoverageEdge))
525 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
526 << "-fsanitize-coverage=bb"
527 << "-fsanitize-coverage=edge";
528 // Basic block tracing and 8-bit counters require some type of coverage
529 // enabled.
530 int CoverageTypes = CoverageFunc | CoverageBB | CoverageEdge;
531 if ((CoverageFeatures & CoverageTraceBB) &&
532 !(CoverageFeatures & CoverageTypes))
533 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
534 << "-fsanitize-coverage=trace-bb"
535 << "-fsanitize-coverage=(func|bb|edge)";
536 if ((CoverageFeatures & Coverage8bitCounters) &&
537 !(CoverageFeatures & CoverageTypes))
538 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
539 << "-fsanitize-coverage=8bit-counters"
540 << "-fsanitize-coverage=(func|bb|edge)";
Kostya Serebryany52e86492016-02-18 00:49:23 +0000541 // trace-pc w/o func/bb/edge implies edge.
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000542 if ((CoverageFeatures & (CoverageTracePC | CoverageTracePCGuard)) &&
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000543 !(CoverageFeatures & CoverageTypes))
Kostya Serebryany52e86492016-02-18 00:49:23 +0000544 CoverageFeatures |= CoverageEdge;
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000545
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000546 if (AllAddedKinds & Address) {
Alexey Samsonovbdfa6c22014-04-01 13:31:10 +0000547 AsanSharedRuntime =
Evgeniy Stepanov14deb7b2015-10-08 21:21:44 +0000548 Args.hasArg(options::OPT_shared_libasan) || TC.getTriple().isAndroid();
Evgeniy Stepanov71554fe2015-10-21 21:28:49 +0000549 NeedPIE |= TC.getTriple().isAndroid();
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000550 if (Arg *A =
551 Args.getLastArg(options::OPT_fsanitize_address_field_padding)) {
552 StringRef S = A->getValue();
553 // Legal values are 0 and 1, 2, but in future we may add more levels.
554 if (S.getAsInteger(0, AsanFieldPadding) || AsanFieldPadding < 0 ||
555 AsanFieldPadding > 2) {
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000556 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000557 }
558 }
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000559
560 if (Arg *WindowsDebugRTArg =
561 Args.getLastArg(options::OPT__SLASH_MTd, options::OPT__SLASH_MT,
562 options::OPT__SLASH_MDd, options::OPT__SLASH_MD,
563 options::OPT__SLASH_LDd, options::OPT__SLASH_LD)) {
564 switch (WindowsDebugRTArg->getOption().getID()) {
565 case options::OPT__SLASH_MTd:
566 case options::OPT__SLASH_MDd:
567 case options::OPT__SLASH_LDd:
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000568 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000569 << WindowsDebugRTArg->getAsString(Args)
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000570 << lastArgumentForMask(D, Args, Address);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000571 D.Diag(clang::diag::note_drv_address_sanitizer_debug_runtime);
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000572 }
573 }
Alexey Samsonov90490af2014-08-08 22:47:17 +0000574
Vitaly Bukaa77ac1b2016-10-10 21:31:50 +0000575 if (Arg *A = Args.getLastArg(
576 options::OPT_fsanitize_address_use_after_scope,
577 options::OPT_fno_sanitize_address_use_after_scope)) {
578 AsanUseAfterScope = A->getOption().getID() ==
579 options::OPT_fsanitize_address_use_after_scope;
580 }
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000581 }
582
Alexey Samsonov90490af2014-08-08 22:47:17 +0000583 // Parse -link-cxx-sanitizer flag.
584 LinkCXXRuntimes =
585 Args.hasArg(options::OPT_fsanitize_link_cxx_runtime) || D.CCCIsCXX();
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000586
587 // Finally, initialize the set of available and recoverable sanitizers.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000588 Sanitizers.Mask |= Kinds;
589 RecoverableSanitizers.Mask |= RecoverableKinds;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000590 TrapSanitizers.Mask |= TrappingKinds;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000591}
592
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000593static std::string toString(const clang::SanitizerSet &Sanitizers) {
594 std::string Res;
595#define SANITIZER(NAME, ID) \
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000596 if (Sanitizers.has(ID)) { \
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000597 if (!Res.empty()) \
598 Res += ","; \
599 Res += NAME; \
600 }
601#include "clang/Basic/Sanitizers.def"
602 return Res;
603}
604
Peter Collingbournedc134532016-01-16 00:31:22 +0000605static void addIncludeLinkerOption(const ToolChain &TC,
606 const llvm::opt::ArgList &Args,
607 llvm::opt::ArgStringList &CmdArgs,
608 StringRef SymbolName) {
609 SmallString<64> LinkerOptionFlag;
610 LinkerOptionFlag = "--linker-option=/include:";
611 if (TC.getTriple().getArch() == llvm::Triple::x86) {
612 // Win32 mangles C function names with a '_' prefix.
613 LinkerOptionFlag += '_';
614 }
615 LinkerOptionFlag += SymbolName;
616 CmdArgs.push_back(Args.MakeArgString(LinkerOptionFlag));
617}
618
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000619void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args,
Peter Collingbourne581f4382015-07-02 01:48:12 +0000620 llvm::opt::ArgStringList &CmdArgs,
621 types::ID InputType) const {
Justin Lebar6efbc732016-09-15 23:44:13 +0000622 // NVPTX doesn't currently support sanitizers. Bailing out here means that
623 // e.g. -fsanitize=address applies only to host code, which is what we want
624 // for now.
625 if (TC.getTriple().isNVPTX())
626 return;
627
Kostya Serebryany52e86492016-02-18 00:49:23 +0000628 // Translate available CoverageFeatures to corresponding clang-cc1 flags.
629 // Do it even if Sanitizers.empty() since some forms of coverage don't require
630 // sanitizers.
631 std::pair<int, const char *> CoverageFlags[] = {
632 std::make_pair(CoverageFunc, "-fsanitize-coverage-type=1"),
633 std::make_pair(CoverageBB, "-fsanitize-coverage-type=2"),
634 std::make_pair(CoverageEdge, "-fsanitize-coverage-type=3"),
635 std::make_pair(CoverageIndirCall, "-fsanitize-coverage-indirect-calls"),
636 std::make_pair(CoverageTraceBB, "-fsanitize-coverage-trace-bb"),
637 std::make_pair(CoverageTraceCmp, "-fsanitize-coverage-trace-cmp"),
Kostya Serebryany3b419712016-08-30 01:27:03 +0000638 std::make_pair(CoverageTraceDiv, "-fsanitize-coverage-trace-div"),
639 std::make_pair(CoverageTraceGep, "-fsanitize-coverage-trace-gep"),
Kostya Serebryany52e86492016-02-18 00:49:23 +0000640 std::make_pair(Coverage8bitCounters, "-fsanitize-coverage-8bit-counters"),
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000641 std::make_pair(CoverageTracePC, "-fsanitize-coverage-trace-pc"),
642 std::make_pair(CoverageTracePCGuard, "-fsanitize-coverage-trace-pc-guard")};
Kostya Serebryany52e86492016-02-18 00:49:23 +0000643 for (auto F : CoverageFlags) {
644 if (CoverageFeatures & F.first)
645 CmdArgs.push_back(Args.MakeArgString(F.second));
646 }
647
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000648 if (TC.getTriple().isOSWindows() && needsUbsanRt()) {
649 // Instruct the code generator to embed linker directives in the object file
650 // that cause the required runtime libraries to be linked.
651 CmdArgs.push_back(Args.MakeArgString(
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000652 "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000653 if (types::isCXX(InputType))
654 CmdArgs.push_back(Args.MakeArgString(
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000655 "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone_cxx")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000656 }
657 if (TC.getTriple().isOSWindows() && needsStatsRt()) {
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000658 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
659 TC.getCompilerRT(Args, "stats_client")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000660
661 // The main executable must export the stats runtime.
662 // FIXME: Only exporting from the main executable (e.g. based on whether the
663 // translation unit defines main()) would save a little space, but having
664 // multiple copies of the runtime shouldn't hurt.
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000665 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
666 TC.getCompilerRT(Args, "stats")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000667 addIncludeLinkerOption(TC, Args, CmdArgs, "__sanitizer_stats_register");
668 }
669
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000670 if (Sanitizers.empty())
Alexey Samsonovcf055962013-08-08 10:11:02 +0000671 return;
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000672 CmdArgs.push_back(Args.MakeArgString("-fsanitize=" + toString(Sanitizers)));
673
Alexey Samsonov88459522015-01-12 22:39:12 +0000674 if (!RecoverableSanitizers.empty())
675 CmdArgs.push_back(Args.MakeArgString("-fsanitize-recover=" +
676 toString(RecoverableSanitizers)));
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000677
Peter Collingbourne9881b782015-06-18 23:59:22 +0000678 if (!TrapSanitizers.empty())
679 CmdArgs.push_back(
680 Args.MakeArgString("-fsanitize-trap=" + toString(TrapSanitizers)));
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000681
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000682 for (const auto &BLPath : BlacklistFiles) {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000683 SmallString<64> BlacklistOpt("-fsanitize-blacklist=");
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000684 BlacklistOpt += BLPath;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000685 CmdArgs.push_back(Args.MakeArgString(BlacklistOpt));
686 }
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000687 for (const auto &Dep : ExtraDeps) {
688 SmallString<64> ExtraDepOpt("-fdepfile-entry=");
689 ExtraDepOpt += Dep;
690 CmdArgs.push_back(Args.MakeArgString(ExtraDepOpt));
691 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000692
693 if (MsanTrackOrigins)
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000694 CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins=" +
695 llvm::utostr(MsanTrackOrigins)));
Evgeniy Stepanov45be9e02015-07-10 20:07:16 +0000696
697 if (MsanUseAfterDtor)
698 CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-use-after-dtor"));
699
Evgeniy Stepanov8a2bedb2016-11-11 23:17:36 +0000700 // FIXME: Pass these parameters as function attributes, not as -llvm flags.
701 if (!TsanMemoryAccess) {
702 CmdArgs.push_back("-mllvm");
703 CmdArgs.push_back("-tsan-instrument-memory-accesses=0");
704 CmdArgs.push_back("-mllvm");
705 CmdArgs.push_back("-tsan-instrument-memintrinsics=0");
706 }
707 if (!TsanFuncEntryExit) {
708 CmdArgs.push_back("-mllvm");
709 CmdArgs.push_back("-tsan-instrument-func-entry-exit=0");
710 }
711 if (!TsanAtomics) {
712 CmdArgs.push_back("-mllvm");
713 CmdArgs.push_back("-tsan-instrument-atomics=0");
714 }
715
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000716 if (CfiCrossDso)
717 CmdArgs.push_back(Args.MakeArgString("-fsanitize-cfi-cross-dso"));
718
Peter Collingbournedc134532016-01-16 00:31:22 +0000719 if (Stats)
720 CmdArgs.push_back(Args.MakeArgString("-fsanitize-stats"));
721
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000722 if (AsanFieldPadding)
723 CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-field-padding=" +
724 llvm::utostr(AsanFieldPadding)));
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000725
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000726 if (AsanUseAfterScope)
727 CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-use-after-scope"));
728
Sergey Matveev2ba87782015-02-17 15:09:33 +0000729 // MSan: Workaround for PR16386.
730 // ASan: This is mainly to help LSan with cases such as
731 // https://code.google.com/p/address-sanitizer/issues/detail?id=373
732 // We can't make this conditional on -fsanitize=leak, as that flag shouldn't
733 // affect compilation.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000734 if (Sanitizers.has(Memory) || Sanitizers.has(Address))
Alexey Samsonovcf055962013-08-08 10:11:02 +0000735 CmdArgs.push_back(Args.MakeArgString("-fno-assume-sane-operator-new"));
Peter Collingbourne581f4382015-07-02 01:48:12 +0000736
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000737 // Require -fvisibility= flag on non-Windows when compiling if vptr CFI is
738 // enabled.
739 if (Sanitizers.hasOneOf(CFIClasses) && !TC.getTriple().isOSWindows() &&
740 !Args.hasArg(options::OPT_fvisibility_EQ)) {
741 TC.getDriver().Diag(clang::diag::err_drv_argument_only_allowed_with)
742 << lastArgumentForMask(TC.getDriver(), Args,
743 Sanitizers.Mask & CFIClasses)
744 << "-fvisibility=";
745 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000746}
747
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000748SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
749 bool DiagnoseErrors) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000750 assert((A->getOption().matches(options::OPT_fsanitize_EQ) ||
Alexey Samsonov88459522015-01-12 22:39:12 +0000751 A->getOption().matches(options::OPT_fno_sanitize_EQ) ||
752 A->getOption().matches(options::OPT_fsanitize_recover_EQ) ||
Peter Collingbourne9881b782015-06-18 23:59:22 +0000753 A->getOption().matches(options::OPT_fno_sanitize_recover_EQ) ||
754 A->getOption().matches(options::OPT_fsanitize_trap_EQ) ||
755 A->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) &&
Alexey Samsonov799f7932014-12-19 02:35:16 +0000756 "Invalid argument in parseArgValues!");
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000757 SanitizerMask Kinds = 0;
Alexey Samsonov83791e22015-03-03 22:15:32 +0000758 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
759 const char *Value = A->getValue(i);
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000760 SanitizerMask Kind;
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000761 // Special case: don't accept -fsanitize=all.
762 if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
763 0 == strcmp("all", Value))
764 Kind = 0;
Derek Bruening256c2e12016-04-21 21:32:04 +0000765 // Similarly, don't accept -fsanitize=efficiency-all.
766 else if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
767 0 == strcmp("efficiency-all", Value))
768 Kind = 0;
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000769 else
Peter Collingbournebf59c342015-05-11 21:39:20 +0000770 Kind = parseSanitizerValue(Value, /*AllowGroups=*/true);
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000771
772 if (Kind)
773 Kinds |= Kind;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000774 else if (DiagnoseErrors)
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000775 D.Diag(clang::diag::err_drv_unsupported_option_argument)
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000776 << A->getOption().getName() << Value;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000777 }
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000778 return Kinds;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000779}
780
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000781int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A) {
782 assert(A->getOption().matches(options::OPT_fsanitize_coverage) ||
783 A->getOption().matches(options::OPT_fno_sanitize_coverage));
784 int Features = 0;
785 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
786 const char *Value = A->getValue(i);
787 int F = llvm::StringSwitch<int>(Value)
788 .Case("func", CoverageFunc)
789 .Case("bb", CoverageBB)
790 .Case("edge", CoverageEdge)
791 .Case("indirect-calls", CoverageIndirCall)
792 .Case("trace-bb", CoverageTraceBB)
793 .Case("trace-cmp", CoverageTraceCmp)
Kostya Serebryany3b419712016-08-30 01:27:03 +0000794 .Case("trace-div", CoverageTraceDiv)
795 .Case("trace-gep", CoverageTraceGep)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000796 .Case("8bit-counters", Coverage8bitCounters)
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000797 .Case("trace-pc", CoverageTracePC)
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000798 .Case("trace-pc-guard", CoverageTracePCGuard)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000799 .Default(0);
800 if (F == 0)
801 D.Diag(clang::diag::err_drv_unsupported_option_argument)
802 << A->getOption().getName() << Value;
803 Features |= F;
804 }
805 return Features;
806}
807
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000808std::string lastArgumentForMask(const Driver &D, const llvm::opt::ArgList &Args,
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000809 SanitizerMask Mask) {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000810 for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(),
811 E = Args.rend();
812 I != E; ++I) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000813 const auto *Arg = *I;
814 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000815 SanitizerMask AddKinds =
816 expandSanitizerGroups(parseArgValues(D, Arg, false));
Alexey Samsonov799f7932014-12-19 02:35:16 +0000817 if (AddKinds & Mask)
818 return describeSanitizeArg(Arg, Mask);
819 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000820 SanitizerMask RemoveKinds =
821 expandSanitizerGroups(parseArgValues(D, Arg, false));
Alexey Samsonov799f7932014-12-19 02:35:16 +0000822 Mask &= ~RemoveKinds;
823 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000824 }
825 llvm_unreachable("arg list didn't provide expected value");
826}
827
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000828std::string describeSanitizeArg(const llvm::opt::Arg *A, SanitizerMask Mask) {
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000829 assert(A->getOption().matches(options::OPT_fsanitize_EQ)
830 && "Invalid argument in describeSanitizerArg!");
Alexey Samsonovcf055962013-08-08 10:11:02 +0000831
Peter Collingbourne32701642013-11-01 18:16:25 +0000832 std::string Sanitizers;
Alexey Samsonov83791e22015-03-03 22:15:32 +0000833 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000834 if (expandSanitizerGroups(
835 parseSanitizerValue(A->getValue(i), /*AllowGroups=*/true)) &
836 Mask) {
Peter Collingbourne32701642013-11-01 18:16:25 +0000837 if (!Sanitizers.empty())
838 Sanitizers += ",";
Alexey Samsonov83791e22015-03-03 22:15:32 +0000839 Sanitizers += A->getValue(i);
Peter Collingbourne32701642013-11-01 18:16:25 +0000840 }
841 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000842
Peter Collingbourne32701642013-11-01 18:16:25 +0000843 assert(!Sanitizers.empty() && "arg didn't provide expected value");
844 return "-fsanitize=" + Sanitizers;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000845}