Coverage Report

Created: 2020-09-15 12:33

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