blob: 2f12c6d4a5f22533d9a9b2b8d6b64192c785d7d6 [file] [log] [blame]
Alexey Samsonovcf055962013-08-08 10:11:02 +00001//===--- SanitizerArgs.cpp - Arguments for sanitizer tools ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Alexey Samsonov609213f92013-08-19 09:14:21 +00009#include "clang/Driver/SanitizerArgs.h"
David L. Jonesf561aba2017-03-08 01:02:16 +000010#include "ToolChains/CommonArgs.h"
Peter Collingbournebf59c342015-05-11 21:39:20 +000011#include "clang/Basic/Sanitizers.h"
Alexey Samsonovcf055962013-08-08 10:11:02 +000012#include "clang/Driver/Driver.h"
13#include "clang/Driver/DriverDiagnostic.h"
14#include "clang/Driver/Options.h"
15#include "clang/Driver/ToolChain.h"
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +000016#include "llvm/ADT/StringExtras.h"
Alexey Samsonovcf055962013-08-08 10:11:02 +000017#include "llvm/ADT/StringSwitch.h"
18#include "llvm/Support/FileSystem.h"
19#include "llvm/Support/Path.h"
Alexey Samsonovb7dd3292014-07-09 19:40:08 +000020#include "llvm/Support/SpecialCaseList.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000021#include <memory>
Alexey Samsonovcf055962013-08-08 10:11:02 +000022
Peter Collingbourne3eea6772015-05-11 21:39:14 +000023using namespace clang;
24using namespace clang::SanitizerKind;
Alexey Samsonovcf055962013-08-08 10:11:02 +000025using namespace clang::driver;
26using namespace llvm::opt;
27
Peter Collingbourne3eea6772015-05-11 21:39:14 +000028enum : SanitizerMask {
Vedant Kumar42c17ec2017-03-14 01:56:34 +000029 NeedsUbsanRt = Undefined | Integer | Nullability | CFI,
Alexey Samsonov9b873092015-06-25 23:14:32 +000030 NeedsUbsanCxxRt = Vptr | CFI,
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000031 NotAllowedWithTrap = Vptr,
Evgeniy Stepanov71554fe2015-10-21 21:28:49 +000032 RequiresPIE = DataFlow,
Kostya Serebryany2d88f3d2015-01-06 01:02:48 +000033 NeedsUnwindTables = Address | Thread | Memory | DataFlow,
Alexander Potapenkodc5b95b2017-06-08 16:24:21 +000034 SupportsCoverage = Address | KernelAddress | Memory | Leak | Undefined |
George Karpenkov3f984ec2017-06-29 19:58:20 +000035 Integer | Nullability | DataFlow | Fuzzer,
Vedant Kumar42c17ec2017-03-14 01:56:34 +000036 RecoverableByDefault = Undefined | Integer | Nullability,
Yury Gribov5bfeca12015-11-11 10:45:48 +000037 Unrecoverable = Unreachable | Return,
Peter Collingbournea4ccff32015-02-20 20:30:56 +000038 LegacyFsanitizeRecoverMask = Undefined | Integer,
Peter Collingbourne1a7488a2015-04-02 00:23:30 +000039 NeedsLTO = CFI,
Vedant Kumar42c17ec2017-03-14 01:56:34 +000040 TrappingSupported = (Undefined & ~Vptr) | UnsignedIntegerOverflow |
41 Nullability | LocalBounds | CFI,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +000042 TrappingDefault = CFI,
Peter Collingbourne3afb2662016-04-28 17:09:37 +000043 CFIClasses = CFIVCall | CFINVCall | CFIDerivedCast | CFIUnrelatedCast,
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000044};
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000045
46enum CoverageFeature {
47 CoverageFunc = 1 << 0,
48 CoverageBB = 1 << 1,
49 CoverageEdge = 1 << 2,
50 CoverageIndirCall = 1 << 3,
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000051 CoverageTraceBB = 1 << 4, // Deprecated.
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000052 CoverageTraceCmp = 1 << 5,
Kostya Serebryany3b419712016-08-30 01:27:03 +000053 CoverageTraceDiv = 1 << 6,
54 CoverageTraceGep = 1 << 7,
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000055 Coverage8bitCounters = 1 << 8, // Deprecated.
Kostya Serebryany3b419712016-08-30 01:27:03 +000056 CoverageTracePC = 1 << 9,
Kostya Serebryany60cdd612016-09-14 01:39:49 +000057 CoverageTracePCGuard = 1 << 10,
Kostya Serebryany50fb6182017-05-05 23:28:18 +000058 CoverageNoPrune = 1 << 11,
Kostya Serebryany61457762017-07-28 00:10:10 +000059 CoverageInline8bitCounters = 1 << 12,
60 CoveragePCTable = 1 << 13,
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000061};
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000062
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000063/// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
Peter Collingbourne3eea6772015-05-11 21:39:14 +000064/// invalid components. Returns a SanitizerMask.
65static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
66 bool DiagnoseErrors);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000067
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000068/// Parse -f(no-)?sanitize-coverage= flag values, diagnosing any invalid
69/// components. Returns OR of members of \c CoverageFeature enumeration.
70static int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A);
71
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000072/// Produce an argument string from ArgList \p Args, which shows how it
73/// provides some sanitizer kind from \p Mask. For example, the argument list
74/// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt
75/// would produce "-fsanitize=vptr".
76static std::string lastArgumentForMask(const Driver &D,
77 const llvm::opt::ArgList &Args,
Peter Collingbourne3eea6772015-05-11 21:39:14 +000078 SanitizerMask Mask);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000079
80/// Produce an argument string from argument \p A, which shows how it provides
81/// a value in \p Mask. For instance, the argument
82/// "-fsanitize=address,alignment" with mask \c NeedsUbsanRt would produce
83/// "-fsanitize=alignment".
Peter Collingbourne3eea6772015-05-11 21:39:14 +000084static std::string describeSanitizeArg(const llvm::opt::Arg *A,
85 SanitizerMask Mask);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000086
Alexey Samsonov1e715a62014-11-16 20:53:53 +000087/// Produce a string containing comma-separated names of sanitizers in \p
88/// Sanitizers set.
89static std::string toString(const clang::SanitizerSet &Sanitizers);
90
Peter Collingbourne3eea6772015-05-11 21:39:14 +000091static bool getDefaultBlacklist(const Driver &D, SanitizerMask Kinds,
Alexey Samsonovecf380e2015-03-20 18:45:06 +000092 std::string &BLPath) {
93 const char *BlacklistFile = nullptr;
Peter Collingbourne3eea6772015-05-11 21:39:14 +000094 if (Kinds & Address)
Alexey Samsonovecf380e2015-03-20 18:45:06 +000095 BlacklistFile = "asan_blacklist.txt";
Peter Collingbourne3eea6772015-05-11 21:39:14 +000096 else if (Kinds & Memory)
Alexey Samsonovecf380e2015-03-20 18:45:06 +000097 BlacklistFile = "msan_blacklist.txt";
Peter Collingbourne3eea6772015-05-11 21:39:14 +000098 else if (Kinds & Thread)
Alexey Samsonovecf380e2015-03-20 18:45:06 +000099 BlacklistFile = "tsan_blacklist.txt";
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000100 else if (Kinds & DataFlow)
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000101 BlacklistFile = "dfsan_abilist.txt";
Peter Collingbourne6fccf952015-07-15 12:15:56 +0000102 else if (Kinds & CFI)
103 BlacklistFile = "cfi_blacklist.txt";
Han Shen0d7ac5f2017-08-02 19:53:38 +0000104 else if (Kinds & Undefined)
105 BlacklistFile = "ubsan_blacklist.txt";
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000106
107 if (BlacklistFile) {
108 clang::SmallString<64> Path(D.ResourceDir);
109 llvm::sys::path::append(Path, BlacklistFile);
110 BLPath = Path.str();
111 return true;
112 }
113 return false;
114}
115
Peter Collingbourne9881b782015-06-18 23:59:22 +0000116/// Sets group bits for every group that has at least one representative already
117/// enabled in \p Kinds.
118static SanitizerMask setGroupBits(SanitizerMask Kinds) {
119#define SANITIZER(NAME, ID)
120#define SANITIZER_GROUP(NAME, ID, ALIAS) \
121 if (Kinds & SanitizerKind::ID) \
122 Kinds |= SanitizerKind::ID##Group;
123#include "clang/Basic/Sanitizers.def"
124 return Kinds;
125}
126
127static SanitizerMask parseSanitizeTrapArgs(const Driver &D,
128 const llvm::opt::ArgList &Args) {
129 SanitizerMask TrapRemove = 0; // During the loop below, the accumulated set of
130 // sanitizers disabled by the current sanitizer
131 // argument or any argument after it.
132 SanitizerMask TrappingKinds = 0;
133 SanitizerMask TrappingSupportedWithGroups = setGroupBits(TrappingSupported);
134
135 for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
136 I != E; ++I) {
137 const auto *Arg = *I;
138 if (Arg->getOption().matches(options::OPT_fsanitize_trap_EQ)) {
139 Arg->claim();
140 SanitizerMask Add = parseArgValues(D, Arg, true);
141 Add &= ~TrapRemove;
142 if (SanitizerMask InvalidValues = Add & ~TrappingSupportedWithGroups) {
143 SanitizerSet S;
144 S.Mask = InvalidValues;
145 D.Diag(diag::err_drv_unsupported_option_argument) << "-fsanitize-trap"
146 << toString(S);
147 }
148 TrappingKinds |= expandSanitizerGroups(Add) & ~TrapRemove;
149 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) {
150 Arg->claim();
151 TrapRemove |= expandSanitizerGroups(parseArgValues(D, Arg, true));
152 } else if (Arg->getOption().matches(
153 options::OPT_fsanitize_undefined_trap_on_error)) {
154 Arg->claim();
155 TrappingKinds |=
156 expandSanitizerGroups(UndefinedGroup & ~TrapRemove) & ~TrapRemove;
157 } else if (Arg->getOption().matches(
158 options::OPT_fno_sanitize_undefined_trap_on_error)) {
159 Arg->claim();
160 TrapRemove |= expandSanitizerGroups(UndefinedGroup);
161 }
162 }
163
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000164 // Apply default trapping behavior.
165 TrappingKinds |= TrappingDefault & ~TrapRemove;
166
Peter Collingbourne9881b782015-06-18 23:59:22 +0000167 return TrappingKinds;
168}
169
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000170bool SanitizerArgs::needsUbsanRt() const {
Evgeniy Stepanov5b49eb42016-06-14 21:33:40 +0000171 return ((Sanitizers.Mask & NeedsUbsanRt & ~TrapSanitizers.Mask) ||
172 CoverageFeatures) &&
173 !Sanitizers.has(Address) && !Sanitizers.has(Memory) &&
Petr Hosekb31582b2017-08-03 23:02:22 +0000174 !Sanitizers.has(Thread) && !Sanitizers.has(DataFlow) &&
Mike Aizatskyd1033f52016-12-08 22:25:01 +0000175 !Sanitizers.has(Leak) && !CfiCrossDso;
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000176}
177
178bool SanitizerArgs::needsCfiRt() const {
Evgeniy Stepanove3fb51c2015-12-16 00:38:42 +0000179 return !(Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso;
180}
181
182bool SanitizerArgs::needsCfiDiagRt() const {
183 return (Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso;
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000184}
185
Dmitry Vyukov43419a72014-11-21 12:19:01 +0000186bool SanitizerArgs::requiresPIE() const {
Evgeniy Stepanov71554fe2015-10-21 21:28:49 +0000187 return NeedPIE || (Sanitizers.Mask & RequiresPIE);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000188}
189
190bool SanitizerArgs::needsUnwindTables() const {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000191 return Sanitizers.Mask & NeedsUnwindTables;
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000192}
193
Peter Collingbourne32701642013-11-01 18:16:25 +0000194SanitizerArgs::SanitizerArgs(const ToolChain &TC,
195 const llvm::opt::ArgList &Args) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000196 SanitizerMask AllRemove = 0; // During the loop below, the accumulated set of
197 // sanitizers disabled by the current sanitizer
198 // argument or any argument after it.
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000199 SanitizerMask AllAddedKinds = 0; // Mask of all sanitizers ever enabled by
200 // -fsanitize= flags (directly or via group
201 // expansion), some of which may be disabled
202 // later. Used to carefully prune
203 // unused-argument diagnostics.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000204 SanitizerMask DiagnosedKinds = 0; // All Kinds we have diagnosed up to now.
205 // Used to deduplicate diagnostics.
206 SanitizerMask Kinds = 0;
Alexey Samsonov9b873092015-06-25 23:14:32 +0000207 const SanitizerMask Supported = setGroupBits(TC.getSupportedSanitizers());
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000208 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
209
Peter Collingbourne32701642013-11-01 18:16:25 +0000210 const Driver &D = TC.getDriver();
Peter Collingbourne9881b782015-06-18 23:59:22 +0000211 SanitizerMask TrappingKinds = parseSanitizeTrapArgs(D, Args);
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000212 SanitizerMask InvalidTrappingKinds = TrappingKinds & NotAllowedWithTrap;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000213
Vedant Kumar7aacb652017-06-23 23:15:24 +0000214 // The object size sanitizer should not be enabled at -O0.
215 Arg *OptLevel = Args.getLastArg(options::OPT_O_Group);
216 bool RemoveObjectSizeAtO0 =
217 !OptLevel || OptLevel->getOption().matches(options::OPT_O0);
218
Peter Collingbourne32701642013-11-01 18:16:25 +0000219 for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
220 I != E; ++I) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000221 const auto *Arg = *I;
222 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
223 Arg->claim();
Vedant Kumar7aacb652017-06-23 23:15:24 +0000224 SanitizerMask Add = parseArgValues(D, Arg, /*AllowGroups=*/true);
225
226 if (RemoveObjectSizeAtO0) {
227 AllRemove |= SanitizerKind::ObjectSize;
228
229 // The user explicitly enabled the object size sanitizer. Warn that
230 // that this does nothing at -O0.
231 if (Add & SanitizerKind::ObjectSize)
232 D.Diag(diag::warn_drv_object_size_disabled_O0)
233 << Arg->getAsString(Args);
234 }
235
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000236 AllAddedKinds |= expandSanitizerGroups(Add);
Peter Collingbourne32701642013-11-01 18:16:25 +0000237
Alexey Samsonov799f7932014-12-19 02:35:16 +0000238 // Avoid diagnosing any sanitizer which is disabled later.
239 Add &= ~AllRemove;
240 // At this point we have not expanded groups, so any unsupported
241 // sanitizers in Add are those which have been explicitly enabled.
242 // Diagnose them.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000243 if (SanitizerMask KindsToDiagnose =
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000244 Add & InvalidTrappingKinds & ~DiagnosedKinds) {
Peter Collingbourne9881b782015-06-18 23:59:22 +0000245 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
246 D.Diag(diag::err_drv_argument_not_allowed_with)
247 << Desc << "-fsanitize-trap=undefined";
248 DiagnosedKinds |= KindsToDiagnose;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000249 }
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000250 Add &= ~InvalidTrappingKinds;
251 if (SanitizerMask KindsToDiagnose = Add & ~Supported & ~DiagnosedKinds) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000252 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
253 D.Diag(diag::err_drv_unsupported_opt_for_target)
254 << Desc << TC.getTriple().str();
255 DiagnosedKinds |= KindsToDiagnose;
256 }
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000257 Add &= Supported;
Peter Collingbourne32701642013-11-01 18:16:25 +0000258
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000259 // Test for -fno-rtti + explicit -fsanitizer=vptr before expanding groups
260 // so we don't error out if -fno-rtti and -fsanitize=undefined were
261 // passed.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000262 if (Add & Vptr &&
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000263 (RTTIMode == ToolChain::RM_DisabledImplicitly ||
264 RTTIMode == ToolChain::RM_DisabledExplicitly)) {
265 if (RTTIMode == ToolChain::RM_DisabledImplicitly)
266 // Warn about not having rtti enabled if the vptr sanitizer is
267 // explicitly enabled
268 D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default);
269 else {
270 const llvm::opt::Arg *NoRTTIArg = TC.getRTTIArg();
271 assert(NoRTTIArg &&
272 "RTTI disabled explicitly but we have no argument!");
273 D.Diag(diag::err_drv_argument_not_allowed_with)
274 << "-fsanitize=vptr" << NoRTTIArg->getAsString(Args);
275 }
276
277 // Take out the Vptr sanitizer from the enabled sanitizers
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000278 AllRemove |= Vptr;
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000279 }
280
Peter Collingbournebf59c342015-05-11 21:39:20 +0000281 Add = expandSanitizerGroups(Add);
Alexey Samsonov799f7932014-12-19 02:35:16 +0000282 // Group expansion may have enabled a sanitizer which is disabled later.
283 Add &= ~AllRemove;
284 // Silently discard any unsupported sanitizers implicitly enabled through
285 // group expansion.
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000286 Add &= ~InvalidTrappingKinds;
287 Add &= Supported;
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000288
George Karpenkovf2fc5b02017-04-24 18:23:24 +0000289 // Enable coverage if the fuzzing flag is set.
290 if (Add & Fuzzer)
Kostya Serebryany7dbb1e12017-08-04 21:35:11 +0000291 CoverageFeatures |= CoverageTracePCGuard | CoverageIndirCall |
292 CoverageTraceCmp | CoveragePCTable;
George Karpenkovf2fc5b02017-04-24 18:23:24 +0000293
Alexey Samsonov799f7932014-12-19 02:35:16 +0000294 Kinds |= Add;
295 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
296 Arg->claim();
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000297 SanitizerMask Remove = parseArgValues(D, Arg, true);
Peter Collingbournebf59c342015-05-11 21:39:20 +0000298 AllRemove |= expandSanitizerGroups(Remove);
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000299 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000300 }
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000301
Ed Schoutenfc79d2c2016-03-29 21:13:53 +0000302 // Enable toolchain specific default sanitizers if not explicitly disabled.
303 Kinds |= TC.getDefaultSanitizers() & ~AllRemove;
304
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000305 // We disable the vptr sanitizer if it was enabled by group expansion but RTTI
306 // is disabled.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000307 if ((Kinds & Vptr) &&
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000308 (RTTIMode == ToolChain::RM_DisabledImplicitly ||
309 RTTIMode == ToolChain::RM_DisabledExplicitly)) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000310 Kinds &= ~Vptr;
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000311 }
312
Alexey Samsonov907880e2015-06-19 19:57:46 +0000313 // Check that LTO is enabled if we need it.
Teresa Johnson945bc502015-10-15 20:35:53 +0000314 if ((Kinds & NeedsLTO) && !D.isUsingLTO()) {
Alexey Samsonov907880e2015-06-19 19:57:46 +0000315 D.Diag(diag::err_drv_argument_only_allowed_with)
316 << lastArgumentForMask(D, Args, Kinds & NeedsLTO) << "-flto";
317 }
318
Alexey Samsonov9b873092015-06-25 23:14:32 +0000319 // Report error if there are non-trapping sanitizers that require
320 // c++abi-specific parts of UBSan runtime, and they are not provided by the
321 // toolchain. We don't have a good way to check the latter, so we just
322 // check if the toolchan supports vptr.
323 if (~Supported & Vptr) {
Peter Collingbourne4bdceaa2015-07-08 21:08:05 +0000324 SanitizerMask KindsToDiagnose = Kinds & ~TrappingKinds & NeedsUbsanCxxRt;
325 // The runtime library supports the Microsoft C++ ABI, but only well enough
326 // for CFI. FIXME: Remove this once we support vptr on Windows.
327 if (TC.getTriple().isOSWindows())
328 KindsToDiagnose &= ~CFI;
329 if (KindsToDiagnose) {
Alexey Samsonov9b873092015-06-25 23:14:32 +0000330 SanitizerSet S;
331 S.Mask = KindsToDiagnose;
332 D.Diag(diag::err_drv_unsupported_opt_for_target)
333 << ("-fno-sanitize-trap=" + toString(S)) << TC.getTriple().str();
334 Kinds &= ~KindsToDiagnose;
335 }
336 }
337
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000338 // Warn about incompatible groups of sanitizers.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000339 std::pair<SanitizerMask, SanitizerMask> IncompatibleGroups[] = {
340 std::make_pair(Address, Thread), std::make_pair(Address, Memory),
341 std::make_pair(Thread, Memory), std::make_pair(Leak, Thread),
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000342 std::make_pair(Leak, Memory), std::make_pair(KernelAddress, Address),
343 std::make_pair(KernelAddress, Leak),
344 std::make_pair(KernelAddress, Thread),
Derek Bruening256c2e12016-04-21 21:32:04 +0000345 std::make_pair(KernelAddress, Memory),
346 std::make_pair(Efficiency, Address),
347 std::make_pair(Efficiency, Leak),
348 std::make_pair(Efficiency, Thread),
349 std::make_pair(Efficiency, Memory),
350 std::make_pair(Efficiency, KernelAddress)};
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000351 for (auto G : IncompatibleGroups) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000352 SanitizerMask Group = G.first;
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000353 if (Kinds & Group) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000354 if (SanitizerMask Incompatible = Kinds & G.second) {
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000355 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
356 << lastArgumentForMask(D, Args, Group)
357 << lastArgumentForMask(D, Args, Incompatible);
358 Kinds &= ~Incompatible;
359 }
360 }
361 }
362 // FIXME: Currently -fsanitize=leak is silently ignored in the presence of
363 // -fsanitize=address. Perhaps it should print an error, or perhaps
364 // -f(-no)sanitize=leak should change whether leak detection is enabled by
365 // default in ASan?
366
Alexey Samsonov88459522015-01-12 22:39:12 +0000367 // Parse -f(no-)?sanitize-recover flags.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000368 SanitizerMask RecoverableKinds = RecoverableByDefault;
369 SanitizerMask DiagnosedUnrecoverableKinds = 0;
Alexey Samsonov88459522015-01-12 22:39:12 +0000370 for (const auto *Arg : Args) {
Alexey Samsonovce2e77c2015-03-11 23:34:25 +0000371 const char *DeprecatedReplacement = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +0000372 if (Arg->getOption().matches(options::OPT_fsanitize_recover)) {
Kostya Serebryanyceb1add2016-05-04 20:21:47 +0000373 DeprecatedReplacement =
374 "-fsanitize-recover=undefined,integer' or '-fsanitize-recover=all";
Peter Collingbournebf59c342015-05-11 21:39:20 +0000375 RecoverableKinds |= expandSanitizerGroups(LegacyFsanitizeRecoverMask);
Alexey Samsonov88459522015-01-12 22:39:12 +0000376 Arg->claim();
377 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover)) {
Kostya Serebryanyceb1add2016-05-04 20:21:47 +0000378 DeprecatedReplacement = "-fno-sanitize-recover=undefined,integer' or "
379 "'-fno-sanitize-recover=all";
Peter Collingbournebf59c342015-05-11 21:39:20 +0000380 RecoverableKinds &= ~expandSanitizerGroups(LegacyFsanitizeRecoverMask);
Alexey Samsonov88459522015-01-12 22:39:12 +0000381 Arg->claim();
382 } else if (Arg->getOption().matches(options::OPT_fsanitize_recover_EQ)) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000383 SanitizerMask Add = parseArgValues(D, Arg, true);
Alexey Samsonov88459522015-01-12 22:39:12 +0000384 // Report error if user explicitly tries to recover from unrecoverable
385 // sanitizer.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000386 if (SanitizerMask KindsToDiagnose =
Alexey Samsonov88459522015-01-12 22:39:12 +0000387 Add & Unrecoverable & ~DiagnosedUnrecoverableKinds) {
388 SanitizerSet SetToDiagnose;
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000389 SetToDiagnose.Mask |= KindsToDiagnose;
Alexey Samsonov88459522015-01-12 22:39:12 +0000390 D.Diag(diag::err_drv_unsupported_option_argument)
391 << Arg->getOption().getName() << toString(SetToDiagnose);
392 DiagnosedUnrecoverableKinds |= KindsToDiagnose;
393 }
Peter Collingbournebf59c342015-05-11 21:39:20 +0000394 RecoverableKinds |= expandSanitizerGroups(Add);
Alexey Samsonov88459522015-01-12 22:39:12 +0000395 Arg->claim();
396 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000397 RecoverableKinds &= ~expandSanitizerGroups(parseArgValues(D, Arg, true));
Alexey Samsonov88459522015-01-12 22:39:12 +0000398 Arg->claim();
399 }
Alexey Samsonovce2e77c2015-03-11 23:34:25 +0000400 if (DeprecatedReplacement) {
401 D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
402 << DeprecatedReplacement;
403 }
Alexey Samsonov88459522015-01-12 22:39:12 +0000404 }
405 RecoverableKinds &= Kinds;
406 RecoverableKinds &= ~Unrecoverable;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000407
Peter Collingbourne9881b782015-06-18 23:59:22 +0000408 TrappingKinds &= Kinds;
409
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000410 // Setup blacklist files.
411 // Add default blacklist from resource directory.
412 {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000413 std::string BLPath;
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000414 if (getDefaultBlacklist(D, Kinds, BLPath) && llvm::sys::fs::exists(BLPath))
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000415 BlacklistFiles.push_back(BLPath);
416 }
417 // Parse -f(no-)sanitize-blacklist options.
418 for (const auto *Arg : Args) {
419 if (Arg->getOption().matches(options::OPT_fsanitize_blacklist)) {
420 Arg->claim();
421 std::string BLPath = Arg->getValue();
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000422 if (llvm::sys::fs::exists(BLPath)) {
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000423 BlacklistFiles.push_back(BLPath);
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000424 ExtraDeps.push_back(BLPath);
425 } else
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000426 D.Diag(clang::diag::err_drv_no_such_file) << BLPath;
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000427
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000428 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_blacklist)) {
429 Arg->claim();
430 BlacklistFiles.clear();
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000431 ExtraDeps.clear();
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000432 }
433 }
434 // Validate blacklists format.
435 {
436 std::string BLError;
437 std::unique_ptr<llvm::SpecialCaseList> SCL(
438 llvm::SpecialCaseList::create(BlacklistFiles, BLError));
439 if (!SCL.get())
440 D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000441 }
442
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000443 // Parse -f[no-]sanitize-memory-track-origins[=level] options.
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000444 if (AllAddedKinds & Memory) {
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000445 if (Arg *A =
446 Args.getLastArg(options::OPT_fsanitize_memory_track_origins_EQ,
447 options::OPT_fsanitize_memory_track_origins,
448 options::OPT_fno_sanitize_memory_track_origins)) {
449 if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) {
Evgeniy Stepanov6e09bca2015-02-26 15:59:30 +0000450 MsanTrackOrigins = 2;
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000451 } else if (A->getOption().matches(
452 options::OPT_fno_sanitize_memory_track_origins)) {
453 MsanTrackOrigins = 0;
454 } else {
455 StringRef S = A->getValue();
456 if (S.getAsInteger(0, MsanTrackOrigins) || MsanTrackOrigins < 0 ||
457 MsanTrackOrigins > 2) {
Nico Weberf2a39a72015-04-13 20:03:03 +0000458 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000459 }
460 }
461 }
Evgeniy Stepanov71554fe2015-10-21 21:28:49 +0000462 MsanUseAfterDtor =
463 Args.hasArg(options::OPT_fsanitize_memory_use_after_dtor);
464 NeedPIE |= !(TC.getTriple().isOSLinux() &&
465 TC.getTriple().getArch() == llvm::Triple::x86_64);
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000466 }
467
Evgeniy Stepanov8a2bedb2016-11-11 23:17:36 +0000468 if (AllAddedKinds & Thread) {
469 TsanMemoryAccess = Args.hasFlag(options::OPT_fsanitize_thread_memory_access,
470 options::OPT_fno_sanitize_thread_memory_access,
471 TsanMemoryAccess);
472 TsanFuncEntryExit = Args.hasFlag(options::OPT_fsanitize_thread_func_entry_exit,
473 options::OPT_fno_sanitize_thread_func_entry_exit,
474 TsanFuncEntryExit);
475 TsanAtomics = Args.hasFlag(options::OPT_fsanitize_thread_atomics,
476 options::OPT_fno_sanitize_thread_atomics,
477 TsanAtomics);
478 }
479
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000480 if (AllAddedKinds & CFI) {
481 CfiCrossDso = Args.hasFlag(options::OPT_fsanitize_cfi_cross_dso,
482 options::OPT_fno_sanitize_cfi_cross_dso, false);
483 // Without PIE, external function address may resolve to a PLT record, which
484 // can not be verified by the target module.
485 NeedPIE |= CfiCrossDso;
486 }
487
Peter Collingbournedc134532016-01-16 00:31:22 +0000488 Stats = Args.hasFlag(options::OPT_fsanitize_stats,
489 options::OPT_fno_sanitize_stats, false);
490
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000491 // Parse -f(no-)?sanitize-coverage flags if coverage is supported by the
492 // enabled sanitizers.
Kostya Serebryany52e86492016-02-18 00:49:23 +0000493 for (const auto *Arg : Args) {
494 if (Arg->getOption().matches(options::OPT_fsanitize_coverage)) {
495 int LegacySanitizeCoverage;
496 if (Arg->getNumValues() == 1 &&
497 !StringRef(Arg->getValue(0))
Kostya Serebryany9d1ed132017-04-19 19:57:16 +0000498 .getAsInteger(0, LegacySanitizeCoverage)) {
499 CoverageFeatures = 0;
500 Arg->claim();
501 if (LegacySanitizeCoverage != 0) {
Nico Weber4152f522016-02-18 19:32:54 +0000502 D.Diag(diag::warn_drv_deprecated_arg)
Kostya Serebryany9d1ed132017-04-19 19:57:16 +0000503 << Arg->getAsString(Args) << "-fsanitize-coverage=trace-pc-guard";
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000504 }
Kostya Serebryany52e86492016-02-18 00:49:23 +0000505 continue;
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000506 }
Kostya Serebryany52e86492016-02-18 00:49:23 +0000507 CoverageFeatures |= parseCoverageFeatures(D, Arg);
Evgeniy Stepanov5b49eb42016-06-14 21:33:40 +0000508
509 // Disable coverage and not claim the flags if there is at least one
510 // non-supporting sanitizer.
Petr Hosekeb4127f2017-07-21 01:17:49 +0000511 if (!(AllAddedKinds & ~AllRemove & ~setGroupBits(SupportsCoverage))) {
Kostya Serebryany52e86492016-02-18 00:49:23 +0000512 Arg->claim();
Kostya Serebryanyf5b25f82016-04-18 21:30:17 +0000513 } else {
514 CoverageFeatures = 0;
Kostya Serebryany52e86492016-02-18 00:49:23 +0000515 }
516 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_coverage)) {
517 Arg->claim();
518 CoverageFeatures &= ~parseCoverageFeatures(D, Arg);
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000519 }
520 }
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000521 // Choose at most one coverage type: function, bb, or edge.
522 if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageBB))
523 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
524 << "-fsanitize-coverage=func"
525 << "-fsanitize-coverage=bb";
526 if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageEdge))
527 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
528 << "-fsanitize-coverage=func"
529 << "-fsanitize-coverage=edge";
530 if ((CoverageFeatures & CoverageBB) && (CoverageFeatures & CoverageEdge))
531 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
532 << "-fsanitize-coverage=bb"
533 << "-fsanitize-coverage=edge";
534 // Basic block tracing and 8-bit counters require some type of coverage
535 // enabled.
Kostya Serebryany1c0e9e92017-04-19 21:31:11 +0000536 if (CoverageFeatures & CoverageTraceBB)
537 D.Diag(clang::diag::warn_drv_deprecated_arg)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000538 << "-fsanitize-coverage=trace-bb"
Kostya Serebryany1c0e9e92017-04-19 21:31:11 +0000539 << "-fsanitize-coverage=trace-pc-guard";
540 if (CoverageFeatures & Coverage8bitCounters)
Kostya Serebryany1a02d8b2017-04-19 20:15:58 +0000541 D.Diag(clang::diag::warn_drv_deprecated_arg)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000542 << "-fsanitize-coverage=8bit-counters"
Kostya Serebryany1a02d8b2017-04-19 20:15:58 +0000543 << "-fsanitize-coverage=trace-pc-guard";
Kostya Serebryany8955efc2017-05-03 01:27:28 +0000544
545 int InsertionPointTypes = CoverageFunc | CoverageBB | CoverageEdge;
Kostya Serebryany9f338dc2017-08-08 20:20:40 +0000546 int InstrumentationTypes =
547 CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters;
Kostya Serebryany8955efc2017-05-03 01:27:28 +0000548 if ((CoverageFeatures & InsertionPointTypes) &&
Kostya Serebryany9f338dc2017-08-08 20:20:40 +0000549 !(CoverageFeatures & InstrumentationTypes)) {
Kostya Serebryany8955efc2017-05-03 01:27:28 +0000550 D.Diag(clang::diag::warn_drv_deprecated_arg)
551 << "-fsanitize-coverage=[func|bb|edge]"
552 << "-fsanitize-coverage=[func|bb|edge],[trace-pc-guard|trace-pc]";
553 }
554
Kostya Serebryany52e86492016-02-18 00:49:23 +0000555 // trace-pc w/o func/bb/edge implies edge.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000556 if ((CoverageFeatures &
557 (CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters)) &&
Kostya Serebryany8955efc2017-05-03 01:27:28 +0000558 !(CoverageFeatures & InsertionPointTypes))
Kostya Serebryany52e86492016-02-18 00:49:23 +0000559 CoverageFeatures |= CoverageEdge;
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000560
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000561 if (AllAddedKinds & Address) {
Alexey Samsonovbdfa6c22014-04-01 13:31:10 +0000562 AsanSharedRuntime =
Petr Hosekb31582b2017-08-03 23:02:22 +0000563 Args.hasArg(options::OPT_shared_libasan) ||
564 TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia();
565 NeedPIE |= TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia();
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000566 if (Arg *A =
567 Args.getLastArg(options::OPT_fsanitize_address_field_padding)) {
568 StringRef S = A->getValue();
569 // Legal values are 0 and 1, 2, but in future we may add more levels.
570 if (S.getAsInteger(0, AsanFieldPadding) || AsanFieldPadding < 0 ||
571 AsanFieldPadding > 2) {
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000572 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000573 }
574 }
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000575
576 if (Arg *WindowsDebugRTArg =
577 Args.getLastArg(options::OPT__SLASH_MTd, options::OPT__SLASH_MT,
578 options::OPT__SLASH_MDd, options::OPT__SLASH_MD,
579 options::OPT__SLASH_LDd, options::OPT__SLASH_LD)) {
580 switch (WindowsDebugRTArg->getOption().getID()) {
581 case options::OPT__SLASH_MTd:
582 case options::OPT__SLASH_MDd:
583 case options::OPT__SLASH_LDd:
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000584 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000585 << WindowsDebugRTArg->getAsString(Args)
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000586 << lastArgumentForMask(D, Args, Address);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000587 D.Diag(clang::diag::note_drv_address_sanitizer_debug_runtime);
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000588 }
589 }
Alexey Samsonov90490af2014-08-08 22:47:17 +0000590
Vedant Kumara9d8be62017-05-08 21:11:55 +0000591 AsanUseAfterScope = Args.hasFlag(
592 options::OPT_fsanitize_address_use_after_scope,
593 options::OPT_fno_sanitize_address_use_after_scope, AsanUseAfterScope);
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000594
595 // As a workaround for a bug in gold 2.26 and earlier, dead stripping of
596 // globals in ASan is disabled by default on ELF targets.
597 // See https://sourceware.org/bugzilla/show_bug.cgi?id=19002
598 AsanGlobalsDeadStripping =
Petr Hosekb31582b2017-08-03 23:02:22 +0000599 !TC.getTriple().isOSBinFormatELF() || TC.getTriple().isOSFuchsia() ||
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000600 Args.hasArg(options::OPT_fsanitize_address_globals_dead_stripping);
Vedant Kumara9d8be62017-05-08 21:11:55 +0000601 } else {
602 AsanUseAfterScope = false;
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000603 }
604
Alexey Samsonov90490af2014-08-08 22:47:17 +0000605 // Parse -link-cxx-sanitizer flag.
606 LinkCXXRuntimes =
607 Args.hasArg(options::OPT_fsanitize_link_cxx_runtime) || D.CCCIsCXX();
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000608
609 // Finally, initialize the set of available and recoverable sanitizers.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000610 Sanitizers.Mask |= Kinds;
611 RecoverableSanitizers.Mask |= RecoverableKinds;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000612 TrapSanitizers.Mask |= TrappingKinds;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000613}
614
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000615static std::string toString(const clang::SanitizerSet &Sanitizers) {
616 std::string Res;
617#define SANITIZER(NAME, ID) \
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000618 if (Sanitizers.has(ID)) { \
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000619 if (!Res.empty()) \
620 Res += ","; \
621 Res += NAME; \
622 }
623#include "clang/Basic/Sanitizers.def"
624 return Res;
625}
626
Peter Collingbournedc134532016-01-16 00:31:22 +0000627static void addIncludeLinkerOption(const ToolChain &TC,
628 const llvm::opt::ArgList &Args,
629 llvm::opt::ArgStringList &CmdArgs,
630 StringRef SymbolName) {
631 SmallString<64> LinkerOptionFlag;
632 LinkerOptionFlag = "--linker-option=/include:";
633 if (TC.getTriple().getArch() == llvm::Triple::x86) {
634 // Win32 mangles C function names with a '_' prefix.
635 LinkerOptionFlag += '_';
636 }
637 LinkerOptionFlag += SymbolName;
638 CmdArgs.push_back(Args.MakeArgString(LinkerOptionFlag));
639}
640
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000641void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args,
Peter Collingbourne581f4382015-07-02 01:48:12 +0000642 llvm::opt::ArgStringList &CmdArgs,
643 types::ID InputType) const {
Justin Lebar6efbc732016-09-15 23:44:13 +0000644 // NVPTX doesn't currently support sanitizers. Bailing out here means that
645 // e.g. -fsanitize=address applies only to host code, which is what we want
646 // for now.
647 if (TC.getTriple().isNVPTX())
648 return;
649
Kostya Serebryany52e86492016-02-18 00:49:23 +0000650 // Translate available CoverageFeatures to corresponding clang-cc1 flags.
651 // Do it even if Sanitizers.empty() since some forms of coverage don't require
652 // sanitizers.
653 std::pair<int, const char *> CoverageFlags[] = {
654 std::make_pair(CoverageFunc, "-fsanitize-coverage-type=1"),
655 std::make_pair(CoverageBB, "-fsanitize-coverage-type=2"),
656 std::make_pair(CoverageEdge, "-fsanitize-coverage-type=3"),
657 std::make_pair(CoverageIndirCall, "-fsanitize-coverage-indirect-calls"),
658 std::make_pair(CoverageTraceBB, "-fsanitize-coverage-trace-bb"),
659 std::make_pair(CoverageTraceCmp, "-fsanitize-coverage-trace-cmp"),
Kostya Serebryany3b419712016-08-30 01:27:03 +0000660 std::make_pair(CoverageTraceDiv, "-fsanitize-coverage-trace-div"),
661 std::make_pair(CoverageTraceGep, "-fsanitize-coverage-trace-gep"),
Kostya Serebryany52e86492016-02-18 00:49:23 +0000662 std::make_pair(Coverage8bitCounters, "-fsanitize-coverage-8bit-counters"),
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000663 std::make_pair(CoverageTracePC, "-fsanitize-coverage-trace-pc"),
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000664 std::make_pair(CoverageTracePCGuard, "-fsanitize-coverage-trace-pc-guard"),
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000665 std::make_pair(CoverageInline8bitCounters, "-fsanitize-coverage-inline-8bit-counters"),
Kostya Serebryany61457762017-07-28 00:10:10 +0000666 std::make_pair(CoveragePCTable, "-fsanitize-coverage-pc-table"),
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000667 std::make_pair(CoverageNoPrune, "-fsanitize-coverage-no-prune")};
Kostya Serebryany52e86492016-02-18 00:49:23 +0000668 for (auto F : CoverageFlags) {
669 if (CoverageFeatures & F.first)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000670 CmdArgs.push_back(F.second);
Kostya Serebryany52e86492016-02-18 00:49:23 +0000671 }
672
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000673 if (TC.getTriple().isOSWindows() && needsUbsanRt()) {
674 // Instruct the code generator to embed linker directives in the object file
675 // that cause the required runtime libraries to be linked.
676 CmdArgs.push_back(Args.MakeArgString(
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000677 "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000678 if (types::isCXX(InputType))
679 CmdArgs.push_back(Args.MakeArgString(
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000680 "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone_cxx")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000681 }
682 if (TC.getTriple().isOSWindows() && needsStatsRt()) {
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000683 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
684 TC.getCompilerRT(Args, "stats_client")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000685
686 // The main executable must export the stats runtime.
687 // FIXME: Only exporting from the main executable (e.g. based on whether the
688 // translation unit defines main()) would save a little space, but having
689 // multiple copies of the runtime shouldn't hurt.
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000690 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
691 TC.getCompilerRT(Args, "stats")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000692 addIncludeLinkerOption(TC, Args, CmdArgs, "__sanitizer_stats_register");
693 }
694
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000695 if (Sanitizers.empty())
Alexey Samsonovcf055962013-08-08 10:11:02 +0000696 return;
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000697 CmdArgs.push_back(Args.MakeArgString("-fsanitize=" + toString(Sanitizers)));
698
Alexey Samsonov88459522015-01-12 22:39:12 +0000699 if (!RecoverableSanitizers.empty())
700 CmdArgs.push_back(Args.MakeArgString("-fsanitize-recover=" +
701 toString(RecoverableSanitizers)));
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000702
Peter Collingbourne9881b782015-06-18 23:59:22 +0000703 if (!TrapSanitizers.empty())
704 CmdArgs.push_back(
705 Args.MakeArgString("-fsanitize-trap=" + toString(TrapSanitizers)));
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000706
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000707 for (const auto &BLPath : BlacklistFiles) {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000708 SmallString<64> BlacklistOpt("-fsanitize-blacklist=");
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000709 BlacklistOpt += BLPath;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000710 CmdArgs.push_back(Args.MakeArgString(BlacklistOpt));
711 }
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000712 for (const auto &Dep : ExtraDeps) {
713 SmallString<64> ExtraDepOpt("-fdepfile-entry=");
714 ExtraDepOpt += Dep;
715 CmdArgs.push_back(Args.MakeArgString(ExtraDepOpt));
716 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000717
718 if (MsanTrackOrigins)
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000719 CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins=" +
720 llvm::utostr(MsanTrackOrigins)));
Evgeniy Stepanov45be9e02015-07-10 20:07:16 +0000721
722 if (MsanUseAfterDtor)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000723 CmdArgs.push_back("-fsanitize-memory-use-after-dtor");
Evgeniy Stepanov45be9e02015-07-10 20:07:16 +0000724
Evgeniy Stepanov8a2bedb2016-11-11 23:17:36 +0000725 // FIXME: Pass these parameters as function attributes, not as -llvm flags.
726 if (!TsanMemoryAccess) {
727 CmdArgs.push_back("-mllvm");
728 CmdArgs.push_back("-tsan-instrument-memory-accesses=0");
729 CmdArgs.push_back("-mllvm");
730 CmdArgs.push_back("-tsan-instrument-memintrinsics=0");
731 }
732 if (!TsanFuncEntryExit) {
733 CmdArgs.push_back("-mllvm");
734 CmdArgs.push_back("-tsan-instrument-func-entry-exit=0");
735 }
736 if (!TsanAtomics) {
737 CmdArgs.push_back("-mllvm");
738 CmdArgs.push_back("-tsan-instrument-atomics=0");
739 }
740
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000741 if (CfiCrossDso)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000742 CmdArgs.push_back("-fsanitize-cfi-cross-dso");
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000743
Peter Collingbournedc134532016-01-16 00:31:22 +0000744 if (Stats)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000745 CmdArgs.push_back("-fsanitize-stats");
Peter Collingbournedc134532016-01-16 00:31:22 +0000746
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000747 if (AsanFieldPadding)
748 CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-field-padding=" +
749 llvm::utostr(AsanFieldPadding)));
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000750
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000751 if (AsanUseAfterScope)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000752 CmdArgs.push_back("-fsanitize-address-use-after-scope");
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000753
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000754 if (AsanGlobalsDeadStripping)
755 CmdArgs.push_back("-fsanitize-address-globals-dead-stripping");
756
Sergey Matveev2ba87782015-02-17 15:09:33 +0000757 // MSan: Workaround for PR16386.
758 // ASan: This is mainly to help LSan with cases such as
759 // https://code.google.com/p/address-sanitizer/issues/detail?id=373
760 // We can't make this conditional on -fsanitize=leak, as that flag shouldn't
761 // affect compilation.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000762 if (Sanitizers.has(Memory) || Sanitizers.has(Address))
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000763 CmdArgs.push_back("-fno-assume-sane-operator-new");
Peter Collingbourne581f4382015-07-02 01:48:12 +0000764
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000765 // Require -fvisibility= flag on non-Windows when compiling if vptr CFI is
766 // enabled.
767 if (Sanitizers.hasOneOf(CFIClasses) && !TC.getTriple().isOSWindows() &&
768 !Args.hasArg(options::OPT_fvisibility_EQ)) {
769 TC.getDriver().Diag(clang::diag::err_drv_argument_only_allowed_with)
770 << lastArgumentForMask(TC.getDriver(), Args,
771 Sanitizers.Mask & CFIClasses)
772 << "-fvisibility=";
773 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000774}
775
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000776SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
777 bool DiagnoseErrors) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000778 assert((A->getOption().matches(options::OPT_fsanitize_EQ) ||
Alexey Samsonov88459522015-01-12 22:39:12 +0000779 A->getOption().matches(options::OPT_fno_sanitize_EQ) ||
780 A->getOption().matches(options::OPT_fsanitize_recover_EQ) ||
Peter Collingbourne9881b782015-06-18 23:59:22 +0000781 A->getOption().matches(options::OPT_fno_sanitize_recover_EQ) ||
782 A->getOption().matches(options::OPT_fsanitize_trap_EQ) ||
783 A->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) &&
Alexey Samsonov799f7932014-12-19 02:35:16 +0000784 "Invalid argument in parseArgValues!");
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000785 SanitizerMask Kinds = 0;
Alexey Samsonov83791e22015-03-03 22:15:32 +0000786 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
787 const char *Value = A->getValue(i);
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000788 SanitizerMask Kind;
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000789 // Special case: don't accept -fsanitize=all.
790 if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
791 0 == strcmp("all", Value))
792 Kind = 0;
Derek Bruening256c2e12016-04-21 21:32:04 +0000793 // Similarly, don't accept -fsanitize=efficiency-all.
794 else if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
795 0 == strcmp("efficiency-all", Value))
796 Kind = 0;
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000797 else
Peter Collingbournebf59c342015-05-11 21:39:20 +0000798 Kind = parseSanitizerValue(Value, /*AllowGroups=*/true);
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000799
800 if (Kind)
801 Kinds |= Kind;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000802 else if (DiagnoseErrors)
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000803 D.Diag(clang::diag::err_drv_unsupported_option_argument)
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000804 << A->getOption().getName() << Value;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000805 }
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000806 return Kinds;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000807}
808
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000809int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A) {
810 assert(A->getOption().matches(options::OPT_fsanitize_coverage) ||
811 A->getOption().matches(options::OPT_fno_sanitize_coverage));
812 int Features = 0;
813 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
814 const char *Value = A->getValue(i);
815 int F = llvm::StringSwitch<int>(Value)
816 .Case("func", CoverageFunc)
817 .Case("bb", CoverageBB)
818 .Case("edge", CoverageEdge)
819 .Case("indirect-calls", CoverageIndirCall)
820 .Case("trace-bb", CoverageTraceBB)
821 .Case("trace-cmp", CoverageTraceCmp)
Kostya Serebryany3b419712016-08-30 01:27:03 +0000822 .Case("trace-div", CoverageTraceDiv)
823 .Case("trace-gep", CoverageTraceGep)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000824 .Case("8bit-counters", Coverage8bitCounters)
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000825 .Case("trace-pc", CoverageTracePC)
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000826 .Case("trace-pc-guard", CoverageTracePCGuard)
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000827 .Case("no-prune", CoverageNoPrune)
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000828 .Case("inline-8bit-counters", CoverageInline8bitCounters)
Kostya Serebryany61457762017-07-28 00:10:10 +0000829 .Case("pc-table", CoveragePCTable)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000830 .Default(0);
831 if (F == 0)
832 D.Diag(clang::diag::err_drv_unsupported_option_argument)
833 << A->getOption().getName() << Value;
834 Features |= F;
835 }
836 return Features;
837}
838
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000839std::string lastArgumentForMask(const Driver &D, const llvm::opt::ArgList &Args,
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000840 SanitizerMask Mask) {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000841 for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(),
842 E = Args.rend();
843 I != E; ++I) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000844 const auto *Arg = *I;
845 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000846 SanitizerMask AddKinds =
847 expandSanitizerGroups(parseArgValues(D, Arg, false));
Alexey Samsonov799f7932014-12-19 02:35:16 +0000848 if (AddKinds & Mask)
849 return describeSanitizeArg(Arg, Mask);
850 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000851 SanitizerMask RemoveKinds =
852 expandSanitizerGroups(parseArgValues(D, Arg, false));
Alexey Samsonov799f7932014-12-19 02:35:16 +0000853 Mask &= ~RemoveKinds;
854 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000855 }
856 llvm_unreachable("arg list didn't provide expected value");
857}
858
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000859std::string describeSanitizeArg(const llvm::opt::Arg *A, SanitizerMask Mask) {
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000860 assert(A->getOption().matches(options::OPT_fsanitize_EQ)
861 && "Invalid argument in describeSanitizerArg!");
Alexey Samsonovcf055962013-08-08 10:11:02 +0000862
Peter Collingbourne32701642013-11-01 18:16:25 +0000863 std::string Sanitizers;
Alexey Samsonov83791e22015-03-03 22:15:32 +0000864 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000865 if (expandSanitizerGroups(
866 parseSanitizerValue(A->getValue(i), /*AllowGroups=*/true)) &
867 Mask) {
Peter Collingbourne32701642013-11-01 18:16:25 +0000868 if (!Sanitizers.empty())
869 Sanitizers += ",";
Alexey Samsonov83791e22015-03-03 22:15:32 +0000870 Sanitizers += A->getValue(i);
Peter Collingbourne32701642013-11-01 18:16:25 +0000871 }
872 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000873
Peter Collingbourne32701642013-11-01 18:16:25 +0000874 assert(!Sanitizers.empty() && "arg didn't provide expected value");
875 return "-fsanitize=" + Sanitizers;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000876}