Coverage Report

Created: 2020-02-18 08:44

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