clang 10.0.0git

SanitizerArgs.cpp
Go to the documentation of this file.
1 //===--- SanitizerArgs.cpp - Arguments for sanitizer tools ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 #include "clang/Driver/SanitizerArgs.h"
9 #include "ToolChains/CommonArgs.h"
10 #include "clang/Basic/Sanitizers.h"
11 #include "clang/Driver/Driver.h"
12 #include "clang/Driver/DriverDiagnostic.h"
13 #include "clang/Driver/Options.h"
14 #include "clang/Driver/ToolChain.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/Support/FileSystem.h"
18 #include "llvm/Support/Path.h"
19 #include "llvm/Support/SpecialCaseList.h"
20 #include "llvm/Support/TargetParser.h"
21 #include <memory>
22
23 using namespace clang;
24 using namespace clang::driver;
25 using namespace llvm::opt;
26
27 static const SanitizerMask NeedsUbsanRt =
28 SanitizerKind::Undefined | SanitizerKind::Integer |
29 SanitizerKind::ImplicitConversion | SanitizerKind::Nullability |
30 SanitizerKind::CFI | SanitizerKind::FloatDivideByZero;
31 static const SanitizerMask NeedsUbsanCxxRt =
32 SanitizerKind::Vptr | SanitizerKind::CFI;
33 static const SanitizerMask NotAllowedWithTrap = SanitizerKind::Vptr;
34 static const SanitizerMask NotAllowedWithMinimalRuntime =
35 SanitizerKind::Function | SanitizerKind::Vptr;
36 static const SanitizerMask RequiresPIE =
37 SanitizerKind::DataFlow | SanitizerKind::HWAddress | SanitizerKind::Scudo;
38 static const SanitizerMask NeedsUnwindTables =
39 SanitizerKind::Address | SanitizerKind::HWAddress | SanitizerKind::Thread |
40 SanitizerKind::Memory | SanitizerKind::DataFlow;
41 static const SanitizerMask SupportsCoverage =
42 SanitizerKind::Address | SanitizerKind::HWAddress |
43 SanitizerKind::KernelAddress | SanitizerKind::KernelHWAddress |
44 SanitizerKind::MemTag | SanitizerKind::Memory |
45 SanitizerKind::KernelMemory | SanitizerKind::Leak |
46 SanitizerKind::Undefined | SanitizerKind::Integer |
47 SanitizerKind::ImplicitConversion | SanitizerKind::Nullability |
48 SanitizerKind::DataFlow | SanitizerKind::Fuzzer |
49 SanitizerKind::FuzzerNoLink | SanitizerKind::FloatDivideByZero |
50 SanitizerKind::SafeStack | SanitizerKind::ShadowCallStack;
51 static const SanitizerMask RecoverableByDefault =
52 SanitizerKind::Undefined | SanitizerKind::Integer |
53 SanitizerKind::ImplicitConversion | SanitizerKind::Nullability |
54 SanitizerKind::FloatDivideByZero;
55 static const SanitizerMask Unrecoverable =
56 SanitizerKind::Unreachable | SanitizerKind::Return;
57 static const SanitizerMask AlwaysRecoverable =
58 SanitizerKind::KernelAddress | SanitizerKind::KernelHWAddress;
59 static const SanitizerMask LegacyFsanitizeRecoverMask =
60 SanitizerKind::Undefined | SanitizerKind::Integer;
61 static const SanitizerMask NeedsLTO = SanitizerKind::CFI;
62 static const SanitizerMask TrappingSupported =
63 (SanitizerKind::Undefined & ~SanitizerKind::Vptr) |
64 SanitizerKind::UnsignedIntegerOverflow | SanitizerKind::ImplicitConversion |
65 SanitizerKind::Nullability | SanitizerKind::LocalBounds |
66 SanitizerKind::CFI | SanitizerKind::FloatDivideByZero;
67 static const SanitizerMask TrappingDefault = SanitizerKind::CFI;
68 static const SanitizerMask CFIClasses =
69 SanitizerKind::CFIVCall | SanitizerKind::CFINVCall |
70 SanitizerKind::CFIMFCall | SanitizerKind::CFIDerivedCast |
71 SanitizerKind::CFIUnrelatedCast;
72 static const SanitizerMask CompatibleWithMinimalRuntime =
73 TrappingSupported | SanitizerKind::Scudo | SanitizerKind::ShadowCallStack;
74
75 enum CoverageFeature {
76 CoverageFunc = 1 << 0,
77 CoverageBB = 1 << 1,
78 CoverageEdge = 1 << 2,
79 CoverageIndirCall = 1 << 3,
80 CoverageTraceBB = 1 << 4, // Deprecated.
81 CoverageTraceCmp = 1 << 5,
82 CoverageTraceDiv = 1 << 6,
83 CoverageTraceGep = 1 << 7,
84 Coverage8bitCounters = 1 << 8, // Deprecated.
85 CoverageTracePC = 1 << 9,
86 CoverageTracePCGuard = 1 << 10,
87 CoverageNoPrune = 1 << 11,
88 CoverageInline8bitCounters = 1 << 12,
89 CoveragePCTable = 1 << 13,
90 CoverageStackDepth = 1 << 14,
91 };
92
93 /// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
94 /// invalid components. Returns a SanitizerMask.
95 static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
96 bool DiagnoseErrors);
97
98 /// Parse -f(no-)?sanitize-coverage= flag values, diagnosing any invalid
99 /// components. Returns OR of members of \c CoverageFeature enumeration.
100 static int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A);
101
102 /// Produce an argument string from ArgList \p Args, which shows how it
103 /// provides some sanitizer kind from \p Mask. For example, the argument list
104 /// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt
105 /// would produce "-fsanitize=vptr".
106 static std::string lastArgumentForMask(const Driver &D,
107 const llvm::opt::ArgList &Args,
108 SanitizerMask Mask);
109
110 /// Produce an argument string from argument \p A, which shows how it provides
111 /// a value in \p Mask. For instance, the argument
112 /// "-fsanitize=address,alignment" with mask \c NeedsUbsanRt would produce
113 /// "-fsanitize=alignment".
114 static std::string describeSanitizeArg(const llvm::opt::Arg *A,
115 SanitizerMask Mask);
116
117 /// Produce a string containing comma-separated names of sanitizers in \p
118 /// Sanitizers set.
119 static std::string toString(const clang::SanitizerSet &Sanitizers);
120
121 static void addDefaultBlacklists(const Driver &D, SanitizerMask Kinds,
122 std::vector<std::string> &BlacklistFiles) {
123 struct Blacklist {
124 const char *File;
125 SanitizerMask Mask;
126 } Blacklists[] = {{"asan_blacklist.txt", SanitizerKind::Address},
127 {"hwasan_blacklist.txt", SanitizerKind::HWAddress},
128 {"memtag_blacklist.txt", SanitizerKind::MemTag},
129 {"msan_blacklist.txt", SanitizerKind::Memory},
130 {"tsan_blacklist.txt", SanitizerKind::Thread},
131 {"dfsan_abilist.txt", SanitizerKind::DataFlow},
132 {"cfi_blacklist.txt", SanitizerKind::CFI},
133 {"ubsan_blacklist.txt",
134 SanitizerKind::Undefined | SanitizerKind::Integer |
135 SanitizerKind::Nullability |
136 SanitizerKind::FloatDivideByZero}};
137
138 for (auto BL : Blacklists) {
139 if (!(Kinds & BL.Mask))
140 continue;
141
142 clang::SmallString<64> Path(D.ResourceDir);
143 llvm::sys::path::append(Path, "share", BL.File);
144 if (D.getVFS().exists(Path))
145 BlacklistFiles.push_back(Path.str());
146 else if (BL.Mask == SanitizerKind::CFI)
147 // If cfi_blacklist.txt cannot be found in the resource dir, driver
148 // should fail.
149 D.Diag(clang::diag::err_drv_no_such_file) << Path;
150 }
151 }
152
153 /// Sets group bits for every group that has at least one representative already
154 /// enabled in \p Kinds.
155 static SanitizerMask setGroupBits(SanitizerMask Kinds) {
156 #define SANITIZER(NAME, ID)
157 #define SANITIZER_GROUP(NAME, ID, ALIAS) \
158 if (Kinds & SanitizerKind::ID) \
159 Kinds |= SanitizerKind::ID##Group;
160 #include "clang/Basic/Sanitizers.def"
161 return Kinds;
162 }
163
164 static SanitizerMask parseSanitizeTrapArgs(const Driver &D,
165 const llvm::opt::ArgList &Args) {
166 SanitizerMask TrapRemove; // During the loop below, the accumulated set of
167 // sanitizers disabled by the current sanitizer
168 // argument or any argument after it.
169 SanitizerMask TrappingKinds;
170 SanitizerMask TrappingSupportedWithGroups = setGroupBits(TrappingSupported);
171
172 for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
173 I != E; ++I) {
174 const auto *Arg = *I;
175 if (Arg->getOption().matches(options::OPT_fsanitize_trap_EQ)) {
176 Arg->claim();
177 SanitizerMask Add = parseArgValues(D, Arg, true);
178 Add &= ~TrapRemove;
179 if (SanitizerMask InvalidValues = Add & ~TrappingSupportedWithGroups) {
180 SanitizerSet S;
181 S.Mask = InvalidValues;
182 D.Diag(diag::err_drv_unsupported_option_argument) << "-fsanitize-trap"
183 << toString(S);
184 }
185 TrappingKinds |= expandSanitizerGroups(Add) & ~TrapRemove;
186 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) {
187 Arg->claim();
188 TrapRemove |= expandSanitizerGroups(parseArgValues(D, Arg, true));
189 } else if (Arg->getOption().matches(
190 options::OPT_fsanitize_undefined_trap_on_error)) {
191 Arg->claim();
192 TrappingKinds |=
193 expandSanitizerGroups(SanitizerKind::UndefinedGroup & ~TrapRemove) &
194 ~TrapRemove;
195 } else if (Arg->getOption().matches(
196 options::OPT_fno_sanitize_undefined_trap_on_error)) {
197 Arg->claim();
198 TrapRemove |= expandSanitizerGroups(SanitizerKind::UndefinedGroup);
199 }
200 }
201
202 // Apply default trapping behavior.
203 TrappingKinds |= TrappingDefault & ~TrapRemove;
204
205 return TrappingKinds;
206 }
207
208 bool SanitizerArgs::needsUbsanRt() const {
209 // All of these include ubsan.
210 if (needsAsanRt() || needsMsanRt() || needsHwasanRt() || needsTsanRt() ||
211 needsDfsanRt() || needsLsanRt() || needsCfiDiagRt() ||
212 (needsScudoRt() && !requiresMinimalRuntime()))
213 return false;
214
215 return (Sanitizers.Mask & NeedsUbsanRt & ~TrapSanitizers.Mask) ||
216 CoverageFeatures;
217 }
218
219 bool SanitizerArgs::needsCfiRt() const {
220 return !(Sanitizers.Mask & SanitizerKind::CFI & ~TrapSanitizers.Mask) &&
221 CfiCrossDso && !ImplicitCfiRuntime;
222 }
223
224 bool SanitizerArgs::needsCfiDiagRt() const {
225 return (Sanitizers.Mask & SanitizerKind::CFI & ~TrapSanitizers.Mask) &&
226 CfiCrossDso && !ImplicitCfiRuntime;
227 }
228
229 bool SanitizerArgs::requiresPIE() const {
230 return NeedPIE || (Sanitizers.Mask & RequiresPIE);
231 }
232
233 bool SanitizerArgs::needsUnwindTables() const {
234 return static_cast<bool>(Sanitizers.Mask & NeedsUnwindTables);
235 }
236
237 bool SanitizerArgs::needsLTO() const {
238 return static_cast<bool>(Sanitizers.Mask & NeedsLTO);
239 }
240
241 SanitizerArgs::SanitizerArgs(const ToolChain &TC,
242 const llvm::opt::ArgList &Args) {
243 SanitizerMask AllRemove; // During the loop below, the accumulated set of
244 // sanitizers disabled by the current sanitizer
245 // argument or any argument after it.
246 SanitizerMask AllAddedKinds; // Mask of all sanitizers ever enabled by
247 // -fsanitize= flags (directly or via group
248 // expansion), some of which may be disabled
249 // later. Used to carefully prune
250 // unused-argument diagnostics.
251 SanitizerMask DiagnosedKinds; // All Kinds we have diagnosed up to now.
252 // Used to deduplicate diagnostics.
253 SanitizerMask Kinds;
254 const SanitizerMask Supported = setGroupBits(TC.getSupportedSanitizers());
255
256 CfiCrossDso = Args.hasFlag(options::OPT_fsanitize_cfi_cross_dso,
257 options::OPT_fno_sanitize_cfi_cross_dso, false);
258
259 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
260
261 const Driver &D = TC.getDriver();
262 SanitizerMask TrappingKinds = parseSanitizeTrapArgs(D, Args);
263 SanitizerMask InvalidTrappingKinds = TrappingKinds & NotAllowedWithTrap;
264
265 MinimalRuntime =
266 Args.hasFlag(options::OPT_fsanitize_minimal_runtime,
267 options::OPT_fno_sanitize_minimal_runtime, MinimalRuntime);
268
269 // The object size sanitizer should not be enabled at -O0.
270 Arg *OptLevel = Args.getLastArg(options::OPT_O_Group);
271 bool RemoveObjectSizeAtO0 =
272 !OptLevel || OptLevel->getOption().matches(options::OPT_O0);
273
274 for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
275 I != E; ++I) {
276 const auto *Arg = *I;
277 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
278 Arg->claim();
279 SanitizerMask Add = parseArgValues(D, Arg, /*AllowGroups=*/true);
280
281 if (RemoveObjectSizeAtO0) {
282 AllRemove |= SanitizerKind::ObjectSize;
283
284 // The user explicitly enabled the object size sanitizer. Warn
285 // that this does nothing at -O0.
286 if (Add & SanitizerKind::ObjectSize)
287 D.Diag(diag::warn_drv_object_size_disabled_O0)
288 << Arg->getAsString(Args);
289 }
290
291 AllAddedKinds |= expandSanitizerGroups(Add);
292
293 // Avoid diagnosing any sanitizer which is disabled later.
294 Add &= ~AllRemove;
295 // At this point we have not expanded groups, so any unsupported
296 // sanitizers in Add are those which have been explicitly enabled.
297 // Diagnose them.
298 if (SanitizerMask KindsToDiagnose =
299 Add & InvalidTrappingKinds & ~DiagnosedKinds) {
300 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
301 D.Diag(diag::err_drv_argument_not_allowed_with)
302 << Desc << "-fsanitize-trap=undefined";
303 DiagnosedKinds |= KindsToDiagnose;
304 }
305 Add &= ~InvalidTrappingKinds;
306
307 if (MinimalRuntime) {
308 if (SanitizerMask KindsToDiagnose =
309 Add & NotAllowedWithMinimalRuntime & ~DiagnosedKinds) {
310 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
311 D.Diag(diag::err_drv_argument_not_allowed_with)
312 << Desc << "-fsanitize-minimal-runtime";
313 DiagnosedKinds |= KindsToDiagnose;
314 }
315 Add &= ~NotAllowedWithMinimalRuntime;
316 }
317
318 // FIXME: Make CFI on member function calls compatible with cross-DSO CFI.
319 // There are currently two problems:
320 // - Virtual function call checks need to pass a pointer to the function
321 // address to llvm.type.test and a pointer to the address point to the
322 // diagnostic function. Currently we pass the same pointer to both
323 // places.
324 // - Non-virtual function call checks may need to check multiple type
325 // identifiers.
326 // Fixing both of those may require changes to the cross-DSO CFI
327 // interface.
328 if (CfiCrossDso && (Add & SanitizerKind::CFIMFCall & ~DiagnosedKinds)) {
329 D.Diag(diag::err_drv_argument_not_allowed_with)
330 << "-fsanitize=cfi-mfcall"
331 << "-fsanitize-cfi-cross-dso";
332 Add &= ~SanitizerKind::CFIMFCall;
333 DiagnosedKinds |= SanitizerKind::CFIMFCall;
334 }
335
336 if (SanitizerMask KindsToDiagnose = Add & ~Supported & ~DiagnosedKinds) {
337 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
338 D.Diag(diag::err_drv_unsupported_opt_for_target)
339 << Desc << TC.getTriple().str();
340 DiagnosedKinds |= KindsToDiagnose;
341 }
342 Add &= Supported;
343
344 // Test for -fno-rtti + explicit -fsanitizer=vptr before expanding groups
345 // so we don't error out if -fno-rtti and -fsanitize=undefined were
346 // passed.
347 if ((Add & SanitizerKind::Vptr) && (RTTIMode == ToolChain::RM_Disabled)) {
348 if (const llvm::opt::Arg *NoRTTIArg = TC.getRTTIArg()) {
349 assert(NoRTTIArg->getOption().matches(options::OPT_fno_rtti) &&
350 "RTTI disabled without -fno-rtti option?");
351 // The user explicitly passed -fno-rtti with -fsanitize=vptr, but
352 // the vptr sanitizer requires RTTI, so this is a user error.
353 D.Diag(diag::err_drv_argument_not_allowed_with)
354 << "-fsanitize=vptr" << NoRTTIArg->getAsString(Args);
355 } else {
356 // The vptr sanitizer requires RTTI, but RTTI is disabled (by
357 // default). Warn that the vptr sanitizer is being disabled.
358 D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default);
359 }
360
361 // Take out the Vptr sanitizer from the enabled sanitizers
362 AllRemove |= SanitizerKind::Vptr;
363 }
364
365 Add = expandSanitizerGroups(Add);
366 // Group expansion may have enabled a sanitizer which is disabled later.
367 Add &= ~AllRemove;
368 // Silently discard any unsupported sanitizers implicitly enabled through
369 // group expansion.
370 Add &= ~InvalidTrappingKinds;
371 if (MinimalRuntime) {
372 Add &= ~NotAllowedWithMinimalRuntime;
373 }
374 if (CfiCrossDso)
375 Add &= ~SanitizerKind::CFIMFCall;
376 Add &= Supported;
377
378 if (Add & SanitizerKind::Fuzzer)
379 Add |= SanitizerKind::FuzzerNoLink;
380
381 // Enable coverage if the fuzzing flag is set.
382 if (Add & SanitizerKind::FuzzerNoLink) {
383 CoverageFeatures |= CoverageInline8bitCounters | CoverageIndirCall |
384 CoverageTraceCmp | CoveragePCTable;
385 // Due to TLS differences, stack depth tracking is only enabled on Linux
386 if (TC.getTriple().isOSLinux())
387 CoverageFeatures |= CoverageStackDepth;
388 }
389
390 Kinds |= Add;
391 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
392 Arg->claim();
393 SanitizerMask Remove = parseArgValues(D, Arg, true);
394 AllRemove |= expandSanitizerGroups(Remove);
395 }
396 }
397
398 std::pair<SanitizerMask, SanitizerMask> IncompatibleGroups[] = {
399 std::make_pair(SanitizerKind::Address,
400 SanitizerKind::Thread | SanitizerKind::Memory),
401 std::make_pair(SanitizerKind::Thread, SanitizerKind::Memory),
402 std::make_pair(SanitizerKind::Leak,
403 SanitizerKind::Thread | SanitizerKind::Memory),
404 std::make_pair(SanitizerKind::KernelAddress,
405 SanitizerKind::Address | SanitizerKind::Leak |
406 SanitizerKind::Thread | SanitizerKind::Memory),
407 std::make_pair(SanitizerKind::HWAddress,
408 SanitizerKind::Address | SanitizerKind::Thread |
409 SanitizerKind::Memory | SanitizerKind::KernelAddress),
410 std::make_pair(SanitizerKind::Scudo,
411 SanitizerKind::Address | SanitizerKind::HWAddress |
412 SanitizerKind::Leak | SanitizerKind::Thread |
413 SanitizerKind::Memory | SanitizerKind::KernelAddress),
414 std::make_pair(SanitizerKind::SafeStack,
415 SanitizerKind::Address | SanitizerKind::HWAddress |
416 SanitizerKind::Leak | SanitizerKind::Thread |
417 SanitizerKind::Memory | SanitizerKind::KernelAddress),
418 std::make_pair(SanitizerKind::KernelHWAddress,
419 SanitizerKind::Address | SanitizerKind::HWAddress |
420 SanitizerKind::Leak | SanitizerKind::Thread |
421 SanitizerKind::Memory | SanitizerKind::KernelAddress |
422 SanitizerKind::SafeStack),
423 std::make_pair(SanitizerKind::KernelMemory,
424 SanitizerKind::Address | SanitizerKind::HWAddress |
425 SanitizerKind::Leak | SanitizerKind::Thread |
426 SanitizerKind::Memory | SanitizerKind::KernelAddress |
427 SanitizerKind::Scudo | SanitizerKind::SafeStack),
428 std::make_pair(SanitizerKind::MemTag,
429 SanitizerKind::Address | SanitizerKind::KernelAddress |
430 SanitizerKind::HWAddress |
431 SanitizerKind::KernelHWAddress)};
432 // Enable toolchain specific default sanitizers if not explicitly disabled.
433 SanitizerMask Default = TC.getDefaultSanitizers() & ~AllRemove;
434
435 // Disable default sanitizers that are incompatible with explicitly requested
436 // ones.
437 for (auto G : IncompatibleGroups) {
438 SanitizerMask Group = G.first;
439 if ((Default & Group) && (Kinds & G.second))
440 Default &= ~Group;
441 }
442
443 Kinds |= Default;
444
445 // We disable the vptr sanitizer if it was enabled by group expansion but RTTI
446 // is disabled.
447 if ((Kinds & SanitizerKind::Vptr) && (RTTIMode == ToolChain::RM_Disabled)) {
448 Kinds &= ~SanitizerKind::Vptr;
449 }
450
451 // Check that LTO is enabled if we need it.
452 if ((Kinds & NeedsLTO) && !D.isUsingLTO()) {
453 D.Diag(diag::err_drv_argument_only_allowed_with)
454 << lastArgumentForMask(D, Args, Kinds & NeedsLTO) << "-flto";
455 }
456
457 if ((Kinds & SanitizerKind::ShadowCallStack) &&
458 TC.getTriple().getArch() == llvm::Triple::aarch64 &&
459 !llvm::AArch64::isX18ReservedByDefault(TC.getTriple()) &&
460 !Args.hasArg(options::OPT_ffixed_x18)) {
461 D.Diag(diag::err_drv_argument_only_allowed_with)
462 << lastArgumentForMask(D, Args, Kinds & SanitizerKind::ShadowCallStack)
463 << "-ffixed-x18";
464 }
465
466 // Report error if there are non-trapping sanitizers that require
467 // c++abi-specific parts of UBSan runtime, and they are not provided by the
468 // toolchain. We don't have a good way to check the latter, so we just
469 // check if the toolchan supports vptr.
470 if (~Supported & SanitizerKind::Vptr) {
471 SanitizerMask KindsToDiagnose = Kinds & ~TrappingKinds & NeedsUbsanCxxRt;
472 // The runtime library supports the Microsoft C++ ABI, but only well enough
473 // for CFI. FIXME: Remove this once we support vptr on Windows.
474 if (TC.getTriple().isOSWindows())
475 KindsToDiagnose &= ~SanitizerKind::CFI;
476 if (KindsToDiagnose) {
477 SanitizerSet S;
478 S.Mask = KindsToDiagnose;
479 D.Diag(diag::err_drv_unsupported_opt_for_target)
480 << ("-fno-sanitize-trap=" + toString(S)) << TC.getTriple().str();
481 Kinds &= ~KindsToDiagnose;
482 }
483 }
484
485 // Warn about incompatible groups of sanitizers.
486 for (auto G : IncompatibleGroups) {
487 SanitizerMask Group = G.first;
488 if (Kinds & Group) {
489 if (SanitizerMask Incompatible = Kinds & G.second) {
490 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
491 << lastArgumentForMask(D, Args, Group)
492 << lastArgumentForMask(D, Args, Incompatible);
493 Kinds &= ~Incompatible;
494 }
495 }
496 }
497 // FIXME: Currently -fsanitize=leak is silently ignored in the presence of
498 // -fsanitize=address. Perhaps it should print an error, or perhaps
499 // -f(-no)sanitize=leak should change whether leak detection is enabled by
500 // default in ASan?
501
502 // Parse -f(no-)?sanitize-recover flags.
503 SanitizerMask RecoverableKinds = RecoverableByDefault | AlwaysRecoverable;
504 SanitizerMask DiagnosedUnrecoverableKinds;
505 SanitizerMask DiagnosedAlwaysRecoverableKinds;
506 for (const auto *Arg : Args) {
507 const char *DeprecatedReplacement = nullptr;
508 if (Arg->getOption().matches(options::OPT_fsanitize_recover)) {
509 DeprecatedReplacement =
510 "-fsanitize-recover=undefined,integer' or '-fsanitize-recover=all";
511 RecoverableKinds |= expandSanitizerGroups(LegacyFsanitizeRecoverMask);
512 Arg->claim();
513 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover)) {
514 DeprecatedReplacement = "-fno-sanitize-recover=undefined,integer' or "
515 "'-fno-sanitize-recover=all";
516 RecoverableKinds &= ~expandSanitizerGroups(LegacyFsanitizeRecoverMask);
517 Arg->claim();
518 } else if (Arg->getOption().matches(options::OPT_fsanitize_recover_EQ)) {
519 SanitizerMask Add = parseArgValues(D, Arg, true);
520 // Report error if user explicitly tries to recover from unrecoverable
521 // sanitizer.
522 if (SanitizerMask KindsToDiagnose =
523 Add & Unrecoverable & ~DiagnosedUnrecoverableKinds) {
524 SanitizerSet SetToDiagnose;
525 SetToDiagnose.Mask |= KindsToDiagnose;
526 D.Diag(diag::err_drv_unsupported_option_argument)
527 << Arg->getOption().getName() << toString(SetToDiagnose);
528 DiagnosedUnrecoverableKinds |= KindsToDiagnose;
529 }
530 RecoverableKinds |= expandSanitizerGroups(Add);
531 Arg->claim();
532 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) {
533 SanitizerMask Remove = parseArgValues(D, Arg, true);
534 // Report error if user explicitly tries to disable recovery from
535 // always recoverable sanitizer.
536 if (SanitizerMask KindsToDiagnose =
537 Remove & AlwaysRecoverable & ~DiagnosedAlwaysRecoverableKinds) {
538 SanitizerSet SetToDiagnose;
539 SetToDiagnose.Mask |= KindsToDiagnose;
540 D.Diag(diag::err_drv_unsupported_option_argument)
541 << Arg->getOption().getName() << toString(SetToDiagnose);
542 DiagnosedAlwaysRecoverableKinds |= KindsToDiagnose;
543 }
544 RecoverableKinds &= ~expandSanitizerGroups(Remove);
545 Arg->claim();
546 }
547 if (DeprecatedReplacement) {
548 D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
549 << DeprecatedReplacement;
550 }
551 }
552 RecoverableKinds &= Kinds;
553 RecoverableKinds &= ~Unrecoverable;
554
555 TrappingKinds &= Kinds;
556 RecoverableKinds &= ~TrappingKinds;
557
558 // Setup blacklist files.
559 // Add default blacklist from resource directory.
560 addDefaultBlacklists(D, Kinds, SystemBlacklistFiles);
561 // Parse -f(no-)sanitize-blacklist options.
562 for (const auto *Arg : Args) {
563 if (Arg->getOption().matches(options::OPT_fsanitize_blacklist)) {
564 Arg->claim();
565 std::string BLPath = Arg->getValue();
566 if (D.getVFS().exists(BLPath)) {
567 UserBlacklistFiles.push_back(BLPath);
568 } else {
569 D.Diag(clang::diag::err_drv_no_such_file) << BLPath;
570 }
571 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_blacklist)) {
572 Arg->claim();
573 UserBlacklistFiles.clear();
574 SystemBlacklistFiles.clear();
575 }
576 }
577 // Validate blacklists format.
578 {
579 std::string BLError;
580 std::unique_ptr<llvm::SpecialCaseList> SCL(
581 llvm::SpecialCaseList::create(UserBlacklistFiles, D.getVFS(), BLError));
582 if (!SCL.get())
583 D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError;
584 }
585 {
586 std::string BLError;
587 std::unique_ptr<llvm::SpecialCaseList> SCL(llvm::SpecialCaseList::create(
588 SystemBlacklistFiles, D.getVFS(), BLError));
589 if (!SCL.get())
590 D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError;
591 }
592
593 // Parse -f[no-]sanitize-memory-track-origins[=level] options.
594 if (AllAddedKinds & SanitizerKind::Memory) {
595 if (Arg *A =
596 Args.getLastArg(options::OPT_fsanitize_memory_track_origins_EQ,
597 options::OPT_fsanitize_memory_track_origins,
598 options::OPT_fno_sanitize_memory_track_origins)) {
599 if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) {
600 MsanTrackOrigins = 2;
601 } else if (A->getOption().matches(
602 options::OPT_fno_sanitize_memory_track_origins)) {
603 MsanTrackOrigins = 0;
604 } else {
605 StringRef S = A->getValue();
606 if (S.getAsInteger(0, MsanTrackOrigins) || MsanTrackOrigins < 0 ||
607 MsanTrackOrigins > 2) {
608 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
609 }
610 }
611 }
612 MsanUseAfterDtor =
613 Args.hasFlag(options::OPT_fsanitize_memory_use_after_dtor,
614 options::OPT_fno_sanitize_memory_use_after_dtor,
615 MsanUseAfterDtor);
616 NeedPIE |= !(TC.getTriple().isOSLinux() &&
617 TC.getTriple().getArch() == llvm::Triple::x86_64);
618 } else {
619 MsanUseAfterDtor = false;
620 }
621
622 if (AllAddedKinds & SanitizerKind::Thread) {
623 TsanMemoryAccess = Args.hasFlag(
624 options::OPT_fsanitize_thread_memory_access,
625 options::OPT_fno_sanitize_thread_memory_access, TsanMemoryAccess);
626 TsanFuncEntryExit = Args.hasFlag(
627 options::OPT_fsanitize_thread_func_entry_exit,
628 options::OPT_fno_sanitize_thread_func_entry_exit, TsanFuncEntryExit);
629 TsanAtomics =
630 Args.hasFlag(options::OPT_fsanitize_thread_atomics,
631 options::OPT_fno_sanitize_thread_atomics, TsanAtomics);
632 }
633
634 if (AllAddedKinds & SanitizerKind::CFI) {
635 // Without PIE, external function address may resolve to a PLT record, which
636 // can not be verified by the target module.
637 NeedPIE |= CfiCrossDso;
638 CfiICallGeneralizePointers =
639 Args.hasArg(options::OPT_fsanitize_cfi_icall_generalize_pointers);
640
641 if (CfiCrossDso && CfiICallGeneralizePointers)
642 D.Diag(diag::err_drv_argument_not_allowed_with)
643 << "-fsanitize-cfi-cross-dso"
644 << "-fsanitize-cfi-icall-generalize-pointers";
645
646 CfiCanonicalJumpTables =
647 Args.hasFlag(options::OPT_fsanitize_cfi_canonical_jump_tables,
648 options::OPT_fno_sanitize_cfi_canonical_jump_tables, true);
649 }
650
651 Stats = Args.hasFlag(options::OPT_fsanitize_stats,
652 options::OPT_fno_sanitize_stats, false);
653
654 if (MinimalRuntime) {
655 SanitizerMask IncompatibleMask =
656 Kinds & ~setGroupBits(CompatibleWithMinimalRuntime);
657 if (IncompatibleMask)
658 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
659 << "-fsanitize-minimal-runtime"
660 << lastArgumentForMask(D, Args, IncompatibleMask);
661
662 SanitizerMask NonTrappingCfi = Kinds & SanitizerKind::CFI & ~TrappingKinds;
663 if (NonTrappingCfi)
664 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
665 << "fsanitize-minimal-runtime"
666 << "fsanitize-trap=cfi";
667 }
668
669 // Parse -f(no-)?sanitize-coverage flags if coverage is supported by the
670 // enabled sanitizers.
671 for (const auto *Arg : Args) {
672 if (Arg->getOption().matches(options::OPT_fsanitize_coverage)) {
673 int LegacySanitizeCoverage;
674 if (Arg->getNumValues() == 1 &&
675 !StringRef(Arg->getValue(0))
676 .getAsInteger(0, LegacySanitizeCoverage)) {
677 CoverageFeatures = 0;
678 Arg->claim();
679 if (LegacySanitizeCoverage != 0) {
680 D.Diag(diag::warn_drv_deprecated_arg)
681 << Arg->getAsString(Args) << "-fsanitize-coverage=trace-pc-guard";
682 }
683 continue;
684 }
685 CoverageFeatures |= parseCoverageFeatures(D, Arg);
686
687 // Disable coverage and not claim the flags if there is at least one
688 // non-supporting sanitizer.
689 if (!(AllAddedKinds & ~AllRemove & ~setGroupBits(SupportsCoverage))) {
690 Arg->claim();
691 } else {
692 CoverageFeatures = 0;
693 }
694 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_coverage)) {
695 Arg->claim();
696 CoverageFeatures &= ~parseCoverageFeatures(D, Arg);
697 }
698 }
699 // Choose at most one coverage type: function, bb, or edge.
700 if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageBB))
701 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
702 << "-fsanitize-coverage=func"
703 << "-fsanitize-coverage=bb";
704 if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageEdge))
705 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
706 << "-fsanitize-coverage=func"
707 << "-fsanitize-coverage=edge";
708 if ((CoverageFeatures & CoverageBB) && (CoverageFeatures & CoverageEdge))
709 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
710 << "-fsanitize-coverage=bb"
711 << "-fsanitize-coverage=edge";
712 // Basic block tracing and 8-bit counters require some type of coverage
713 // enabled.
714 if (CoverageFeatures & CoverageTraceBB)
715 D.Diag(clang::diag::warn_drv_deprecated_arg)
716 << "-fsanitize-coverage=trace-bb"
717 << "-fsanitize-coverage=trace-pc-guard";
718 if (CoverageFeatures & Coverage8bitCounters)
719 D.Diag(clang::diag::warn_drv_deprecated_arg)
720 << "-fsanitize-coverage=8bit-counters"
721 << "-fsanitize-coverage=trace-pc-guard";
722
723 int InsertionPointTypes = CoverageFunc | CoverageBB | CoverageEdge;
724 int InstrumentationTypes =
725 CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters;
726 if ((CoverageFeatures & InsertionPointTypes) &&
727 !(CoverageFeatures & InstrumentationTypes)) {
728 D.Diag(clang::diag::warn_drv_deprecated_arg)
729 << "-fsanitize-coverage=[func|bb|edge]"
730 << "-fsanitize-coverage=[func|bb|edge],[trace-pc-guard|trace-pc]";
731 }
732
733 // trace-pc w/o func/bb/edge implies edge.
734 if (!(CoverageFeatures & InsertionPointTypes)) {
735 if (CoverageFeatures &
736 (CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters))
737 CoverageFeatures |= CoverageEdge;
738
739 if (CoverageFeatures & CoverageStackDepth)
740 CoverageFeatures |= CoverageFunc;
741 }
742
743 SharedRuntime =
744 Args.hasFlag(options::OPT_shared_libsan, options::OPT_static_libsan,
745 TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia() ||
746 TC.getTriple().isOSDarwin());
747
748 ImplicitCfiRuntime = TC.getTriple().isAndroid();
749
750 if (AllAddedKinds & SanitizerKind::Address) {
751 NeedPIE |= TC.getTriple().isOSFuchsia();
752 if (Arg *A =
753 Args.getLastArg(options::OPT_fsanitize_address_field_padding)) {
754 StringRef S = A->getValue();
755 // Legal values are 0 and 1, 2, but in future we may add more levels.
756 if (S.getAsInteger(0, AsanFieldPadding) || AsanFieldPadding < 0 ||
757 AsanFieldPadding > 2) {
758 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
759 }
760 }
761
762 if (Arg *WindowsDebugRTArg =
763 Args.getLastArg(options::OPT__SLASH_MTd, options::OPT__SLASH_MT,
764 options::OPT__SLASH_MDd, options::OPT__SLASH_MD,
765 options::OPT__SLASH_LDd, options::OPT__SLASH_LD)) {
766 switch (WindowsDebugRTArg->getOption().getID()) {
767 case options::OPT__SLASH_MTd:
768 case options::OPT__SLASH_MDd:
769 case options::OPT__SLASH_LDd:
770 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
771 << WindowsDebugRTArg->getAsString(Args)
772 << lastArgumentForMask(D, Args, SanitizerKind::Address);
773 D.Diag(clang::diag::note_drv_address_sanitizer_debug_runtime);
774 }
775 }
776
777 AsanUseAfterScope = Args.hasFlag(
778 options::OPT_fsanitize_address_use_after_scope,
779 options::OPT_fno_sanitize_address_use_after_scope, AsanUseAfterScope);
780
781 AsanPoisonCustomArrayCookie = Args.hasFlag(
782 options::OPT_fsanitize_address_poison_custom_array_cookie,
783 options::OPT_fno_sanitize_address_poison_custom_array_cookie,
784 AsanPoisonCustomArrayCookie);
785
786 // As a workaround for a bug in gold 2.26 and earlier, dead stripping of
787 // globals in ASan is disabled by default on ELF targets.
788 // See https://sourceware.org/bugzilla/show_bug.cgi?id=19002
789 AsanGlobalsDeadStripping =
790 !TC.getTriple().isOSBinFormatELF() || TC.getTriple().isOSFuchsia() ||
791 TC.getTriple().isPS4() ||
792 Args.hasArg(options::OPT_fsanitize_address_globals_dead_stripping);
793
794 AsanUseOdrIndicator =
795 Args.hasFlag(options::OPT_fsanitize_address_use_odr_indicator,
796 options::OPT_fno_sanitize_address_use_odr_indicator,
797 AsanUseOdrIndicator);
798
799 if (AllAddedKinds & SanitizerKind::PointerCompare & ~AllRemove) {
800 AsanInvalidPointerCmp = true;
801 }
802
803 if (AllAddedKinds & SanitizerKind::PointerSubtract & ~AllRemove) {
804 AsanInvalidPointerSub = true;
805 }
806
807 } else {
808 AsanUseAfterScope = false;
809 // -fsanitize=pointer-compare/pointer-subtract requires -fsanitize=address.
810 SanitizerMask DetectInvalidPointerPairs =
811 SanitizerKind::PointerCompare | SanitizerKind::PointerSubtract;
812 if (AllAddedKinds & DetectInvalidPointerPairs & ~AllRemove) {
813 TC.getDriver().Diag(clang::diag::err_drv_argument_only_allowed_with)
814 << lastArgumentForMask(D, Args,
815 SanitizerKind::PointerCompare |
816 SanitizerKind::PointerSubtract)
817 << "-fsanitize=address";
818 }
819 }
820
821 if (AllAddedKinds & SanitizerKind::HWAddress) {
822 if (Arg *HwasanAbiArg =
823 Args.getLastArg(options::OPT_fsanitize_hwaddress_abi_EQ)) {
824 HwasanAbi = HwasanAbiArg->getValue();
825 if (HwasanAbi != "platform" && HwasanAbi != "interceptor")
826 D.Diag(clang::diag::err_drv_invalid_value)
827 << HwasanAbiArg->getAsString(Args) << HwasanAbi;
828 } else {
829 HwasanAbi = "interceptor";
830 }
831 }
832
833 if (AllAddedKinds & SanitizerKind::SafeStack) {
834 // SafeStack runtime is built into the system on Fuchsia.
835 SafeStackRuntime = !TC.getTriple().isOSFuchsia();
836 }
837
838 LinkRuntimes =
839 Args.hasFlag(options::OPT_fsanitize_link_runtime,
840 options::OPT_fno_sanitize_link_runtime, LinkRuntimes);
841
842 // Parse -link-cxx-sanitizer flag.
843 LinkCXXRuntimes = Args.hasArg(options::OPT_fsanitize_link_cxx_runtime,
844 options::OPT_fno_sanitize_link_cxx_runtime,
845 LinkCXXRuntimes) ||
846 D.CCCIsCXX();
847
848 // Finally, initialize the set of available and recoverable sanitizers.
849 Sanitizers.Mask |= Kinds;
850 RecoverableSanitizers.Mask |= RecoverableKinds;
851 TrapSanitizers.Mask |= TrappingKinds;
852 assert(!(RecoverableKinds & TrappingKinds) &&
853 "Overlap between recoverable and trapping sanitizers");
854 }
855
856 static std::string toString(const clang::SanitizerSet &Sanitizers) {
857 std::string Res;
858 #define SANITIZER(NAME, ID) \
859 if (Sanitizers.has(SanitizerKind::ID)) { \
860 if (!Res.empty()) \
861 Res += ","; \
862 Res += NAME; \
863 }
864 #include "clang/Basic/Sanitizers.def"
865 return Res;
866 }
867
868 static void addIncludeLinkerOption(const ToolChain &TC,
869 const llvm::opt::ArgList &Args,
870 llvm::opt::ArgStringList &CmdArgs,
871 StringRef SymbolName) {
872 SmallString<64> LinkerOptionFlag;
873 LinkerOptionFlag = "--linker-option=/include:";
874 if (TC.getTriple().getArch() == llvm::Triple::x86) {
875 // Win32 mangles C function names with a '_' prefix.
876 LinkerOptionFlag += '_';
877 }
878 LinkerOptionFlag += SymbolName;
879 CmdArgs.push_back(Args.MakeArgString(LinkerOptionFlag));
880 }
881
882 static bool hasTargetFeatureMTE(const llvm::opt::ArgStringList &CmdArgs) {
883 for (auto Start = CmdArgs.begin(), End = CmdArgs.end(); Start != End; ++Start) {
884 auto It = std::find(Start, End, StringRef("+mte"));
885 if (It == End)
886 break;
887 if (It > Start && *std::prev(It) == StringRef("-target-feature"))
888 return true;
889 Start = It;
890 }
891 return false;
892 }
893
894 void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args,
895 llvm::opt::ArgStringList &CmdArgs,
896 types::ID InputType) const {
897 // NVPTX doesn't currently support sanitizers. Bailing out here means that
898 // e.g. -fsanitize=address applies only to host code, which is what we want
899 // for now.
900 if (TC.getTriple().isNVPTX())
901 return;
902
903 // Translate available CoverageFeatures to corresponding clang-cc1 flags.
904 // Do it even if Sanitizers.empty() since some forms of coverage don't require
905 // sanitizers.
906 std::pair<int, const char *> CoverageFlags[] = {
907 std::make_pair(CoverageFunc, "-fsanitize-coverage-type=1"),
908 std::make_pair(CoverageBB, "-fsanitize-coverage-type=2"),
909 std::make_pair(CoverageEdge, "-fsanitize-coverage-type=3"),
910 std::make_pair(CoverageIndirCall, "-fsanitize-coverage-indirect-calls"),
911 std::make_pair(CoverageTraceBB, "-fsanitize-coverage-trace-bb"),
912 std::make_pair(CoverageTraceCmp, "-fsanitize-coverage-trace-cmp"),
913 std::make_pair(CoverageTraceDiv, "-fsanitize-coverage-trace-div"),
914 std::make_pair(CoverageTraceGep, "-fsanitize-coverage-trace-gep"),
915 std::make_pair(Coverage8bitCounters, "-fsanitize-coverage-8bit-counters"),
916 std::make_pair(CoverageTracePC, "-fsanitize-coverage-trace-pc"),
917 std::make_pair(CoverageTracePCGuard, "-fsanitize-coverage-trace-pc-guard"),
918 std::make_pair(CoverageInline8bitCounters, "-fsanitize-coverage-inline-8bit-counters"),
919 std::make_pair(CoveragePCTable, "-fsanitize-coverage-pc-table"),
920 std::make_pair(CoverageNoPrune, "-fsanitize-coverage-no-prune"),
921 std::make_pair(CoverageStackDepth, "-fsanitize-coverage-stack-depth")};
922 for (auto F : CoverageFlags) {
923 if (CoverageFeatures & F.first)
924 CmdArgs.push_back(F.second);
925 }
926
927 if (TC.getTriple().isOSWindows() && needsUbsanRt()) {
928 // Instruct the code generator to embed linker directives in the object file
929 // that cause the required runtime libraries to be linked.
930 CmdArgs.push_back(Args.MakeArgString(
931 "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone")));
932 if (types::isCXX(InputType))
933 CmdArgs.push_back(Args.MakeArgString(
934 "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone_cxx")));
935 }
936 if (TC.getTriple().isOSWindows() && needsStatsRt()) {
937 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
938 TC.getCompilerRT(Args, "stats_client")));
939
940 // The main executable must export the stats runtime.
941 // FIXME: Only exporting from the main executable (e.g. based on whether the
942 // translation unit defines main()) would save a little space, but having
943 // multiple copies of the runtime shouldn't hurt.
944 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
945 TC.getCompilerRT(Args, "stats")));
946 addIncludeLinkerOption(TC, Args, CmdArgs, "__sanitizer_stats_register");
947 }
948
949 if (Sanitizers.empty())
950 return;
951 CmdArgs.push_back(Args.MakeArgString("-fsanitize=" + toString(Sanitizers)));
952
953 if (!RecoverableSanitizers.empty())
954 CmdArgs.push_back(Args.MakeArgString("-fsanitize-recover=" +
955 toString(RecoverableSanitizers)));
956
957 if (!TrapSanitizers.empty())
958 CmdArgs.push_back(
959 Args.MakeArgString("-fsanitize-trap=" + toString(TrapSanitizers)));
960
961 for (const auto &BLPath : UserBlacklistFiles) {
962 SmallString<64> BlacklistOpt("-fsanitize-blacklist=");
963 BlacklistOpt += BLPath;
964 CmdArgs.push_back(Args.MakeArgString(BlacklistOpt));
965 }
966 for (const auto &BLPath : SystemBlacklistFiles) {
967 SmallString<64> BlacklistOpt("-fsanitize-system-blacklist=");
968 BlacklistOpt += BLPath;
969 CmdArgs.push_back(Args.MakeArgString(BlacklistOpt));
970 }
971
972 if (MsanTrackOrigins)
973 CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins=" +
974 Twine(MsanTrackOrigins)));
975
976 if (MsanUseAfterDtor)
977 CmdArgs.push_back("-fsanitize-memory-use-after-dtor");
978
979 // FIXME: Pass these parameters as function attributes, not as -llvm flags.
980 if (!TsanMemoryAccess) {
981 CmdArgs.push_back("-mllvm");
982 CmdArgs.push_back("-tsan-instrument-memory-accesses=0");
983 CmdArgs.push_back("-mllvm");
984 CmdArgs.push_back("-tsan-instrument-memintrinsics=0");
985 }
986 if (!TsanFuncEntryExit) {
987 CmdArgs.push_back("-mllvm");
988 CmdArgs.push_back("-tsan-instrument-func-entry-exit=0");
989 }
990 if (!TsanAtomics) {
991 CmdArgs.push_back("-mllvm");
992 CmdArgs.push_back("-tsan-instrument-atomics=0");
993 }
994
995 if (CfiCrossDso)
996 CmdArgs.push_back("-fsanitize-cfi-cross-dso");
997
998 if (CfiICallGeneralizePointers)
999 CmdArgs.push_back("-fsanitize-cfi-icall-generalize-pointers");
1000
1001 if (CfiCanonicalJumpTables)
1002 CmdArgs.push_back("-fsanitize-cfi-canonical-jump-tables");
1003
1004 if (Stats)
1005 CmdArgs.push_back("-fsanitize-stats");
1006
1007 if (MinimalRuntime)
1008 CmdArgs.push_back("-fsanitize-minimal-runtime");
1009
1010 if (AsanFieldPadding)
1011 CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-field-padding=" +
1012 Twine(AsanFieldPadding)));
1013
1014 if (AsanUseAfterScope)
1015 CmdArgs.push_back("-fsanitize-address-use-after-scope");
1016
1017 if (AsanPoisonCustomArrayCookie)
1018 CmdArgs.push_back("-fsanitize-address-poison-custom-array-cookie");
1019
1020 if (AsanGlobalsDeadStripping)
1021 CmdArgs.push_back("-fsanitize-address-globals-dead-stripping");
1022
1023 if (AsanUseOdrIndicator)
1024 CmdArgs.push_back("-fsanitize-address-use-odr-indicator");
1025
1026 if (AsanInvalidPointerCmp) {
1027 CmdArgs.push_back("-mllvm");
1028 CmdArgs.push_back("-asan-detect-invalid-pointer-cmp");
1029 }
1030
1031 if (AsanInvalidPointerSub) {
1032 CmdArgs.push_back("-mllvm");
1033 CmdArgs.push_back("-asan-detect-invalid-pointer-sub");
1034 }
1035
1036 if (!HwasanAbi.empty()) {
1037 CmdArgs.push_back("-default-function-attr");
1038 CmdArgs.push_back(Args.MakeArgString("hwasan-abi=" + HwasanAbi));
1039 }
1040
1041 if (Sanitizers.has(SanitizerKind::HWAddress)) {
1042 CmdArgs.push_back("-target-feature");
1043 CmdArgs.push_back("+tagged-globals");
1044 }
1045
1046 // MSan: Workaround for PR16386.
1047 // ASan: This is mainly to help LSan with cases such as
1048 // https://github.com/google/sanitizers/issues/373
1049 // We can't make this conditional on -fsanitize=leak, as that flag shouldn't
1050 // affect compilation.
1051 if (Sanitizers.has(SanitizerKind::Memory) ||
1052 Sanitizers.has(SanitizerKind::Address))
1053 CmdArgs.push_back("-fno-assume-sane-operator-new");
1054
1055 // Require -fvisibility= flag on non-Windows when compiling if vptr CFI is
1056 // enabled.
1057 if (Sanitizers.hasOneOf(CFIClasses) && !TC.getTriple().isOSWindows() &&
1058 !Args.hasArg(options::OPT_fvisibility_EQ)) {
1059 TC.getDriver().Diag(clang::diag::err_drv_argument_only_allowed_with)
1060 << lastArgumentForMask(TC.getDriver(), Args,
1061 Sanitizers.Mask & CFIClasses)
1062 << "-fvisibility=";
1063 }
1064
1065 if (Sanitizers.has(SanitizerKind::MemTag) && !hasTargetFeatureMTE(CmdArgs))
1066 TC.getDriver().Diag(diag::err_stack_tagging_requires_hardware_feature);
1067 }
1068
1069 SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
1070 bool DiagnoseErrors) {
1071 assert((A->getOption().matches(options::OPT_fsanitize_EQ) ||
1072 A->getOption().matches(options::OPT_fno_sanitize_EQ) ||
1073 A->getOption().matches(options::OPT_fsanitize_recover_EQ) ||
1074 A->getOption().matches(options::OPT_fno_sanitize_recover_EQ) ||
1075 A->getOption().matches(options::OPT_fsanitize_trap_EQ) ||
1076 A->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) &&
1077 "Invalid argument in parseArgValues!");
1078 SanitizerMask Kinds;
1079 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
1080 const char *Value = A->getValue(i);
1081 SanitizerMask Kind;
1082 // Special case: don't accept -fsanitize=all.
1083 if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
1084 0 == strcmp("all", Value))
1085 Kind = SanitizerMask();
1086 else
1087 Kind = parseSanitizerValue(Value, /*AllowGroups=*/true);
1088
1089 if (Kind)
1090 Kinds |= Kind;
1091 else if (DiagnoseErrors)
1092 D.Diag(clang::diag::err_drv_unsupported_option_argument)
1093 << A->getOption().getName() << Value;
1094 }
1095 return Kinds;
1096 }
1097
1098 int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A) {
1099 assert(A->getOption().matches(options::OPT_fsanitize_coverage) ||
1100 A->getOption().matches(options::OPT_fno_sanitize_coverage));
1101 int Features = 0;
1102 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
1103 const char *Value = A->getValue(i);
1104 int F = llvm::StringSwitch<int>(Value)
1105 .Case("func", CoverageFunc)
1106 .Case("bb", CoverageBB)
1107 .Case("edge", CoverageEdge)
1108 .Case("indirect-calls", CoverageIndirCall)
1109 .Case("trace-bb", CoverageTraceBB)
1110 .Case("trace-cmp", CoverageTraceCmp)
1111 .Case("trace-div", CoverageTraceDiv)
1112 .Case("trace-gep", CoverageTraceGep)
1113 .Case("8bit-counters", Coverage8bitCounters)
1114 .Case("trace-pc", CoverageTracePC)
1115 .Case("trace-pc-guard", CoverageTracePCGuard)
1116 .Case("no-prune", CoverageNoPrune)
1117 .Case("inline-8bit-counters", CoverageInline8bitCounters)
1118 .Case("pc-table", CoveragePCTable)
1119 .Case("stack-depth", CoverageStackDepth)
1120 .Default(0);
1121 if (F == 0)
1122 D.Diag(clang::diag::err_drv_unsupported_option_argument)
1123 << A->getOption().getName() << Value;
1124 Features |= F;
1125 }
1126 return Features;
1127 }
1128
1129 std::string lastArgumentForMask(const Driver &D, const llvm::opt::ArgList &Args,
1130 SanitizerMask Mask) {
1131 for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(),
1132 E = Args.rend();
1133 I != E; ++I) {
1134 const auto *Arg = *I;
1135 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
1136 SanitizerMask AddKinds =
1137 expandSanitizerGroups(parseArgValues(D, Arg, false));
1138 if (AddKinds & Mask)
1139 return describeSanitizeArg(Arg, Mask);
1140 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
1141 SanitizerMask RemoveKinds =
1142 expandSanitizerGroups(parseArgValues(D, Arg, false));
1143 Mask &= ~RemoveKinds;
1144 }
1145 }
1146 llvm_unreachable("arg list didn't provide expected value");
1147 }
1148
1149 std::string describeSanitizeArg(const llvm::opt::Arg *A, SanitizerMask Mask) {
1150 assert(A->getOption().matches(options::OPT_fsanitize_EQ)
1151 && "Invalid argument in describeSanitizerArg!");
1152
1153 std::string Sanitizers;
1154 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
1155 if (expandSanitizerGroups(
1156 parseSanitizerValue(A->getValue(i), /*AllowGroups=*/true)) &
1157 Mask) {
1158 if (!Sanitizers.empty())
1159 Sanitizers += ",";
1160 Sanitizers += A->getValue(i);
1161 }
1162 }
1163
1164 assert(!Sanitizers.empty() && "arg didn't provide expected value");
1165 return "-fsanitize=" + Sanitizers;
1166 }
clang::ento::Nullability
Nullability
Definition: CheckerHelpers.h:52
NeedsUbsanRt
static const SanitizerMask NeedsUbsanRt
Definition: SanitizerArgs.cpp:27
RecoverableByDefault
static const SanitizerMask RecoverableByDefault
Definition: SanitizerArgs.cpp:51
CoverageBB
Definition: SanitizerArgs.cpp:77
CoverageTraceDiv
Definition: SanitizerArgs.cpp:82
CoverageIndirCall
Definition: SanitizerArgs.cpp:79
AlwaysRecoverable
static const SanitizerMask AlwaysRecoverable
Definition: SanitizerArgs.cpp:57
clang::driver::Driver::isUsingLTO
bool isUsingLTO() const
Returns true if we are performing any kind of LTO.
Definition: Driver.h:554
SupportsCoverage
static const SanitizerMask SupportsCoverage
Definition: SanitizerArgs.cpp:41
clang::XRayInstrKind::Function
constexpr XRayInstrMask Function
Definition: XRayInstr.h:38
clang::driver::SanitizerArgs::addArgs
void addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, types::ID InputType) const
Definition: SanitizerArgs.cpp:894
clang::driver::Driver::Diag
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:109
Value
Value
Definition: UninitializedValues.cpp:101
clang::driver::types::ID
ID
Definition: Types.h:23
NeedsUnwindTables
static const SanitizerMask NeedsUnwindTables
Definition: SanitizerArgs.cpp:38
Sanitizers.h
Defines the clang::SanitizerKind enum.
Coverage8bitCounters
Definition: SanitizerArgs.cpp:84
SanitizerArgs.h
CoverageTraceBB
Definition: SanitizerArgs.cpp:80
clang::driver::ToolChain::RM_Disabled
Definition: ToolChain.h:110
toString
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Definition: SanitizerArgs.cpp:856
CommonArgs.h
clang::driver::SanitizerArgs::needsUbsanRt
bool needsUbsanRt() const
Definition: SanitizerArgs.cpp:208
CFIClasses
static const SanitizerMask CFIClasses
Definition: SanitizerArgs.cpp:68
clang::SanitizerSet::Mask
SanitizerMask Mask
Bitmask of enabled sanitizers.
Definition: Sanitizers.h:174
CoverageEdge
Definition: SanitizerArgs.cpp:78
CoverageFeature
CoverageFeature
Definition: SanitizerArgs.cpp:75
NotAllowedWithMinimalRuntime
static const SanitizerMask NotAllowedWithMinimalRuntime
Definition: SanitizerArgs.cpp:34
clang::SanitizerSet
Definition: Sanitizers.h:151
clang::driver::Driver
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:59
clang::driver::ToolChain::getRTTIArg
const llvm::opt::Arg * getRTTIArg() const
Definition: ToolChain.h:252
NeedsUbsanCxxRt
static const SanitizerMask NeedsUbsanCxxRt
Definition: SanitizerArgs.cpp:31
llvm::SmallString
Definition: LLVM.h:34
CoveragePCTable
Definition: SanitizerArgs.cpp:89
Driver.h
clang::driver::Driver::getVFS
llvm::vfs::FileSystem & getVFS() const
Definition: Driver.h:319
clang::driver::SanitizerArgs::needsCfiDiagRt
bool needsCfiDiagRt() const
Definition: SanitizerArgs.cpp:224
NeedsLTO
static const SanitizerMask NeedsLTO
Definition: SanitizerArgs.cpp:61
clang::driver::SanitizerArgs::needsUnwindTables
bool needsUnwindTables() const
Definition: SanitizerArgs.cpp:233
CoverageNoPrune
Definition: SanitizerArgs.cpp:87
End
SourceLocation End
Definition: USRLocFinder.cpp:166
llvm::opt
Definition: Action.h:23
parseArgValues
static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A, bool DiagnoseErrors)
Parse a -fsanitize= or -fno-sanitize= argument&#39;s values, diagnosing any invalid components.
Definition: SanitizerArgs.cpp:1069
CoverageTraceCmp
Definition: SanitizerArgs.cpp:81
CoverageStackDepth
Definition: SanitizerArgs.cpp:90
clang::SanitizerKind
Definition: Sanitizers.h:129
NotAllowedWithTrap
static const SanitizerMask NotAllowedWithTrap
Definition: SanitizerArgs.cpp:33
TrappingSupported
static const SanitizerMask TrappingSupported
Definition: SanitizerArgs.cpp:62
parseCoverageFeatures
static int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A)
Parse -f(no-)?sanitize-coverage= flag values, diagnosing any invalid components.
Definition: SanitizerArgs.cpp:1098
addIncludeLinkerOption
static void addIncludeLinkerOption(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, StringRef SymbolName)
Definition: SanitizerArgs.cpp:868
Kind
Kind
Definition: ChrootChecker.cpp:29
clang::driver::ToolChain::getCompilerRT
virtual std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
Definition: ToolChain.cpp:391
clang::driver::ToolChain::getDriver
const Driver & getDriver() const
Definition: ToolChain.h:199
clang::driver::Driver::CCCIsCXX
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition: Driver.h:173
TrappingDefault
static const SanitizerMask TrappingDefault
Definition: SanitizerArgs.cpp:67
ToolChain.h
clang::SanitizerMask
Definition: Sanitizers.h:29
Options.h
clang::driver::ToolChain::getDefaultSanitizers
virtual SanitizerMask getDefaultSanitizers() const
Return sanitizers which are enabled by default.
Definition: ToolChain.h:602
clang
Dataflow Directional Tag Classes.
Definition: CFGReachabilityAnalysis.h:21
clang::StructuralEquivalenceKind::Default
addDefaultBlacklists
static void addDefaultBlacklists(const Driver &D, SanitizerMask Kinds, std::vector< std::string > &BlacklistFiles)
Definition: SanitizerArgs.cpp:121
RequiresPIE
static const SanitizerMask RequiresPIE
Definition: SanitizerArgs.cpp:36
clang::serialized_diags::create
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
Definition: SerializedDiagnosticPrinter.cpp:298
CompatibleWithMinimalRuntime
static const SanitizerMask CompatibleWithMinimalRuntime
Definition: SanitizerArgs.cpp:72
clang::driver::SanitizerArgs::needsCfiRt
bool needsCfiRt() const
Definition: SanitizerArgs.cpp:219
clang::driver::SanitizerArgs::requiresPIE
bool requiresPIE() const
Definition: SanitizerArgs.cpp:229
clang::driver::ToolChain::RTTIMode
RTTIMode
Definition: ToolChain.h:108
clang::parseSanitizerValue
SanitizerMask parseSanitizerValue(StringRef Value, bool AllowGroups)
Parse a single value from a -fsanitize= or -fno-sanitize= value list.
Definition: Sanitizers.cpp:27
setGroupBits
static SanitizerMask setGroupBits(SanitizerMask Kinds)
Sets group bits for every group that has at least one representative already enabled in Kinds...
Definition: SanitizerArgs.cpp:155
CoverageFunc
Definition: SanitizerArgs.cpp:76
clang::driver::types::isCXX
bool isCXX(ID Id)
isCXX - Is this a "C++" input (C++ and Obj-C++ sources and headers).
Definition: Types.cpp:160
clang::driver::ToolChain::getRTTIMode
RTTIMode getRTTIMode() const
Definition: ToolChain.h:255
clang::driver::ToolChain::getTriple
const llvm::Triple & getTriple() const
Definition: ToolChain.h:201
CoverageInline8bitCounters
Definition: SanitizerArgs.cpp:88
clang::driver
Definition: Action.h:31
clang::driver::ToolChain::getSupportedSanitizers
virtual SanitizerMask getSupportedSanitizers() const
Return sanitizers which are available in this toolchain.
Definition: ToolChain.cpp:942
DriverDiagnostic.h
CoverageTracePC
Definition: SanitizerArgs.cpp:85
clang::expandSanitizerGroups
SanitizerMask expandSanitizerGroups(SanitizerMask Kinds)
For each sanitizer group bit set in Kinds, set the bits for sanitizers this group enables...
Definition: Sanitizers.cpp:37
Unrecoverable
static const SanitizerMask Unrecoverable
Definition: SanitizerArgs.cpp:55
clang::interp::Add
bool Add(InterpState &S, CodePtr OpPC)
Definition: Interp.h:132
LegacyFsanitizeRecoverMask
static const SanitizerMask LegacyFsanitizeRecoverMask
Definition: SanitizerArgs.cpp:59
parseSanitizeTrapArgs
static SanitizerMask parseSanitizeTrapArgs(const Driver &D, const llvm::opt::ArgList &Args)
Definition: SanitizerArgs.cpp:164
clang::driver::SanitizerArgs::SanitizerArgs
SanitizerArgs(const ToolChain &TC, const llvm::opt::ArgList &Args)
Parses the sanitizer arguments from an argument list.
Definition: SanitizerArgs.cpp:241
describeSanitizeArg
static std::string describeSanitizeArg(const llvm::opt::Arg *A, SanitizerMask Mask)
Produce an argument string from argument A, which shows how it provides a value in Mask...
Definition: SanitizerArgs.cpp:1149
hasTargetFeatureMTE
static bool hasTargetFeatureMTE(const llvm::opt::ArgStringList &CmdArgs)
Definition: SanitizerArgs.cpp:882
CoverageTraceGep
Definition: SanitizerArgs.cpp:83
lastArgumentForMask
static std::string lastArgumentForMask(const Driver &D, const llvm::opt::ArgList &Args, SanitizerMask Mask)
Produce an argument string from ArgList Args, which shows how it provides some sanitizer kind from Ma...
Definition: SanitizerArgs.cpp:1129
clang::driver::SanitizerArgs::needsLTO
bool needsLTO() const
Definition: SanitizerArgs.cpp:237
CoverageTracePCGuard
Definition: SanitizerArgs.cpp:86
clang::driver::ToolChain
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:88
clang::driver::Driver::ResourceDir
std::string ResourceDir
The path to the compiler resource directory.
Definition: Driver.h:132