blob: 6afa48729589be986d6777a6bc2f480b914692ac [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 Karpenkov33613f62017-08-11 17:22:58 +000035 Integer | Nullability | DataFlow | Fuzzer | FuzzerNoLink,
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,
Matt Morehouse5c7fc762017-08-18 18:43:30 +000061 CoverageStackDepth = 1 << 14,
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000062};
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000063
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000064/// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
Peter Collingbourne3eea6772015-05-11 21:39:14 +000065/// invalid components. Returns a SanitizerMask.
66static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
67 bool DiagnoseErrors);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000068
Alexey Samsonovdfa908c2015-05-07 22:34:06 +000069/// Parse -f(no-)?sanitize-coverage= flag values, diagnosing any invalid
70/// components. Returns OR of members of \c CoverageFeature enumeration.
71static int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A);
72
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000073/// Produce an argument string from ArgList \p Args, which shows how it
74/// provides some sanitizer kind from \p Mask. For example, the argument list
75/// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt
76/// would produce "-fsanitize=vptr".
77static std::string lastArgumentForMask(const Driver &D,
78 const llvm::opt::ArgList &Args,
Peter Collingbourne3eea6772015-05-11 21:39:14 +000079 SanitizerMask Mask);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000080
81/// Produce an argument string from argument \p A, which shows how it provides
82/// a value in \p Mask. For instance, the argument
83/// "-fsanitize=address,alignment" with mask \c NeedsUbsanRt would produce
84/// "-fsanitize=alignment".
Peter Collingbourne3eea6772015-05-11 21:39:14 +000085static std::string describeSanitizeArg(const llvm::opt::Arg *A,
86 SanitizerMask Mask);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +000087
Alexey Samsonov1e715a62014-11-16 20:53:53 +000088/// Produce a string containing comma-separated names of sanitizers in \p
89/// Sanitizers set.
90static std::string toString(const clang::SanitizerSet &Sanitizers);
91
Peter Collingbourne3eea6772015-05-11 21:39:14 +000092static bool getDefaultBlacklist(const Driver &D, SanitizerMask Kinds,
Alexey Samsonovecf380e2015-03-20 18:45:06 +000093 std::string &BLPath) {
94 const char *BlacklistFile = nullptr;
Peter Collingbourne3eea6772015-05-11 21:39:14 +000095 if (Kinds & Address)
Alexey Samsonovecf380e2015-03-20 18:45:06 +000096 BlacklistFile = "asan_blacklist.txt";
Peter Collingbourne3eea6772015-05-11 21:39:14 +000097 else if (Kinds & Memory)
Alexey Samsonovecf380e2015-03-20 18:45:06 +000098 BlacklistFile = "msan_blacklist.txt";
Peter Collingbourne3eea6772015-05-11 21:39:14 +000099 else if (Kinds & Thread)
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000100 BlacklistFile = "tsan_blacklist.txt";
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000101 else if (Kinds & DataFlow)
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000102 BlacklistFile = "dfsan_abilist.txt";
Peter Collingbourne6fccf952015-07-15 12:15:56 +0000103 else if (Kinds & CFI)
104 BlacklistFile = "cfi_blacklist.txt";
Han Shen0d7ac5f2017-08-02 19:53:38 +0000105 else if (Kinds & Undefined)
106 BlacklistFile = "ubsan_blacklist.txt";
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000107
108 if (BlacklistFile) {
109 clang::SmallString<64> Path(D.ResourceDir);
110 llvm::sys::path::append(Path, BlacklistFile);
111 BLPath = Path.str();
112 return true;
113 }
114 return false;
115}
116
Peter Collingbourne9881b782015-06-18 23:59:22 +0000117/// Sets group bits for every group that has at least one representative already
118/// enabled in \p Kinds.
119static SanitizerMask setGroupBits(SanitizerMask Kinds) {
120#define SANITIZER(NAME, ID)
121#define SANITIZER_GROUP(NAME, ID, ALIAS) \
122 if (Kinds & SanitizerKind::ID) \
123 Kinds |= SanitizerKind::ID##Group;
124#include "clang/Basic/Sanitizers.def"
125 return Kinds;
126}
127
128static SanitizerMask parseSanitizeTrapArgs(const Driver &D,
129 const llvm::opt::ArgList &Args) {
130 SanitizerMask TrapRemove = 0; // During the loop below, the accumulated set of
131 // sanitizers disabled by the current sanitizer
132 // argument or any argument after it.
133 SanitizerMask TrappingKinds = 0;
134 SanitizerMask TrappingSupportedWithGroups = setGroupBits(TrappingSupported);
135
136 for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
137 I != E; ++I) {
138 const auto *Arg = *I;
139 if (Arg->getOption().matches(options::OPT_fsanitize_trap_EQ)) {
140 Arg->claim();
141 SanitizerMask Add = parseArgValues(D, Arg, true);
142 Add &= ~TrapRemove;
143 if (SanitizerMask InvalidValues = Add & ~TrappingSupportedWithGroups) {
144 SanitizerSet S;
145 S.Mask = InvalidValues;
146 D.Diag(diag::err_drv_unsupported_option_argument) << "-fsanitize-trap"
147 << toString(S);
148 }
149 TrappingKinds |= expandSanitizerGroups(Add) & ~TrapRemove;
150 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) {
151 Arg->claim();
152 TrapRemove |= expandSanitizerGroups(parseArgValues(D, Arg, true));
153 } else if (Arg->getOption().matches(
154 options::OPT_fsanitize_undefined_trap_on_error)) {
155 Arg->claim();
156 TrappingKinds |=
157 expandSanitizerGroups(UndefinedGroup & ~TrapRemove) & ~TrapRemove;
158 } else if (Arg->getOption().matches(
159 options::OPT_fno_sanitize_undefined_trap_on_error)) {
160 Arg->claim();
161 TrapRemove |= expandSanitizerGroups(UndefinedGroup);
162 }
163 }
164
Peter Collingbourne6708c4a2015-06-19 01:51:54 +0000165 // Apply default trapping behavior.
166 TrappingKinds |= TrappingDefault & ~TrapRemove;
167
Peter Collingbourne9881b782015-06-18 23:59:22 +0000168 return TrappingKinds;
169}
170
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000171bool SanitizerArgs::needsUbsanRt() const {
Evgeniy Stepanov5b49eb42016-06-14 21:33:40 +0000172 return ((Sanitizers.Mask & NeedsUbsanRt & ~TrapSanitizers.Mask) ||
173 CoverageFeatures) &&
174 !Sanitizers.has(Address) && !Sanitizers.has(Memory) &&
Petr Hosekb31582b2017-08-03 23:02:22 +0000175 !Sanitizers.has(Thread) && !Sanitizers.has(DataFlow) &&
Mike Aizatskyd1033f52016-12-08 22:25:01 +0000176 !Sanitizers.has(Leak) && !CfiCrossDso;
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000177}
178
179bool SanitizerArgs::needsCfiRt() const {
Evgeniy Stepanove3fb51c2015-12-16 00:38:42 +0000180 return !(Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso;
181}
182
183bool SanitizerArgs::needsCfiDiagRt() const {
184 return (Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso;
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000185}
186
Dmitry Vyukov43419a72014-11-21 12:19:01 +0000187bool SanitizerArgs::requiresPIE() const {
Evgeniy Stepanov71554fe2015-10-21 21:28:49 +0000188 return NeedPIE || (Sanitizers.Mask & RequiresPIE);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000189}
190
191bool SanitizerArgs::needsUnwindTables() const {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000192 return Sanitizers.Mask & NeedsUnwindTables;
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000193}
194
Peter Collingbourne32701642013-11-01 18:16:25 +0000195SanitizerArgs::SanitizerArgs(const ToolChain &TC,
196 const llvm::opt::ArgList &Args) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000197 SanitizerMask AllRemove = 0; // During the loop below, the accumulated set of
198 // sanitizers disabled by the current sanitizer
199 // argument or any argument after it.
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000200 SanitizerMask AllAddedKinds = 0; // Mask of all sanitizers ever enabled by
201 // -fsanitize= flags (directly or via group
202 // expansion), some of which may be disabled
203 // later. Used to carefully prune
204 // unused-argument diagnostics.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000205 SanitizerMask DiagnosedKinds = 0; // All Kinds we have diagnosed up to now.
206 // Used to deduplicate diagnostics.
207 SanitizerMask Kinds = 0;
Alexey Samsonov9b873092015-06-25 23:14:32 +0000208 const SanitizerMask Supported = setGroupBits(TC.getSupportedSanitizers());
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000209 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
210
Peter Collingbourne32701642013-11-01 18:16:25 +0000211 const Driver &D = TC.getDriver();
Peter Collingbourne9881b782015-06-18 23:59:22 +0000212 SanitizerMask TrappingKinds = parseSanitizeTrapArgs(D, Args);
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000213 SanitizerMask InvalidTrappingKinds = TrappingKinds & NotAllowedWithTrap;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000214
Vedant Kumar7aacb652017-06-23 23:15:24 +0000215 // The object size sanitizer should not be enabled at -O0.
216 Arg *OptLevel = Args.getLastArg(options::OPT_O_Group);
217 bool RemoveObjectSizeAtO0 =
218 !OptLevel || OptLevel->getOption().matches(options::OPT_O0);
219
Peter Collingbourne32701642013-11-01 18:16:25 +0000220 for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
221 I != E; ++I) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000222 const auto *Arg = *I;
223 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
224 Arg->claim();
Vedant Kumar7aacb652017-06-23 23:15:24 +0000225 SanitizerMask Add = parseArgValues(D, Arg, /*AllowGroups=*/true);
226
227 if (RemoveObjectSizeAtO0) {
228 AllRemove |= SanitizerKind::ObjectSize;
229
230 // The user explicitly enabled the object size sanitizer. Warn that
231 // that this does nothing at -O0.
232 if (Add & SanitizerKind::ObjectSize)
233 D.Diag(diag::warn_drv_object_size_disabled_O0)
234 << Arg->getAsString(Args);
235 }
236
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000237 AllAddedKinds |= expandSanitizerGroups(Add);
Peter Collingbourne32701642013-11-01 18:16:25 +0000238
Alexey Samsonov799f7932014-12-19 02:35:16 +0000239 // Avoid diagnosing any sanitizer which is disabled later.
240 Add &= ~AllRemove;
241 // At this point we have not expanded groups, so any unsupported
242 // sanitizers in Add are those which have been explicitly enabled.
243 // Diagnose them.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000244 if (SanitizerMask KindsToDiagnose =
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000245 Add & InvalidTrappingKinds & ~DiagnosedKinds) {
Peter Collingbourne9881b782015-06-18 23:59:22 +0000246 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
247 D.Diag(diag::err_drv_argument_not_allowed_with)
248 << Desc << "-fsanitize-trap=undefined";
249 DiagnosedKinds |= KindsToDiagnose;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000250 }
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000251 Add &= ~InvalidTrappingKinds;
252 if (SanitizerMask KindsToDiagnose = Add & ~Supported & ~DiagnosedKinds) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000253 std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
254 D.Diag(diag::err_drv_unsupported_opt_for_target)
255 << Desc << TC.getTriple().str();
256 DiagnosedKinds |= KindsToDiagnose;
257 }
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000258 Add &= Supported;
Peter Collingbourne32701642013-11-01 18:16:25 +0000259
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000260 // Test for -fno-rtti + explicit -fsanitizer=vptr before expanding groups
261 // so we don't error out if -fno-rtti and -fsanitize=undefined were
262 // passed.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000263 if (Add & Vptr &&
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000264 (RTTIMode == ToolChain::RM_DisabledImplicitly ||
265 RTTIMode == ToolChain::RM_DisabledExplicitly)) {
266 if (RTTIMode == ToolChain::RM_DisabledImplicitly)
267 // Warn about not having rtti enabled if the vptr sanitizer is
268 // explicitly enabled
269 D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default);
270 else {
271 const llvm::opt::Arg *NoRTTIArg = TC.getRTTIArg();
272 assert(NoRTTIArg &&
273 "RTTI disabled explicitly but we have no argument!");
274 D.Diag(diag::err_drv_argument_not_allowed_with)
275 << "-fsanitize=vptr" << NoRTTIArg->getAsString(Args);
276 }
277
278 // Take out the Vptr sanitizer from the enabled sanitizers
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000279 AllRemove |= Vptr;
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000280 }
281
Peter Collingbournebf59c342015-05-11 21:39:20 +0000282 Add = expandSanitizerGroups(Add);
Alexey Samsonov799f7932014-12-19 02:35:16 +0000283 // Group expansion may have enabled a sanitizer which is disabled later.
284 Add &= ~AllRemove;
285 // Silently discard any unsupported sanitizers implicitly enabled through
286 // group expansion.
Alexey Samsonov7f2a0d22015-06-19 21:36:47 +0000287 Add &= ~InvalidTrappingKinds;
288 Add &= Supported;
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000289
George Karpenkovf2fc5b02017-04-24 18:23:24 +0000290 if (Add & Fuzzer)
George Karpenkov33613f62017-08-11 17:22:58 +0000291 Add |= FuzzerNoLink;
292
Matt Morehouse6ec75952017-08-25 22:01:21 +0000293 // Enable coverage if the fuzzing flag is set.
Matt Morehouse2ad8d942017-08-29 19:48:12 +0000294 if (Add & FuzzerNoLink) {
Kostya Serebryany7dbb1e12017-08-04 21:35:11 +0000295 CoverageFeatures |= CoverageTracePCGuard | CoverageIndirCall |
Matt Morehouse6ec75952017-08-25 22:01:21 +0000296 CoverageTraceCmp | CoveragePCTable;
Matt Morehouse2ad8d942017-08-29 19:48:12 +0000297 // Due to TLS differences, stack depth tracking is disabled on Mac.
298 if (!TC.getTriple().isOSDarwin())
299 CoverageFeatures |= CoverageStackDepth;
300 }
George Karpenkovf2fc5b02017-04-24 18:23:24 +0000301
Alexey Samsonov799f7932014-12-19 02:35:16 +0000302 Kinds |= Add;
303 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
304 Arg->claim();
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000305 SanitizerMask Remove = parseArgValues(D, Arg, true);
Peter Collingbournebf59c342015-05-11 21:39:20 +0000306 AllRemove |= expandSanitizerGroups(Remove);
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000307 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000308 }
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000309
Ed Schoutenfc79d2c2016-03-29 21:13:53 +0000310 // Enable toolchain specific default sanitizers if not explicitly disabled.
311 Kinds |= TC.getDefaultSanitizers() & ~AllRemove;
312
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000313 // We disable the vptr sanitizer if it was enabled by group expansion but RTTI
314 // is disabled.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000315 if ((Kinds & Vptr) &&
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000316 (RTTIMode == ToolChain::RM_DisabledImplicitly ||
317 RTTIMode == ToolChain::RM_DisabledExplicitly)) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000318 Kinds &= ~Vptr;
Filipe Cabecinhasec5d0e62015-02-19 01:04:49 +0000319 }
320
Alexey Samsonov907880e2015-06-19 19:57:46 +0000321 // Check that LTO is enabled if we need it.
Teresa Johnson945bc502015-10-15 20:35:53 +0000322 if ((Kinds & NeedsLTO) && !D.isUsingLTO()) {
Alexey Samsonov907880e2015-06-19 19:57:46 +0000323 D.Diag(diag::err_drv_argument_only_allowed_with)
324 << lastArgumentForMask(D, Args, Kinds & NeedsLTO) << "-flto";
325 }
326
Alexey Samsonov9b873092015-06-25 23:14:32 +0000327 // Report error if there are non-trapping sanitizers that require
328 // c++abi-specific parts of UBSan runtime, and they are not provided by the
329 // toolchain. We don't have a good way to check the latter, so we just
330 // check if the toolchan supports vptr.
331 if (~Supported & Vptr) {
Peter Collingbourne4bdceaa2015-07-08 21:08:05 +0000332 SanitizerMask KindsToDiagnose = Kinds & ~TrappingKinds & NeedsUbsanCxxRt;
333 // The runtime library supports the Microsoft C++ ABI, but only well enough
334 // for CFI. FIXME: Remove this once we support vptr on Windows.
335 if (TC.getTriple().isOSWindows())
336 KindsToDiagnose &= ~CFI;
337 if (KindsToDiagnose) {
Alexey Samsonov9b873092015-06-25 23:14:32 +0000338 SanitizerSet S;
339 S.Mask = KindsToDiagnose;
340 D.Diag(diag::err_drv_unsupported_opt_for_target)
341 << ("-fno-sanitize-trap=" + toString(S)) << TC.getTriple().str();
342 Kinds &= ~KindsToDiagnose;
343 }
344 }
345
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000346 // Warn about incompatible groups of sanitizers.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000347 std::pair<SanitizerMask, SanitizerMask> IncompatibleGroups[] = {
348 std::make_pair(Address, Thread), std::make_pair(Address, Memory),
349 std::make_pair(Thread, Memory), std::make_pair(Leak, Thread),
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000350 std::make_pair(Leak, Memory), std::make_pair(KernelAddress, Address),
351 std::make_pair(KernelAddress, Leak),
352 std::make_pair(KernelAddress, Thread),
Derek Bruening256c2e12016-04-21 21:32:04 +0000353 std::make_pair(KernelAddress, Memory),
354 std::make_pair(Efficiency, Address),
355 std::make_pair(Efficiency, Leak),
356 std::make_pair(Efficiency, Thread),
357 std::make_pair(Efficiency, Memory),
358 std::make_pair(Efficiency, KernelAddress)};
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000359 for (auto G : IncompatibleGroups) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000360 SanitizerMask Group = G.first;
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000361 if (Kinds & Group) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000362 if (SanitizerMask Incompatible = Kinds & G.second) {
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000363 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
364 << lastArgumentForMask(D, Args, Group)
365 << lastArgumentForMask(D, Args, Incompatible);
366 Kinds &= ~Incompatible;
367 }
368 }
369 }
370 // FIXME: Currently -fsanitize=leak is silently ignored in the presence of
371 // -fsanitize=address. Perhaps it should print an error, or perhaps
372 // -f(-no)sanitize=leak should change whether leak detection is enabled by
373 // default in ASan?
374
Alexey Samsonov88459522015-01-12 22:39:12 +0000375 // Parse -f(no-)?sanitize-recover flags.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000376 SanitizerMask RecoverableKinds = RecoverableByDefault;
377 SanitizerMask DiagnosedUnrecoverableKinds = 0;
Alexey Samsonov88459522015-01-12 22:39:12 +0000378 for (const auto *Arg : Args) {
Alexey Samsonovce2e77c2015-03-11 23:34:25 +0000379 const char *DeprecatedReplacement = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +0000380 if (Arg->getOption().matches(options::OPT_fsanitize_recover)) {
Kostya Serebryanyceb1add2016-05-04 20:21:47 +0000381 DeprecatedReplacement =
382 "-fsanitize-recover=undefined,integer' or '-fsanitize-recover=all";
Peter Collingbournebf59c342015-05-11 21:39:20 +0000383 RecoverableKinds |= expandSanitizerGroups(LegacyFsanitizeRecoverMask);
Alexey Samsonov88459522015-01-12 22:39:12 +0000384 Arg->claim();
385 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover)) {
Kostya Serebryanyceb1add2016-05-04 20:21:47 +0000386 DeprecatedReplacement = "-fno-sanitize-recover=undefined,integer' or "
387 "'-fno-sanitize-recover=all";
Peter Collingbournebf59c342015-05-11 21:39:20 +0000388 RecoverableKinds &= ~expandSanitizerGroups(LegacyFsanitizeRecoverMask);
Alexey Samsonov88459522015-01-12 22:39:12 +0000389 Arg->claim();
390 } else if (Arg->getOption().matches(options::OPT_fsanitize_recover_EQ)) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000391 SanitizerMask Add = parseArgValues(D, Arg, true);
Alexey Samsonov88459522015-01-12 22:39:12 +0000392 // Report error if user explicitly tries to recover from unrecoverable
393 // sanitizer.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000394 if (SanitizerMask KindsToDiagnose =
Alexey Samsonov88459522015-01-12 22:39:12 +0000395 Add & Unrecoverable & ~DiagnosedUnrecoverableKinds) {
396 SanitizerSet SetToDiagnose;
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000397 SetToDiagnose.Mask |= KindsToDiagnose;
Alexey Samsonov88459522015-01-12 22:39:12 +0000398 D.Diag(diag::err_drv_unsupported_option_argument)
399 << Arg->getOption().getName() << toString(SetToDiagnose);
400 DiagnosedUnrecoverableKinds |= KindsToDiagnose;
401 }
Peter Collingbournebf59c342015-05-11 21:39:20 +0000402 RecoverableKinds |= expandSanitizerGroups(Add);
Alexey Samsonov88459522015-01-12 22:39:12 +0000403 Arg->claim();
404 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000405 RecoverableKinds &= ~expandSanitizerGroups(parseArgValues(D, Arg, true));
Alexey Samsonov88459522015-01-12 22:39:12 +0000406 Arg->claim();
407 }
Alexey Samsonovce2e77c2015-03-11 23:34:25 +0000408 if (DeprecatedReplacement) {
409 D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
410 << DeprecatedReplacement;
411 }
Alexey Samsonov88459522015-01-12 22:39:12 +0000412 }
413 RecoverableKinds &= Kinds;
414 RecoverableKinds &= ~Unrecoverable;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000415
Peter Collingbourne9881b782015-06-18 23:59:22 +0000416 TrappingKinds &= Kinds;
417
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000418 // Setup blacklist files.
419 // Add default blacklist from resource directory.
420 {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000421 std::string BLPath;
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000422 if (getDefaultBlacklist(D, Kinds, BLPath) && llvm::sys::fs::exists(BLPath))
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000423 BlacklistFiles.push_back(BLPath);
424 }
425 // Parse -f(no-)sanitize-blacklist options.
426 for (const auto *Arg : Args) {
427 if (Arg->getOption().matches(options::OPT_fsanitize_blacklist)) {
428 Arg->claim();
429 std::string BLPath = Arg->getValue();
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000430 if (llvm::sys::fs::exists(BLPath)) {
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000431 BlacklistFiles.push_back(BLPath);
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000432 ExtraDeps.push_back(BLPath);
433 } else
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000434 D.Diag(clang::diag::err_drv_no_such_file) << BLPath;
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000435
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000436 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_blacklist)) {
437 Arg->claim();
438 BlacklistFiles.clear();
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000439 ExtraDeps.clear();
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000440 }
441 }
442 // Validate blacklists format.
443 {
444 std::string BLError;
445 std::unique_ptr<llvm::SpecialCaseList> SCL(
446 llvm::SpecialCaseList::create(BlacklistFiles, BLError));
447 if (!SCL.get())
448 D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000449 }
450
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000451 // Parse -f[no-]sanitize-memory-track-origins[=level] options.
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000452 if (AllAddedKinds & Memory) {
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000453 if (Arg *A =
454 Args.getLastArg(options::OPT_fsanitize_memory_track_origins_EQ,
455 options::OPT_fsanitize_memory_track_origins,
456 options::OPT_fno_sanitize_memory_track_origins)) {
457 if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) {
Evgeniy Stepanov6e09bca2015-02-26 15:59:30 +0000458 MsanTrackOrigins = 2;
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000459 } else if (A->getOption().matches(
460 options::OPT_fno_sanitize_memory_track_origins)) {
461 MsanTrackOrigins = 0;
462 } else {
463 StringRef S = A->getValue();
464 if (S.getAsInteger(0, MsanTrackOrigins) || MsanTrackOrigins < 0 ||
465 MsanTrackOrigins > 2) {
Nico Weberf2a39a72015-04-13 20:03:03 +0000466 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000467 }
468 }
469 }
Evgeniy Stepanov71554fe2015-10-21 21:28:49 +0000470 MsanUseAfterDtor =
471 Args.hasArg(options::OPT_fsanitize_memory_use_after_dtor);
472 NeedPIE |= !(TC.getTriple().isOSLinux() &&
473 TC.getTriple().getArch() == llvm::Triple::x86_64);
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000474 }
475
Evgeniy Stepanov8a2bedb2016-11-11 23:17:36 +0000476 if (AllAddedKinds & Thread) {
477 TsanMemoryAccess = Args.hasFlag(options::OPT_fsanitize_thread_memory_access,
478 options::OPT_fno_sanitize_thread_memory_access,
479 TsanMemoryAccess);
480 TsanFuncEntryExit = Args.hasFlag(options::OPT_fsanitize_thread_func_entry_exit,
481 options::OPT_fno_sanitize_thread_func_entry_exit,
482 TsanFuncEntryExit);
483 TsanAtomics = Args.hasFlag(options::OPT_fsanitize_thread_atomics,
484 options::OPT_fno_sanitize_thread_atomics,
485 TsanAtomics);
486 }
487
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000488 if (AllAddedKinds & CFI) {
489 CfiCrossDso = Args.hasFlag(options::OPT_fsanitize_cfi_cross_dso,
490 options::OPT_fno_sanitize_cfi_cross_dso, false);
491 // Without PIE, external function address may resolve to a PLT record, which
492 // can not be verified by the target module.
493 NeedPIE |= CfiCrossDso;
494 }
495
Peter Collingbournedc134532016-01-16 00:31:22 +0000496 Stats = Args.hasFlag(options::OPT_fsanitize_stats,
497 options::OPT_fno_sanitize_stats, false);
498
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000499 // Parse -f(no-)?sanitize-coverage flags if coverage is supported by the
500 // enabled sanitizers.
Kostya Serebryany52e86492016-02-18 00:49:23 +0000501 for (const auto *Arg : Args) {
502 if (Arg->getOption().matches(options::OPT_fsanitize_coverage)) {
503 int LegacySanitizeCoverage;
504 if (Arg->getNumValues() == 1 &&
505 !StringRef(Arg->getValue(0))
Kostya Serebryany9d1ed132017-04-19 19:57:16 +0000506 .getAsInteger(0, LegacySanitizeCoverage)) {
507 CoverageFeatures = 0;
508 Arg->claim();
509 if (LegacySanitizeCoverage != 0) {
Nico Weber4152f522016-02-18 19:32:54 +0000510 D.Diag(diag::warn_drv_deprecated_arg)
Kostya Serebryany9d1ed132017-04-19 19:57:16 +0000511 << Arg->getAsString(Args) << "-fsanitize-coverage=trace-pc-guard";
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000512 }
Kostya Serebryany52e86492016-02-18 00:49:23 +0000513 continue;
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000514 }
Kostya Serebryany52e86492016-02-18 00:49:23 +0000515 CoverageFeatures |= parseCoverageFeatures(D, Arg);
Evgeniy Stepanov5b49eb42016-06-14 21:33:40 +0000516
517 // Disable coverage and not claim the flags if there is at least one
518 // non-supporting sanitizer.
Petr Hosekeb4127f2017-07-21 01:17:49 +0000519 if (!(AllAddedKinds & ~AllRemove & ~setGroupBits(SupportsCoverage))) {
Kostya Serebryany52e86492016-02-18 00:49:23 +0000520 Arg->claim();
Kostya Serebryanyf5b25f82016-04-18 21:30:17 +0000521 } else {
522 CoverageFeatures = 0;
Kostya Serebryany52e86492016-02-18 00:49:23 +0000523 }
524 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_coverage)) {
525 Arg->claim();
526 CoverageFeatures &= ~parseCoverageFeatures(D, Arg);
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000527 }
528 }
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000529 // Choose at most one coverage type: function, bb, or edge.
530 if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageBB))
531 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
532 << "-fsanitize-coverage=func"
533 << "-fsanitize-coverage=bb";
534 if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageEdge))
535 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
536 << "-fsanitize-coverage=func"
537 << "-fsanitize-coverage=edge";
538 if ((CoverageFeatures & CoverageBB) && (CoverageFeatures & CoverageEdge))
539 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
540 << "-fsanitize-coverage=bb"
541 << "-fsanitize-coverage=edge";
542 // Basic block tracing and 8-bit counters require some type of coverage
543 // enabled.
Kostya Serebryany1c0e9e92017-04-19 21:31:11 +0000544 if (CoverageFeatures & CoverageTraceBB)
545 D.Diag(clang::diag::warn_drv_deprecated_arg)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000546 << "-fsanitize-coverage=trace-bb"
Kostya Serebryany1c0e9e92017-04-19 21:31:11 +0000547 << "-fsanitize-coverage=trace-pc-guard";
548 if (CoverageFeatures & Coverage8bitCounters)
Kostya Serebryany1a02d8b2017-04-19 20:15:58 +0000549 D.Diag(clang::diag::warn_drv_deprecated_arg)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000550 << "-fsanitize-coverage=8bit-counters"
Kostya Serebryany1a02d8b2017-04-19 20:15:58 +0000551 << "-fsanitize-coverage=trace-pc-guard";
Kostya Serebryany8955efc2017-05-03 01:27:28 +0000552
553 int InsertionPointTypes = CoverageFunc | CoverageBB | CoverageEdge;
Kostya Serebryany9f338dc2017-08-08 20:20:40 +0000554 int InstrumentationTypes =
555 CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters;
Kostya Serebryany8955efc2017-05-03 01:27:28 +0000556 if ((CoverageFeatures & InsertionPointTypes) &&
Kostya Serebryany9f338dc2017-08-08 20:20:40 +0000557 !(CoverageFeatures & InstrumentationTypes)) {
Kostya Serebryany8955efc2017-05-03 01:27:28 +0000558 D.Diag(clang::diag::warn_drv_deprecated_arg)
559 << "-fsanitize-coverage=[func|bb|edge]"
560 << "-fsanitize-coverage=[func|bb|edge],[trace-pc-guard|trace-pc]";
561 }
562
Kostya Serebryany52e86492016-02-18 00:49:23 +0000563 // trace-pc w/o func/bb/edge implies edge.
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000564 if (!(CoverageFeatures & InsertionPointTypes)) {
565 if (CoverageFeatures &
566 (CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters))
567 CoverageFeatures |= CoverageEdge;
568
569 if (CoverageFeatures & CoverageStackDepth)
570 CoverageFeatures |= CoverageFunc;
571 }
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000572
Alexey Samsonovde0aff32015-05-21 01:07:52 +0000573 if (AllAddedKinds & Address) {
Alexey Samsonovbdfa6c22014-04-01 13:31:10 +0000574 AsanSharedRuntime =
Petr Hosekb31582b2017-08-03 23:02:22 +0000575 Args.hasArg(options::OPT_shared_libasan) ||
576 TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia();
577 NeedPIE |= TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia();
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000578 if (Arg *A =
579 Args.getLastArg(options::OPT_fsanitize_address_field_padding)) {
580 StringRef S = A->getValue();
581 // Legal values are 0 and 1, 2, but in future we may add more levels.
582 if (S.getAsInteger(0, AsanFieldPadding) || AsanFieldPadding < 0 ||
583 AsanFieldPadding > 2) {
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000584 D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000585 }
586 }
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000587
588 if (Arg *WindowsDebugRTArg =
589 Args.getLastArg(options::OPT__SLASH_MTd, options::OPT__SLASH_MT,
590 options::OPT__SLASH_MDd, options::OPT__SLASH_MD,
591 options::OPT__SLASH_LDd, options::OPT__SLASH_LD)) {
592 switch (WindowsDebugRTArg->getOption().getID()) {
593 case options::OPT__SLASH_MTd:
594 case options::OPT__SLASH_MDd:
595 case options::OPT__SLASH_LDd:
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000596 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000597 << WindowsDebugRTArg->getAsString(Args)
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000598 << lastArgumentForMask(D, Args, Address);
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000599 D.Diag(clang::diag::note_drv_address_sanitizer_debug_runtime);
Ehsan Akhgarie0db1962014-10-14 23:15:44 +0000600 }
601 }
Alexey Samsonov90490af2014-08-08 22:47:17 +0000602
Vedant Kumara9d8be62017-05-08 21:11:55 +0000603 AsanUseAfterScope = Args.hasFlag(
604 options::OPT_fsanitize_address_use_after_scope,
605 options::OPT_fno_sanitize_address_use_after_scope, AsanUseAfterScope);
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000606
607 // As a workaround for a bug in gold 2.26 and earlier, dead stripping of
608 // globals in ASan is disabled by default on ELF targets.
609 // See https://sourceware.org/bugzilla/show_bug.cgi?id=19002
610 AsanGlobalsDeadStripping =
Petr Hosekb31582b2017-08-03 23:02:22 +0000611 !TC.getTriple().isOSBinFormatELF() || TC.getTriple().isOSFuchsia() ||
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000612 Args.hasArg(options::OPT_fsanitize_address_globals_dead_stripping);
Vedant Kumara9d8be62017-05-08 21:11:55 +0000613 } else {
614 AsanUseAfterScope = false;
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000615 }
616
Petr Hosek766288b2017-08-16 19:06:05 +0000617 if (AllAddedKinds & SafeStack) {
618 // SafeStack runtime is built into the system on Fuchsia.
619 SafeStackRuntime = !TC.getTriple().isOSFuchsia();
620 }
621
Alexey Samsonov90490af2014-08-08 22:47:17 +0000622 // Parse -link-cxx-sanitizer flag.
623 LinkCXXRuntimes =
624 Args.hasArg(options::OPT_fsanitize_link_cxx_runtime) || D.CCCIsCXX();
Alexey Samsonovecf380e2015-03-20 18:45:06 +0000625
626 // Finally, initialize the set of available and recoverable sanitizers.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000627 Sanitizers.Mask |= Kinds;
628 RecoverableSanitizers.Mask |= RecoverableKinds;
Peter Collingbourne9881b782015-06-18 23:59:22 +0000629 TrapSanitizers.Mask |= TrappingKinds;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000630}
631
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000632static std::string toString(const clang::SanitizerSet &Sanitizers) {
633 std::string Res;
634#define SANITIZER(NAME, ID) \
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000635 if (Sanitizers.has(ID)) { \
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000636 if (!Res.empty()) \
637 Res += ","; \
638 Res += NAME; \
639 }
640#include "clang/Basic/Sanitizers.def"
641 return Res;
642}
643
Peter Collingbournedc134532016-01-16 00:31:22 +0000644static void addIncludeLinkerOption(const ToolChain &TC,
645 const llvm::opt::ArgList &Args,
646 llvm::opt::ArgStringList &CmdArgs,
647 StringRef SymbolName) {
648 SmallString<64> LinkerOptionFlag;
649 LinkerOptionFlag = "--linker-option=/include:";
650 if (TC.getTriple().getArch() == llvm::Triple::x86) {
651 // Win32 mangles C function names with a '_' prefix.
652 LinkerOptionFlag += '_';
653 }
654 LinkerOptionFlag += SymbolName;
655 CmdArgs.push_back(Args.MakeArgString(LinkerOptionFlag));
656}
657
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000658void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args,
Peter Collingbourne581f4382015-07-02 01:48:12 +0000659 llvm::opt::ArgStringList &CmdArgs,
660 types::ID InputType) const {
Justin Lebar6efbc732016-09-15 23:44:13 +0000661 // NVPTX doesn't currently support sanitizers. Bailing out here means that
662 // e.g. -fsanitize=address applies only to host code, which is what we want
663 // for now.
664 if (TC.getTriple().isNVPTX())
665 return;
666
Kostya Serebryany52e86492016-02-18 00:49:23 +0000667 // Translate available CoverageFeatures to corresponding clang-cc1 flags.
668 // Do it even if Sanitizers.empty() since some forms of coverage don't require
669 // sanitizers.
670 std::pair<int, const char *> CoverageFlags[] = {
671 std::make_pair(CoverageFunc, "-fsanitize-coverage-type=1"),
672 std::make_pair(CoverageBB, "-fsanitize-coverage-type=2"),
673 std::make_pair(CoverageEdge, "-fsanitize-coverage-type=3"),
674 std::make_pair(CoverageIndirCall, "-fsanitize-coverage-indirect-calls"),
675 std::make_pair(CoverageTraceBB, "-fsanitize-coverage-trace-bb"),
676 std::make_pair(CoverageTraceCmp, "-fsanitize-coverage-trace-cmp"),
Kostya Serebryany3b419712016-08-30 01:27:03 +0000677 std::make_pair(CoverageTraceDiv, "-fsanitize-coverage-trace-div"),
678 std::make_pair(CoverageTraceGep, "-fsanitize-coverage-trace-gep"),
Kostya Serebryany52e86492016-02-18 00:49:23 +0000679 std::make_pair(Coverage8bitCounters, "-fsanitize-coverage-8bit-counters"),
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000680 std::make_pair(CoverageTracePC, "-fsanitize-coverage-trace-pc"),
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000681 std::make_pair(CoverageTracePCGuard, "-fsanitize-coverage-trace-pc-guard"),
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000682 std::make_pair(CoverageInline8bitCounters, "-fsanitize-coverage-inline-8bit-counters"),
Kostya Serebryany61457762017-07-28 00:10:10 +0000683 std::make_pair(CoveragePCTable, "-fsanitize-coverage-pc-table"),
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000684 std::make_pair(CoverageNoPrune, "-fsanitize-coverage-no-prune"),
685 std::make_pair(CoverageStackDepth, "-fsanitize-coverage-stack-depth")};
Kostya Serebryany52e86492016-02-18 00:49:23 +0000686 for (auto F : CoverageFlags) {
687 if (CoverageFeatures & F.first)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000688 CmdArgs.push_back(F.second);
Kostya Serebryany52e86492016-02-18 00:49:23 +0000689 }
690
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000691 if (TC.getTriple().isOSWindows() && needsUbsanRt()) {
692 // Instruct the code generator to embed linker directives in the object file
693 // that cause the required runtime libraries to be linked.
694 CmdArgs.push_back(Args.MakeArgString(
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000695 "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000696 if (types::isCXX(InputType))
697 CmdArgs.push_back(Args.MakeArgString(
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000698 "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone_cxx")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000699 }
700 if (TC.getTriple().isOSWindows() && needsStatsRt()) {
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000701 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
702 TC.getCompilerRT(Args, "stats_client")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000703
704 // The main executable must export the stats runtime.
705 // FIXME: Only exporting from the main executable (e.g. based on whether the
706 // translation unit defines main()) would save a little space, but having
707 // multiple copies of the runtime shouldn't hurt.
Vedant Kumar5fb00e42016-07-27 23:01:55 +0000708 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
709 TC.getCompilerRT(Args, "stats")));
Evgeniy Stepanov5c063c12016-06-14 23:21:19 +0000710 addIncludeLinkerOption(TC, Args, CmdArgs, "__sanitizer_stats_register");
711 }
712
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000713 if (Sanitizers.empty())
Alexey Samsonovcf055962013-08-08 10:11:02 +0000714 return;
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000715 CmdArgs.push_back(Args.MakeArgString("-fsanitize=" + toString(Sanitizers)));
716
Alexey Samsonov88459522015-01-12 22:39:12 +0000717 if (!RecoverableSanitizers.empty())
718 CmdArgs.push_back(Args.MakeArgString("-fsanitize-recover=" +
719 toString(RecoverableSanitizers)));
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000720
Peter Collingbourne9881b782015-06-18 23:59:22 +0000721 if (!TrapSanitizers.empty())
722 CmdArgs.push_back(
723 Args.MakeArgString("-fsanitize-trap=" + toString(TrapSanitizers)));
Alexey Samsonov1e715a62014-11-16 20:53:53 +0000724
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000725 for (const auto &BLPath : BlacklistFiles) {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000726 SmallString<64> BlacklistOpt("-fsanitize-blacklist=");
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000727 BlacklistOpt += BLPath;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000728 CmdArgs.push_back(Args.MakeArgString(BlacklistOpt));
729 }
Ivan Krasin4c3f2372015-09-02 20:02:38 +0000730 for (const auto &Dep : ExtraDeps) {
731 SmallString<64> ExtraDepOpt("-fdepfile-entry=");
732 ExtraDepOpt += Dep;
733 CmdArgs.push_back(Args.MakeArgString(ExtraDepOpt));
734 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000735
736 if (MsanTrackOrigins)
Evgeniy Stepanov2bfcaab2014-03-20 14:58:36 +0000737 CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins=" +
738 llvm::utostr(MsanTrackOrigins)));
Evgeniy Stepanov45be9e02015-07-10 20:07:16 +0000739
740 if (MsanUseAfterDtor)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000741 CmdArgs.push_back("-fsanitize-memory-use-after-dtor");
Evgeniy Stepanov45be9e02015-07-10 20:07:16 +0000742
Evgeniy Stepanov8a2bedb2016-11-11 23:17:36 +0000743 // FIXME: Pass these parameters as function attributes, not as -llvm flags.
744 if (!TsanMemoryAccess) {
745 CmdArgs.push_back("-mllvm");
746 CmdArgs.push_back("-tsan-instrument-memory-accesses=0");
747 CmdArgs.push_back("-mllvm");
748 CmdArgs.push_back("-tsan-instrument-memintrinsics=0");
749 }
750 if (!TsanFuncEntryExit) {
751 CmdArgs.push_back("-mllvm");
752 CmdArgs.push_back("-tsan-instrument-func-entry-exit=0");
753 }
754 if (!TsanAtomics) {
755 CmdArgs.push_back("-mllvm");
756 CmdArgs.push_back("-tsan-instrument-atomics=0");
757 }
758
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000759 if (CfiCrossDso)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000760 CmdArgs.push_back("-fsanitize-cfi-cross-dso");
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000761
Peter Collingbournedc134532016-01-16 00:31:22 +0000762 if (Stats)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000763 CmdArgs.push_back("-fsanitize-stats");
Peter Collingbournedc134532016-01-16 00:31:22 +0000764
Kostya Serebryanyaed71a82014-10-09 17:53:04 +0000765 if (AsanFieldPadding)
766 CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-field-padding=" +
767 llvm::utostr(AsanFieldPadding)));
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000768
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000769 if (AsanUseAfterScope)
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000770 CmdArgs.push_back("-fsanitize-address-use-after-scope");
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000771
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000772 if (AsanGlobalsDeadStripping)
773 CmdArgs.push_back("-fsanitize-address-globals-dead-stripping");
774
Sergey Matveev2ba87782015-02-17 15:09:33 +0000775 // MSan: Workaround for PR16386.
776 // ASan: This is mainly to help LSan with cases such as
777 // https://code.google.com/p/address-sanitizer/issues/detail?id=373
778 // We can't make this conditional on -fsanitize=leak, as that flag shouldn't
779 // affect compilation.
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000780 if (Sanitizers.has(Memory) || Sanitizers.has(Address))
Evgeniy Stepanovb86ca112017-05-09 21:57:39 +0000781 CmdArgs.push_back("-fno-assume-sane-operator-new");
Peter Collingbourne581f4382015-07-02 01:48:12 +0000782
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000783 // Require -fvisibility= flag on non-Windows when compiling if vptr CFI is
784 // enabled.
785 if (Sanitizers.hasOneOf(CFIClasses) && !TC.getTriple().isOSWindows() &&
786 !Args.hasArg(options::OPT_fvisibility_EQ)) {
787 TC.getDriver().Diag(clang::diag::err_drv_argument_only_allowed_with)
788 << lastArgumentForMask(TC.getDriver(), Args,
789 Sanitizers.Mask & CFIClasses)
790 << "-fvisibility=";
791 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000792}
793
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000794SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
795 bool DiagnoseErrors) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000796 assert((A->getOption().matches(options::OPT_fsanitize_EQ) ||
Alexey Samsonov88459522015-01-12 22:39:12 +0000797 A->getOption().matches(options::OPT_fno_sanitize_EQ) ||
798 A->getOption().matches(options::OPT_fsanitize_recover_EQ) ||
Peter Collingbourne9881b782015-06-18 23:59:22 +0000799 A->getOption().matches(options::OPT_fno_sanitize_recover_EQ) ||
800 A->getOption().matches(options::OPT_fsanitize_trap_EQ) ||
801 A->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) &&
Alexey Samsonov799f7932014-12-19 02:35:16 +0000802 "Invalid argument in parseArgValues!");
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000803 SanitizerMask Kinds = 0;
Alexey Samsonov83791e22015-03-03 22:15:32 +0000804 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
805 const char *Value = A->getValue(i);
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000806 SanitizerMask Kind;
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000807 // Special case: don't accept -fsanitize=all.
808 if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
809 0 == strcmp("all", Value))
810 Kind = 0;
Derek Bruening256c2e12016-04-21 21:32:04 +0000811 // Similarly, don't accept -fsanitize=efficiency-all.
812 else if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
813 0 == strcmp("efficiency-all", Value))
814 Kind = 0;
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000815 else
Peter Collingbournebf59c342015-05-11 21:39:20 +0000816 Kind = parseSanitizerValue(Value, /*AllowGroups=*/true);
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000817
818 if (Kind)
819 Kinds |= Kind;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000820 else if (DiagnoseErrors)
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000821 D.Diag(clang::diag::err_drv_unsupported_option_argument)
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000822 << A->getOption().getName() << Value;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000823 }
Alexey Samsonovabd5bea2014-12-19 18:41:43 +0000824 return Kinds;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000825}
826
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000827int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A) {
828 assert(A->getOption().matches(options::OPT_fsanitize_coverage) ||
829 A->getOption().matches(options::OPT_fno_sanitize_coverage));
830 int Features = 0;
831 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
832 const char *Value = A->getValue(i);
833 int F = llvm::StringSwitch<int>(Value)
834 .Case("func", CoverageFunc)
835 .Case("bb", CoverageBB)
836 .Case("edge", CoverageEdge)
837 .Case("indirect-calls", CoverageIndirCall)
838 .Case("trace-bb", CoverageTraceBB)
839 .Case("trace-cmp", CoverageTraceCmp)
Kostya Serebryany3b419712016-08-30 01:27:03 +0000840 .Case("trace-div", CoverageTraceDiv)
841 .Case("trace-gep", CoverageTraceGep)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000842 .Case("8bit-counters", Coverage8bitCounters)
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000843 .Case("trace-pc", CoverageTracePC)
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000844 .Case("trace-pc-guard", CoverageTracePCGuard)
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000845 .Case("no-prune", CoverageNoPrune)
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000846 .Case("inline-8bit-counters", CoverageInline8bitCounters)
Kostya Serebryany61457762017-07-28 00:10:10 +0000847 .Case("pc-table", CoveragePCTable)
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000848 .Case("stack-depth", CoverageStackDepth)
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000849 .Default(0);
850 if (F == 0)
851 D.Diag(clang::diag::err_drv_unsupported_option_argument)
852 << A->getOption().getName() << Value;
853 Features |= F;
854 }
855 return Features;
856}
857
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000858std::string lastArgumentForMask(const Driver &D, const llvm::opt::ArgList &Args,
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000859 SanitizerMask Mask) {
Alexey Samsonovcf055962013-08-08 10:11:02 +0000860 for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(),
861 E = Args.rend();
862 I != E; ++I) {
Alexey Samsonov799f7932014-12-19 02:35:16 +0000863 const auto *Arg = *I;
864 if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000865 SanitizerMask AddKinds =
866 expandSanitizerGroups(parseArgValues(D, Arg, false));
Alexey Samsonov799f7932014-12-19 02:35:16 +0000867 if (AddKinds & Mask)
868 return describeSanitizeArg(Arg, Mask);
869 } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000870 SanitizerMask RemoveKinds =
871 expandSanitizerGroups(parseArgValues(D, Arg, false));
Alexey Samsonov799f7932014-12-19 02:35:16 +0000872 Mask &= ~RemoveKinds;
873 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000874 }
875 llvm_unreachable("arg list didn't provide expected value");
876}
877
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000878std::string describeSanitizeArg(const llvm::opt::Arg *A, SanitizerMask Mask) {
Alexey Samsonov4c12c6c2014-11-14 02:59:20 +0000879 assert(A->getOption().matches(options::OPT_fsanitize_EQ)
880 && "Invalid argument in describeSanitizerArg!");
Alexey Samsonovcf055962013-08-08 10:11:02 +0000881
Peter Collingbourne32701642013-11-01 18:16:25 +0000882 std::string Sanitizers;
Alexey Samsonov83791e22015-03-03 22:15:32 +0000883 for (int i = 0, n = A->getNumValues(); i != n; ++i) {
Peter Collingbournebf59c342015-05-11 21:39:20 +0000884 if (expandSanitizerGroups(
885 parseSanitizerValue(A->getValue(i), /*AllowGroups=*/true)) &
886 Mask) {
Peter Collingbourne32701642013-11-01 18:16:25 +0000887 if (!Sanitizers.empty())
888 Sanitizers += ",";
Alexey Samsonov83791e22015-03-03 22:15:32 +0000889 Sanitizers += A->getValue(i);
Peter Collingbourne32701642013-11-01 18:16:25 +0000890 }
891 }
Alexey Samsonovcf055962013-08-08 10:11:02 +0000892
Peter Collingbourne32701642013-11-01 18:16:25 +0000893 assert(!Sanitizers.empty() && "arg didn't provide expected value");
894 return "-fsanitize=" + Sanitizers;
Alexey Samsonovcf055962013-08-08 10:11:02 +0000895}