diff --git a/clang/lib/Driver/SanitizerArgs.cpp b/clang/lib/Driver/SanitizerArgs.cpp index a37d0b64cbe4..7086ee382ef5 100644 --- a/clang/lib/Driver/SanitizerArgs.cpp +++ b/clang/lib/Driver/SanitizerArgs.cpp @@ -1,891 +1,892 @@ //===--- SanitizerArgs.cpp - Arguments for sanitizer tools ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Driver/SanitizerArgs.h" #include "ToolChains/CommonArgs.h" #include "clang/Basic/Sanitizers.h" #include "clang/Driver/Driver.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Options.h" #include "clang/Driver/ToolChain.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/SpecialCaseList.h" #include using namespace clang; using namespace clang::SanitizerKind; using namespace clang::driver; using namespace llvm::opt; enum : SanitizerMask { NeedsUbsanRt = Undefined | Integer | Nullability | CFI, NeedsUbsanCxxRt = Vptr | CFI, NotAllowedWithTrap = Vptr, RequiresPIE = DataFlow, NeedsUnwindTables = Address | Thread | Memory | DataFlow, SupportsCoverage = Address | KernelAddress | Memory | Leak | Undefined | Integer | Nullability | DataFlow | Fuzzer | FuzzerNoLink, RecoverableByDefault = Undefined | Integer | Nullability, Unrecoverable = Unreachable | Return, LegacyFsanitizeRecoverMask = Undefined | Integer, NeedsLTO = CFI, TrappingSupported = (Undefined & ~Vptr) | UnsignedIntegerOverflow | Nullability | LocalBounds | CFI, TrappingDefault = CFI, CFIClasses = CFIVCall | CFINVCall | CFIDerivedCast | CFIUnrelatedCast, }; enum CoverageFeature { CoverageFunc = 1 << 0, CoverageBB = 1 << 1, CoverageEdge = 1 << 2, CoverageIndirCall = 1 << 3, CoverageTraceBB = 1 << 4, // Deprecated. CoverageTraceCmp = 1 << 5, CoverageTraceDiv = 1 << 6, CoverageTraceGep = 1 << 7, Coverage8bitCounters = 1 << 8, // Deprecated. CoverageTracePC = 1 << 9, CoverageTracePCGuard = 1 << 10, CoverageNoPrune = 1 << 11, CoverageInline8bitCounters = 1 << 12, CoveragePCTable = 1 << 13, CoverageStackDepth = 1 << 14, }; /// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any /// invalid components. Returns a SanitizerMask. static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A, bool DiagnoseErrors); /// Parse -f(no-)?sanitize-coverage= flag values, diagnosing any invalid /// components. Returns OR of members of \c CoverageFeature enumeration. static int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A); /// Produce an argument string from ArgList \p Args, which shows how it /// provides some sanitizer kind from \p Mask. For example, the argument list /// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt /// would produce "-fsanitize=vptr". static std::string lastArgumentForMask(const Driver &D, const llvm::opt::ArgList &Args, SanitizerMask Mask); /// Produce an argument string from argument \p A, which shows how it provides /// a value in \p Mask. For instance, the argument /// "-fsanitize=address,alignment" with mask \c NeedsUbsanRt would produce /// "-fsanitize=alignment". static std::string describeSanitizeArg(const llvm::opt::Arg *A, SanitizerMask Mask); /// Produce a string containing comma-separated names of sanitizers in \p /// Sanitizers set. static std::string toString(const clang::SanitizerSet &Sanitizers); static bool getDefaultBlacklist(const Driver &D, SanitizerMask Kinds, std::string &BLPath) { const char *BlacklistFile = nullptr; if (Kinds & Address) BlacklistFile = "asan_blacklist.txt"; else if (Kinds & Memory) BlacklistFile = "msan_blacklist.txt"; else if (Kinds & Thread) BlacklistFile = "tsan_blacklist.txt"; else if (Kinds & DataFlow) BlacklistFile = "dfsan_abilist.txt"; else if (Kinds & CFI) BlacklistFile = "cfi_blacklist.txt"; else if (Kinds & Undefined) BlacklistFile = "ubsan_blacklist.txt"; if (BlacklistFile) { clang::SmallString<64> Path(D.ResourceDir); llvm::sys::path::append(Path, BlacklistFile); BLPath = Path.str(); return true; } return false; } /// Sets group bits for every group that has at least one representative already /// enabled in \p Kinds. static SanitizerMask setGroupBits(SanitizerMask Kinds) { #define SANITIZER(NAME, ID) #define SANITIZER_GROUP(NAME, ID, ALIAS) \ if (Kinds & SanitizerKind::ID) \ Kinds |= SanitizerKind::ID##Group; #include "clang/Basic/Sanitizers.def" return Kinds; } static SanitizerMask parseSanitizeTrapArgs(const Driver &D, const llvm::opt::ArgList &Args) { SanitizerMask TrapRemove = 0; // During the loop below, the accumulated set of // sanitizers disabled by the current sanitizer // argument or any argument after it. SanitizerMask TrappingKinds = 0; SanitizerMask TrappingSupportedWithGroups = setGroupBits(TrappingSupported); for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend(); I != E; ++I) { const auto *Arg = *I; if (Arg->getOption().matches(options::OPT_fsanitize_trap_EQ)) { Arg->claim(); SanitizerMask Add = parseArgValues(D, Arg, true); Add &= ~TrapRemove; if (SanitizerMask InvalidValues = Add & ~TrappingSupportedWithGroups) { SanitizerSet S; S.Mask = InvalidValues; D.Diag(diag::err_drv_unsupported_option_argument) << "-fsanitize-trap" << toString(S); } TrappingKinds |= expandSanitizerGroups(Add) & ~TrapRemove; } else if (Arg->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) { Arg->claim(); TrapRemove |= expandSanitizerGroups(parseArgValues(D, Arg, true)); } else if (Arg->getOption().matches( options::OPT_fsanitize_undefined_trap_on_error)) { Arg->claim(); TrappingKinds |= expandSanitizerGroups(UndefinedGroup & ~TrapRemove) & ~TrapRemove; } else if (Arg->getOption().matches( options::OPT_fno_sanitize_undefined_trap_on_error)) { Arg->claim(); TrapRemove |= expandSanitizerGroups(UndefinedGroup); } } // Apply default trapping behavior. TrappingKinds |= TrappingDefault & ~TrapRemove; return TrappingKinds; } bool SanitizerArgs::needsUbsanRt() const { return ((Sanitizers.Mask & NeedsUbsanRt & ~TrapSanitizers.Mask) || CoverageFeatures) && !Sanitizers.has(Address) && !Sanitizers.has(Memory) && !Sanitizers.has(Thread) && !Sanitizers.has(DataFlow) && !Sanitizers.has(Leak) && !CfiCrossDso; } bool SanitizerArgs::needsCfiRt() const { return !(Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso; } bool SanitizerArgs::needsCfiDiagRt() const { return (Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso; } bool SanitizerArgs::requiresPIE() const { return NeedPIE || (Sanitizers.Mask & RequiresPIE); } bool SanitizerArgs::needsUnwindTables() const { return Sanitizers.Mask & NeedsUnwindTables; } SanitizerArgs::SanitizerArgs(const ToolChain &TC, const llvm::opt::ArgList &Args) { SanitizerMask AllRemove = 0; // During the loop below, the accumulated set of // sanitizers disabled by the current sanitizer // argument or any argument after it. SanitizerMask AllAddedKinds = 0; // Mask of all sanitizers ever enabled by // -fsanitize= flags (directly or via group // expansion), some of which may be disabled // later. Used to carefully prune // unused-argument diagnostics. SanitizerMask DiagnosedKinds = 0; // All Kinds we have diagnosed up to now. // Used to deduplicate diagnostics. SanitizerMask Kinds = 0; const SanitizerMask Supported = setGroupBits(TC.getSupportedSanitizers()); ToolChain::RTTIMode RTTIMode = TC.getRTTIMode(); const Driver &D = TC.getDriver(); SanitizerMask TrappingKinds = parseSanitizeTrapArgs(D, Args); SanitizerMask InvalidTrappingKinds = TrappingKinds & NotAllowedWithTrap; // The object size sanitizer should not be enabled at -O0. Arg *OptLevel = Args.getLastArg(options::OPT_O_Group); bool RemoveObjectSizeAtO0 = !OptLevel || OptLevel->getOption().matches(options::OPT_O0); for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend(); I != E; ++I) { const auto *Arg = *I; if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) { Arg->claim(); SanitizerMask Add = parseArgValues(D, Arg, /*AllowGroups=*/true); if (RemoveObjectSizeAtO0) { AllRemove |= SanitizerKind::ObjectSize; // The user explicitly enabled the object size sanitizer. Warn that // that this does nothing at -O0. if (Add & SanitizerKind::ObjectSize) D.Diag(diag::warn_drv_object_size_disabled_O0) << Arg->getAsString(Args); } AllAddedKinds |= expandSanitizerGroups(Add); // Avoid diagnosing any sanitizer which is disabled later. Add &= ~AllRemove; // At this point we have not expanded groups, so any unsupported // sanitizers in Add are those which have been explicitly enabled. // Diagnose them. if (SanitizerMask KindsToDiagnose = Add & InvalidTrappingKinds & ~DiagnosedKinds) { std::string Desc = describeSanitizeArg(*I, KindsToDiagnose); D.Diag(diag::err_drv_argument_not_allowed_with) << Desc << "-fsanitize-trap=undefined"; DiagnosedKinds |= KindsToDiagnose; } Add &= ~InvalidTrappingKinds; if (SanitizerMask KindsToDiagnose = Add & ~Supported & ~DiagnosedKinds) { std::string Desc = describeSanitizeArg(*I, KindsToDiagnose); D.Diag(diag::err_drv_unsupported_opt_for_target) << Desc << TC.getTriple().str(); DiagnosedKinds |= KindsToDiagnose; } Add &= Supported; // Test for -fno-rtti + explicit -fsanitizer=vptr before expanding groups // so we don't error out if -fno-rtti and -fsanitize=undefined were // passed. if (Add & Vptr && (RTTIMode == ToolChain::RM_DisabledImplicitly || RTTIMode == ToolChain::RM_DisabledExplicitly)) { if (RTTIMode == ToolChain::RM_DisabledImplicitly) // Warn about not having rtti enabled if the vptr sanitizer is // explicitly enabled D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default); else { const llvm::opt::Arg *NoRTTIArg = TC.getRTTIArg(); assert(NoRTTIArg && "RTTI disabled explicitly but we have no argument!"); D.Diag(diag::err_drv_argument_not_allowed_with) << "-fsanitize=vptr" << NoRTTIArg->getAsString(Args); } // Take out the Vptr sanitizer from the enabled sanitizers AllRemove |= Vptr; } Add = expandSanitizerGroups(Add); // Group expansion may have enabled a sanitizer which is disabled later. Add &= ~AllRemove; // Silently discard any unsupported sanitizers implicitly enabled through // group expansion. Add &= ~InvalidTrappingKinds; Add &= Supported; if (Add & Fuzzer) Add |= FuzzerNoLink; - // Enable coverage if the fuzzing flag is set. + // Enable coverage and stack depth tracking if the fuzzing flag is set. if (Add & FuzzerNoLink) CoverageFeatures |= CoverageTracePCGuard | CoverageIndirCall | - CoverageTraceCmp | CoveragePCTable; + CoverageTraceCmp | CoveragePCTable | + CoverageStackDepth; Kinds |= Add; } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) { Arg->claim(); SanitizerMask Remove = parseArgValues(D, Arg, true); AllRemove |= expandSanitizerGroups(Remove); } } // Enable toolchain specific default sanitizers if not explicitly disabled. Kinds |= TC.getDefaultSanitizers() & ~AllRemove; // We disable the vptr sanitizer if it was enabled by group expansion but RTTI // is disabled. if ((Kinds & Vptr) && (RTTIMode == ToolChain::RM_DisabledImplicitly || RTTIMode == ToolChain::RM_DisabledExplicitly)) { Kinds &= ~Vptr; } // Check that LTO is enabled if we need it. if ((Kinds & NeedsLTO) && !D.isUsingLTO()) { D.Diag(diag::err_drv_argument_only_allowed_with) << lastArgumentForMask(D, Args, Kinds & NeedsLTO) << "-flto"; } // Report error if there are non-trapping sanitizers that require // c++abi-specific parts of UBSan runtime, and they are not provided by the // toolchain. We don't have a good way to check the latter, so we just // check if the toolchan supports vptr. if (~Supported & Vptr) { SanitizerMask KindsToDiagnose = Kinds & ~TrappingKinds & NeedsUbsanCxxRt; // The runtime library supports the Microsoft C++ ABI, but only well enough // for CFI. FIXME: Remove this once we support vptr on Windows. if (TC.getTriple().isOSWindows()) KindsToDiagnose &= ~CFI; if (KindsToDiagnose) { SanitizerSet S; S.Mask = KindsToDiagnose; D.Diag(diag::err_drv_unsupported_opt_for_target) << ("-fno-sanitize-trap=" + toString(S)) << TC.getTriple().str(); Kinds &= ~KindsToDiagnose; } } // Warn about incompatible groups of sanitizers. std::pair IncompatibleGroups[] = { std::make_pair(Address, Thread), std::make_pair(Address, Memory), std::make_pair(Thread, Memory), std::make_pair(Leak, Thread), std::make_pair(Leak, Memory), std::make_pair(KernelAddress, Address), std::make_pair(KernelAddress, Leak), std::make_pair(KernelAddress, Thread), std::make_pair(KernelAddress, Memory), std::make_pair(Efficiency, Address), std::make_pair(Efficiency, Leak), std::make_pair(Efficiency, Thread), std::make_pair(Efficiency, Memory), std::make_pair(Efficiency, KernelAddress)}; for (auto G : IncompatibleGroups) { SanitizerMask Group = G.first; if (Kinds & Group) { if (SanitizerMask Incompatible = Kinds & G.second) { D.Diag(clang::diag::err_drv_argument_not_allowed_with) << lastArgumentForMask(D, Args, Group) << lastArgumentForMask(D, Args, Incompatible); Kinds &= ~Incompatible; } } } // FIXME: Currently -fsanitize=leak is silently ignored in the presence of // -fsanitize=address. Perhaps it should print an error, or perhaps // -f(-no)sanitize=leak should change whether leak detection is enabled by // default in ASan? // Parse -f(no-)?sanitize-recover flags. SanitizerMask RecoverableKinds = RecoverableByDefault; SanitizerMask DiagnosedUnrecoverableKinds = 0; for (const auto *Arg : Args) { const char *DeprecatedReplacement = nullptr; if (Arg->getOption().matches(options::OPT_fsanitize_recover)) { DeprecatedReplacement = "-fsanitize-recover=undefined,integer' or '-fsanitize-recover=all"; RecoverableKinds |= expandSanitizerGroups(LegacyFsanitizeRecoverMask); Arg->claim(); } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover)) { DeprecatedReplacement = "-fno-sanitize-recover=undefined,integer' or " "'-fno-sanitize-recover=all"; RecoverableKinds &= ~expandSanitizerGroups(LegacyFsanitizeRecoverMask); Arg->claim(); } else if (Arg->getOption().matches(options::OPT_fsanitize_recover_EQ)) { SanitizerMask Add = parseArgValues(D, Arg, true); // Report error if user explicitly tries to recover from unrecoverable // sanitizer. if (SanitizerMask KindsToDiagnose = Add & Unrecoverable & ~DiagnosedUnrecoverableKinds) { SanitizerSet SetToDiagnose; SetToDiagnose.Mask |= KindsToDiagnose; D.Diag(diag::err_drv_unsupported_option_argument) << Arg->getOption().getName() << toString(SetToDiagnose); DiagnosedUnrecoverableKinds |= KindsToDiagnose; } RecoverableKinds |= expandSanitizerGroups(Add); Arg->claim(); } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) { RecoverableKinds &= ~expandSanitizerGroups(parseArgValues(D, Arg, true)); Arg->claim(); } if (DeprecatedReplacement) { D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args) << DeprecatedReplacement; } } RecoverableKinds &= Kinds; RecoverableKinds &= ~Unrecoverable; TrappingKinds &= Kinds; // Setup blacklist files. // Add default blacklist from resource directory. { std::string BLPath; if (getDefaultBlacklist(D, Kinds, BLPath) && llvm::sys::fs::exists(BLPath)) BlacklistFiles.push_back(BLPath); } // Parse -f(no-)sanitize-blacklist options. for (const auto *Arg : Args) { if (Arg->getOption().matches(options::OPT_fsanitize_blacklist)) { Arg->claim(); std::string BLPath = Arg->getValue(); if (llvm::sys::fs::exists(BLPath)) { BlacklistFiles.push_back(BLPath); ExtraDeps.push_back(BLPath); } else D.Diag(clang::diag::err_drv_no_such_file) << BLPath; } else if (Arg->getOption().matches(options::OPT_fno_sanitize_blacklist)) { Arg->claim(); BlacklistFiles.clear(); ExtraDeps.clear(); } } // Validate blacklists format. { std::string BLError; std::unique_ptr SCL( llvm::SpecialCaseList::create(BlacklistFiles, BLError)); if (!SCL.get()) D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError; } // Parse -f[no-]sanitize-memory-track-origins[=level] options. if (AllAddedKinds & Memory) { if (Arg *A = Args.getLastArg(options::OPT_fsanitize_memory_track_origins_EQ, options::OPT_fsanitize_memory_track_origins, options::OPT_fno_sanitize_memory_track_origins)) { if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) { MsanTrackOrigins = 2; } else if (A->getOption().matches( options::OPT_fno_sanitize_memory_track_origins)) { MsanTrackOrigins = 0; } else { StringRef S = A->getValue(); if (S.getAsInteger(0, MsanTrackOrigins) || MsanTrackOrigins < 0 || MsanTrackOrigins > 2) { D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S; } } } MsanUseAfterDtor = Args.hasArg(options::OPT_fsanitize_memory_use_after_dtor); NeedPIE |= !(TC.getTriple().isOSLinux() && TC.getTriple().getArch() == llvm::Triple::x86_64); } if (AllAddedKinds & Thread) { TsanMemoryAccess = Args.hasFlag(options::OPT_fsanitize_thread_memory_access, options::OPT_fno_sanitize_thread_memory_access, TsanMemoryAccess); TsanFuncEntryExit = Args.hasFlag(options::OPT_fsanitize_thread_func_entry_exit, options::OPT_fno_sanitize_thread_func_entry_exit, TsanFuncEntryExit); TsanAtomics = Args.hasFlag(options::OPT_fsanitize_thread_atomics, options::OPT_fno_sanitize_thread_atomics, TsanAtomics); } if (AllAddedKinds & CFI) { CfiCrossDso = Args.hasFlag(options::OPT_fsanitize_cfi_cross_dso, options::OPT_fno_sanitize_cfi_cross_dso, false); // Without PIE, external function address may resolve to a PLT record, which // can not be verified by the target module. NeedPIE |= CfiCrossDso; } Stats = Args.hasFlag(options::OPT_fsanitize_stats, options::OPT_fno_sanitize_stats, false); // Parse -f(no-)?sanitize-coverage flags if coverage is supported by the // enabled sanitizers. for (const auto *Arg : Args) { if (Arg->getOption().matches(options::OPT_fsanitize_coverage)) { int LegacySanitizeCoverage; if (Arg->getNumValues() == 1 && !StringRef(Arg->getValue(0)) .getAsInteger(0, LegacySanitizeCoverage)) { CoverageFeatures = 0; Arg->claim(); if (LegacySanitizeCoverage != 0) { D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args) << "-fsanitize-coverage=trace-pc-guard"; } continue; } CoverageFeatures |= parseCoverageFeatures(D, Arg); // Disable coverage and not claim the flags if there is at least one // non-supporting sanitizer. if (!(AllAddedKinds & ~AllRemove & ~setGroupBits(SupportsCoverage))) { Arg->claim(); } else { CoverageFeatures = 0; } } else if (Arg->getOption().matches(options::OPT_fno_sanitize_coverage)) { Arg->claim(); CoverageFeatures &= ~parseCoverageFeatures(D, Arg); } } // Choose at most one coverage type: function, bb, or edge. if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageBB)) D.Diag(clang::diag::err_drv_argument_not_allowed_with) << "-fsanitize-coverage=func" << "-fsanitize-coverage=bb"; if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageEdge)) D.Diag(clang::diag::err_drv_argument_not_allowed_with) << "-fsanitize-coverage=func" << "-fsanitize-coverage=edge"; if ((CoverageFeatures & CoverageBB) && (CoverageFeatures & CoverageEdge)) D.Diag(clang::diag::err_drv_argument_not_allowed_with) << "-fsanitize-coverage=bb" << "-fsanitize-coverage=edge"; // Basic block tracing and 8-bit counters require some type of coverage // enabled. if (CoverageFeatures & CoverageTraceBB) D.Diag(clang::diag::warn_drv_deprecated_arg) << "-fsanitize-coverage=trace-bb" << "-fsanitize-coverage=trace-pc-guard"; if (CoverageFeatures & Coverage8bitCounters) D.Diag(clang::diag::warn_drv_deprecated_arg) << "-fsanitize-coverage=8bit-counters" << "-fsanitize-coverage=trace-pc-guard"; int InsertionPointTypes = CoverageFunc | CoverageBB | CoverageEdge; int InstrumentationTypes = CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters; if ((CoverageFeatures & InsertionPointTypes) && !(CoverageFeatures & InstrumentationTypes)) { D.Diag(clang::diag::warn_drv_deprecated_arg) << "-fsanitize-coverage=[func|bb|edge]" << "-fsanitize-coverage=[func|bb|edge],[trace-pc-guard|trace-pc]"; } // trace-pc w/o func/bb/edge implies edge. if (!(CoverageFeatures & InsertionPointTypes)) { if (CoverageFeatures & (CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters)) CoverageFeatures |= CoverageEdge; if (CoverageFeatures & CoverageStackDepth) CoverageFeatures |= CoverageFunc; } if (AllAddedKinds & Address) { AsanSharedRuntime = Args.hasArg(options::OPT_shared_libasan) || TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia(); NeedPIE |= TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia(); if (Arg *A = Args.getLastArg(options::OPT_fsanitize_address_field_padding)) { StringRef S = A->getValue(); // Legal values are 0 and 1, 2, but in future we may add more levels. if (S.getAsInteger(0, AsanFieldPadding) || AsanFieldPadding < 0 || AsanFieldPadding > 2) { D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S; } } if (Arg *WindowsDebugRTArg = Args.getLastArg(options::OPT__SLASH_MTd, options::OPT__SLASH_MT, options::OPT__SLASH_MDd, options::OPT__SLASH_MD, options::OPT__SLASH_LDd, options::OPT__SLASH_LD)) { switch (WindowsDebugRTArg->getOption().getID()) { case options::OPT__SLASH_MTd: case options::OPT__SLASH_MDd: case options::OPT__SLASH_LDd: D.Diag(clang::diag::err_drv_argument_not_allowed_with) << WindowsDebugRTArg->getAsString(Args) << lastArgumentForMask(D, Args, Address); D.Diag(clang::diag::note_drv_address_sanitizer_debug_runtime); } } AsanUseAfterScope = Args.hasFlag( options::OPT_fsanitize_address_use_after_scope, options::OPT_fno_sanitize_address_use_after_scope, AsanUseAfterScope); // As a workaround for a bug in gold 2.26 and earlier, dead stripping of // globals in ASan is disabled by default on ELF targets. // See https://sourceware.org/bugzilla/show_bug.cgi?id=19002 AsanGlobalsDeadStripping = !TC.getTriple().isOSBinFormatELF() || TC.getTriple().isOSFuchsia() || Args.hasArg(options::OPT_fsanitize_address_globals_dead_stripping); } else { AsanUseAfterScope = false; } if (AllAddedKinds & SafeStack) { // SafeStack runtime is built into the system on Fuchsia. SafeStackRuntime = !TC.getTriple().isOSFuchsia(); } // Parse -link-cxx-sanitizer flag. LinkCXXRuntimes = Args.hasArg(options::OPT_fsanitize_link_cxx_runtime) || D.CCCIsCXX(); // Finally, initialize the set of available and recoverable sanitizers. Sanitizers.Mask |= Kinds; RecoverableSanitizers.Mask |= RecoverableKinds; TrapSanitizers.Mask |= TrappingKinds; } static std::string toString(const clang::SanitizerSet &Sanitizers) { std::string Res; #define SANITIZER(NAME, ID) \ if (Sanitizers.has(ID)) { \ if (!Res.empty()) \ Res += ","; \ Res += NAME; \ } #include "clang/Basic/Sanitizers.def" return Res; } static void addIncludeLinkerOption(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, StringRef SymbolName) { SmallString<64> LinkerOptionFlag; LinkerOptionFlag = "--linker-option=/include:"; if (TC.getTriple().getArch() == llvm::Triple::x86) { // Win32 mangles C function names with a '_' prefix. LinkerOptionFlag += '_'; } LinkerOptionFlag += SymbolName; CmdArgs.push_back(Args.MakeArgString(LinkerOptionFlag)); } void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, types::ID InputType) const { // NVPTX doesn't currently support sanitizers. Bailing out here means that // e.g. -fsanitize=address applies only to host code, which is what we want // for now. if (TC.getTriple().isNVPTX()) return; // Translate available CoverageFeatures to corresponding clang-cc1 flags. // Do it even if Sanitizers.empty() since some forms of coverage don't require // sanitizers. std::pair CoverageFlags[] = { std::make_pair(CoverageFunc, "-fsanitize-coverage-type=1"), std::make_pair(CoverageBB, "-fsanitize-coverage-type=2"), std::make_pair(CoverageEdge, "-fsanitize-coverage-type=3"), std::make_pair(CoverageIndirCall, "-fsanitize-coverage-indirect-calls"), std::make_pair(CoverageTraceBB, "-fsanitize-coverage-trace-bb"), std::make_pair(CoverageTraceCmp, "-fsanitize-coverage-trace-cmp"), std::make_pair(CoverageTraceDiv, "-fsanitize-coverage-trace-div"), std::make_pair(CoverageTraceGep, "-fsanitize-coverage-trace-gep"), std::make_pair(Coverage8bitCounters, "-fsanitize-coverage-8bit-counters"), std::make_pair(CoverageTracePC, "-fsanitize-coverage-trace-pc"), std::make_pair(CoverageTracePCGuard, "-fsanitize-coverage-trace-pc-guard"), std::make_pair(CoverageInline8bitCounters, "-fsanitize-coverage-inline-8bit-counters"), std::make_pair(CoveragePCTable, "-fsanitize-coverage-pc-table"), std::make_pair(CoverageNoPrune, "-fsanitize-coverage-no-prune"), std::make_pair(CoverageStackDepth, "-fsanitize-coverage-stack-depth")}; for (auto F : CoverageFlags) { if (CoverageFeatures & F.first) CmdArgs.push_back(F.second); } if (TC.getTriple().isOSWindows() && needsUbsanRt()) { // Instruct the code generator to embed linker directives in the object file // that cause the required runtime libraries to be linked. CmdArgs.push_back(Args.MakeArgString( "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone"))); if (types::isCXX(InputType)) CmdArgs.push_back(Args.MakeArgString( "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone_cxx"))); } if (TC.getTriple().isOSWindows() && needsStatsRt()) { CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" + TC.getCompilerRT(Args, "stats_client"))); // The main executable must export the stats runtime. // FIXME: Only exporting from the main executable (e.g. based on whether the // translation unit defines main()) would save a little space, but having // multiple copies of the runtime shouldn't hurt. CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" + TC.getCompilerRT(Args, "stats"))); addIncludeLinkerOption(TC, Args, CmdArgs, "__sanitizer_stats_register"); } if (Sanitizers.empty()) return; CmdArgs.push_back(Args.MakeArgString("-fsanitize=" + toString(Sanitizers))); if (!RecoverableSanitizers.empty()) CmdArgs.push_back(Args.MakeArgString("-fsanitize-recover=" + toString(RecoverableSanitizers))); if (!TrapSanitizers.empty()) CmdArgs.push_back( Args.MakeArgString("-fsanitize-trap=" + toString(TrapSanitizers))); for (const auto &BLPath : BlacklistFiles) { SmallString<64> BlacklistOpt("-fsanitize-blacklist="); BlacklistOpt += BLPath; CmdArgs.push_back(Args.MakeArgString(BlacklistOpt)); } for (const auto &Dep : ExtraDeps) { SmallString<64> ExtraDepOpt("-fdepfile-entry="); ExtraDepOpt += Dep; CmdArgs.push_back(Args.MakeArgString(ExtraDepOpt)); } if (MsanTrackOrigins) CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins=" + llvm::utostr(MsanTrackOrigins))); if (MsanUseAfterDtor) CmdArgs.push_back("-fsanitize-memory-use-after-dtor"); // FIXME: Pass these parameters as function attributes, not as -llvm flags. if (!TsanMemoryAccess) { CmdArgs.push_back("-mllvm"); CmdArgs.push_back("-tsan-instrument-memory-accesses=0"); CmdArgs.push_back("-mllvm"); CmdArgs.push_back("-tsan-instrument-memintrinsics=0"); } if (!TsanFuncEntryExit) { CmdArgs.push_back("-mllvm"); CmdArgs.push_back("-tsan-instrument-func-entry-exit=0"); } if (!TsanAtomics) { CmdArgs.push_back("-mllvm"); CmdArgs.push_back("-tsan-instrument-atomics=0"); } if (CfiCrossDso) CmdArgs.push_back("-fsanitize-cfi-cross-dso"); if (Stats) CmdArgs.push_back("-fsanitize-stats"); if (AsanFieldPadding) CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-field-padding=" + llvm::utostr(AsanFieldPadding))); if (AsanUseAfterScope) CmdArgs.push_back("-fsanitize-address-use-after-scope"); if (AsanGlobalsDeadStripping) CmdArgs.push_back("-fsanitize-address-globals-dead-stripping"); // MSan: Workaround for PR16386. // ASan: This is mainly to help LSan with cases such as // https://code.google.com/p/address-sanitizer/issues/detail?id=373 // We can't make this conditional on -fsanitize=leak, as that flag shouldn't // affect compilation. if (Sanitizers.has(Memory) || Sanitizers.has(Address)) CmdArgs.push_back("-fno-assume-sane-operator-new"); // Require -fvisibility= flag on non-Windows when compiling if vptr CFI is // enabled. if (Sanitizers.hasOneOf(CFIClasses) && !TC.getTriple().isOSWindows() && !Args.hasArg(options::OPT_fvisibility_EQ)) { TC.getDriver().Diag(clang::diag::err_drv_argument_only_allowed_with) << lastArgumentForMask(TC.getDriver(), Args, Sanitizers.Mask & CFIClasses) << "-fvisibility="; } } SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A, bool DiagnoseErrors) { assert((A->getOption().matches(options::OPT_fsanitize_EQ) || A->getOption().matches(options::OPT_fno_sanitize_EQ) || A->getOption().matches(options::OPT_fsanitize_recover_EQ) || A->getOption().matches(options::OPT_fno_sanitize_recover_EQ) || A->getOption().matches(options::OPT_fsanitize_trap_EQ) || A->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) && "Invalid argument in parseArgValues!"); SanitizerMask Kinds = 0; for (int i = 0, n = A->getNumValues(); i != n; ++i) { const char *Value = A->getValue(i); SanitizerMask Kind; // Special case: don't accept -fsanitize=all. if (A->getOption().matches(options::OPT_fsanitize_EQ) && 0 == strcmp("all", Value)) Kind = 0; // Similarly, don't accept -fsanitize=efficiency-all. else if (A->getOption().matches(options::OPT_fsanitize_EQ) && 0 == strcmp("efficiency-all", Value)) Kind = 0; else Kind = parseSanitizerValue(Value, /*AllowGroups=*/true); if (Kind) Kinds |= Kind; else if (DiagnoseErrors) D.Diag(clang::diag::err_drv_unsupported_option_argument) << A->getOption().getName() << Value; } return Kinds; } int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A) { assert(A->getOption().matches(options::OPT_fsanitize_coverage) || A->getOption().matches(options::OPT_fno_sanitize_coverage)); int Features = 0; for (int i = 0, n = A->getNumValues(); i != n; ++i) { const char *Value = A->getValue(i); int F = llvm::StringSwitch(Value) .Case("func", CoverageFunc) .Case("bb", CoverageBB) .Case("edge", CoverageEdge) .Case("indirect-calls", CoverageIndirCall) .Case("trace-bb", CoverageTraceBB) .Case("trace-cmp", CoverageTraceCmp) .Case("trace-div", CoverageTraceDiv) .Case("trace-gep", CoverageTraceGep) .Case("8bit-counters", Coverage8bitCounters) .Case("trace-pc", CoverageTracePC) .Case("trace-pc-guard", CoverageTracePCGuard) .Case("no-prune", CoverageNoPrune) .Case("inline-8bit-counters", CoverageInline8bitCounters) .Case("pc-table", CoveragePCTable) .Case("stack-depth", CoverageStackDepth) .Default(0); if (F == 0) D.Diag(clang::diag::err_drv_unsupported_option_argument) << A->getOption().getName() << Value; Features |= F; } return Features; } std::string lastArgumentForMask(const Driver &D, const llvm::opt::ArgList &Args, SanitizerMask Mask) { for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend(); I != E; ++I) { const auto *Arg = *I; if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) { SanitizerMask AddKinds = expandSanitizerGroups(parseArgValues(D, Arg, false)); if (AddKinds & Mask) return describeSanitizeArg(Arg, Mask); } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) { SanitizerMask RemoveKinds = expandSanitizerGroups(parseArgValues(D, Arg, false)); Mask &= ~RemoveKinds; } } llvm_unreachable("arg list didn't provide expected value"); } std::string describeSanitizeArg(const llvm::opt::Arg *A, SanitizerMask Mask) { assert(A->getOption().matches(options::OPT_fsanitize_EQ) && "Invalid argument in describeSanitizerArg!"); std::string Sanitizers; for (int i = 0, n = A->getNumValues(); i != n; ++i) { if (expandSanitizerGroups( parseSanitizerValue(A->getValue(i), /*AllowGroups=*/true)) & Mask) { if (!Sanitizers.empty()) Sanitizers += ","; Sanitizers += A->getValue(i); } } assert(!Sanitizers.empty() && "arg didn't provide expected value"); return "-fsanitize=" + Sanitizers; } diff --git a/compiler-rt/test/fuzzer/deep-recursion.test b/compiler-rt/test/fuzzer/deep-recursion.test index 23b7af1df385..d3294d9a74c6 100644 --- a/compiler-rt/test/fuzzer/deep-recursion.test +++ b/compiler-rt/test/fuzzer/deep-recursion.test @@ -1,4 +1,4 @@ # Test that we can find a stack overflow -RUN: %cpp_compiler -fsanitize-coverage=stack-depth %S/DeepRecursionTest.cpp -o %t +RUN: %cpp_compiler %S/DeepRecursionTest.cpp -o %t RUN: not %t -seed=1 -runs=100000000 2>&1 | FileCheck %s CHECK: ERROR: libFuzzer: deadly signal diff --git a/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp b/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp index 870784dc483b..01689dfd1618 100644 --- a/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp +++ b/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp @@ -1,816 +1,828 @@ //===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Coverage instrumentation done on LLVM IR level, works with Sanitizers. // //===----------------------------------------------------------------------===// #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Analysis/EHPersonalities.h" #include "llvm/Analysis/PostDominators.h" #include "llvm/IR/CFG.h" #include "llvm/IR/CallSite.h" #include "llvm/IR/Constant.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DebugInfo.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/InlineAsm.h" +#include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/MDBuilder.h" #include "llvm/IR/Module.h" #include "llvm/IR/Type.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/Instrumentation.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Transforms/Utils/ModuleUtils.h" using namespace llvm; #define DEBUG_TYPE "sancov" static const char *const SanCovTracePCIndirName = "__sanitizer_cov_trace_pc_indir"; static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc"; static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1"; static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2"; static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4"; static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8"; static const char *const SanCovTraceConstCmp1 = "__sanitizer_cov_trace_const_cmp1"; static const char *const SanCovTraceConstCmp2 = "__sanitizer_cov_trace_const_cmp2"; static const char *const SanCovTraceConstCmp4 = "__sanitizer_cov_trace_const_cmp4"; static const char *const SanCovTraceConstCmp8 = "__sanitizer_cov_trace_const_cmp8"; static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4"; static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8"; static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep"; static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch"; static const char *const SanCovModuleCtorName = "sancov.module_ctor"; static const uint64_t SanCtorAndDtorPriority = 2; static const char *const SanCovTracePCGuardName = "__sanitizer_cov_trace_pc_guard"; static const char *const SanCovTracePCGuardInitName = "__sanitizer_cov_trace_pc_guard_init"; static const char *const SanCov8bitCountersInitName = "__sanitizer_cov_8bit_counters_init"; static const char *const SanCovPCsInitName = "__sanitizer_cov_pcs_init"; static const char *const SanCovGuardsSectionName = "sancov_guards"; static const char *const SanCovCountersSectionName = "sancov_cntrs"; static const char *const SanCovPCsSectionName = "sancov_pcs"; static const char *const SanCovLowestStackName = "__sancov_lowest_stack"; static cl::opt ClCoverageLevel( "sanitizer-coverage-level", cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, " "3: all blocks and critical edges"), cl::Hidden, cl::init(0)); static cl::opt ClTracePC("sanitizer-coverage-trace-pc", cl::desc("Experimental pc tracing"), cl::Hidden, cl::init(false)); static cl::opt ClTracePCGuard("sanitizer-coverage-trace-pc-guard", cl::desc("pc tracing with a guard"), cl::Hidden, cl::init(false)); // If true, we create a global variable that contains PCs of all instrumented // BBs, put this global into a named section, and pass this section's bounds // to __sanitizer_cov_pcs_init. // This way the coverage instrumentation does not need to acquire the PCs // at run-time. Works with trace-pc-guard and inline-8bit-counters. static cl::opt ClCreatePCTable("sanitizer-coverage-pc-table", cl::desc("create a static PC table"), cl::Hidden, cl::init(false)); static cl::opt ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters", cl::desc("increments 8-bit counter for every edge"), cl::Hidden, cl::init(false)); static cl::opt ClCMPTracing("sanitizer-coverage-trace-compares", cl::desc("Tracing of CMP and similar instructions"), cl::Hidden, cl::init(false)); static cl::opt ClDIVTracing("sanitizer-coverage-trace-divs", cl::desc("Tracing of DIV instructions"), cl::Hidden, cl::init(false)); static cl::opt ClGEPTracing("sanitizer-coverage-trace-geps", cl::desc("Tracing of GEP instructions"), cl::Hidden, cl::init(false)); static cl::opt ClPruneBlocks("sanitizer-coverage-prune-blocks", cl::desc("Reduce the number of instrumented blocks"), cl::Hidden, cl::init(true)); static cl::opt ClStackDepth("sanitizer-coverage-stack-depth", cl::desc("max stack depth tracing"), cl::Hidden, cl::init(false)); namespace { SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) { SanitizerCoverageOptions Res; switch (LegacyCoverageLevel) { case 0: Res.CoverageType = SanitizerCoverageOptions::SCK_None; break; case 1: Res.CoverageType = SanitizerCoverageOptions::SCK_Function; break; case 2: Res.CoverageType = SanitizerCoverageOptions::SCK_BB; break; case 3: Res.CoverageType = SanitizerCoverageOptions::SCK_Edge; break; case 4: Res.CoverageType = SanitizerCoverageOptions::SCK_Edge; Res.IndirectCalls = true; break; } return Res; } SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) { // Sets CoverageType and IndirectCalls. SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel); Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType); Options.IndirectCalls |= CLOpts.IndirectCalls; Options.TraceCmp |= ClCMPTracing; Options.TraceDiv |= ClDIVTracing; Options.TraceGep |= ClGEPTracing; Options.TracePC |= ClTracePC; Options.TracePCGuard |= ClTracePCGuard; Options.Inline8bitCounters |= ClInline8bitCounters; Options.PCTable |= ClCreatePCTable; Options.NoPrune |= !ClPruneBlocks; Options.StackDepth |= ClStackDepth; if (!Options.TracePCGuard && !Options.TracePC && !Options.Inline8bitCounters && !Options.StackDepth) Options.TracePCGuard = true; // TracePCGuard is default. return Options; } class SanitizerCoverageModule : public ModulePass { public: SanitizerCoverageModule( const SanitizerCoverageOptions &Options = SanitizerCoverageOptions()) : ModulePass(ID), Options(OverrideFromCL(Options)) { initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry()); } bool runOnModule(Module &M) override; bool runOnFunction(Function &F); static char ID; // Pass identification, replacement for typeid StringRef getPassName() const override { return "SanitizerCoverageModule"; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired(); AU.addRequired(); } private: void InjectCoverageForIndirectCalls(Function &F, ArrayRef IndirCalls); void InjectTraceForCmp(Function &F, ArrayRef CmpTraceTargets); void InjectTraceForDiv(Function &F, ArrayRef DivTraceTargets); void InjectTraceForGep(Function &F, ArrayRef GepTraceTargets); void InjectTraceForSwitch(Function &F, ArrayRef SwitchTraceTargets); - bool InjectCoverage(Function &F, ArrayRef AllBlocks); + bool InjectCoverage(Function &F, ArrayRef AllBlocks, + bool IsLeafFunc = true); GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements, Function &F, Type *Ty, const char *Section); void CreateFunctionLocalArrays(Function &F, ArrayRef AllBlocks); void CreatePCArray(Function &F, ArrayRef AllBlocks); - void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx); + void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx, + bool IsLeafFunc = true); Function *CreateInitCallsForSections(Module &M, const char *InitFunctionName, Type *Ty, const char *Section); std::pair CreateSecStartEnd(Module &M, const char *Section, Type *Ty); void SetNoSanitizeMetadata(Instruction *I) { I->setMetadata(I->getModule()->getMDKindID("nosanitize"), MDNode::get(*C, None)); } std::string getSectionName(const std::string &Section) const; std::string getSectionStart(const std::string &Section) const; std::string getSectionEnd(const std::string &Section) const; Function *SanCovTracePCIndir; Function *SanCovTracePC, *SanCovTracePCGuard; Function *SanCovTraceCmpFunction[4]; Function *SanCovTraceConstCmpFunction[4]; Function *SanCovTraceDivFunction[2]; Function *SanCovTraceGepFunction; Function *SanCovTraceSwitchFunction; GlobalVariable *SanCovLowestStack; InlineAsm *EmptyAsm; Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy, *Int16Ty, *Int8Ty, *Int8PtrTy; Module *CurModule; Triple TargetTriple; LLVMContext *C; const DataLayout *DL; GlobalVariable *FunctionGuardArray; // for trace-pc-guard. GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters. GlobalVariable *FunctionPCsArray; // for pc-table. SanitizerCoverageOptions Options; }; } // namespace std::pair SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section, Type *Ty) { GlobalVariable *SecStart = new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr, getSectionStart(Section)); SecStart->setVisibility(GlobalValue::HiddenVisibility); GlobalVariable *SecEnd = new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr, getSectionEnd(Section)); SecEnd->setVisibility(GlobalValue::HiddenVisibility); return std::make_pair(SecStart, SecEnd); } Function *SanitizerCoverageModule::CreateInitCallsForSections( Module &M, const char *InitFunctionName, Type *Ty, const char *Section) { IRBuilder<> IRB(M.getContext()); auto SecStartEnd = CreateSecStartEnd(M, Section, Ty); auto SecStart = SecStartEnd.first; auto SecEnd = SecStartEnd.second; Function *CtorFunc; std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions( M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty}, {IRB.CreatePointerCast(SecStart, Ty), IRB.CreatePointerCast(SecEnd, Ty)}); if (TargetTriple.supportsCOMDAT()) { // Use comdat to dedup CtorFunc. CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName)); appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc); } else { appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority); } return CtorFunc; } bool SanitizerCoverageModule::runOnModule(Module &M) { if (Options.CoverageType == SanitizerCoverageOptions::SCK_None) return false; C = &(M.getContext()); DL = &M.getDataLayout(); CurModule = &M; TargetTriple = Triple(M.getTargetTriple()); FunctionGuardArray = nullptr; Function8bitCounterArray = nullptr; FunctionPCsArray = nullptr; IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits()); IntptrPtrTy = PointerType::getUnqual(IntptrTy); Type *VoidTy = Type::getVoidTy(*C); IRBuilder<> IRB(*C); Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty()); Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty()); Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty()); Int64Ty = IRB.getInt64Ty(); Int32Ty = IRB.getInt32Ty(); Int16Ty = IRB.getInt16Ty(); Int8Ty = IRB.getInt8Ty(); SanCovTracePCIndir = checkSanitizerInterfaceFunction( M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy)); SanCovTraceCmpFunction[0] = checkSanitizerInterfaceFunction(M.getOrInsertFunction( SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty())); SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction( M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(), IRB.getInt16Ty())); SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction( M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(), IRB.getInt32Ty())); SanCovTraceCmpFunction[3] = checkSanitizerInterfaceFunction(M.getOrInsertFunction( SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty)); SanCovTraceConstCmpFunction[0] = checkSanitizerInterfaceFunction(M.getOrInsertFunction( SanCovTraceConstCmp1, VoidTy, Int8Ty, Int8Ty)); SanCovTraceConstCmpFunction[1] = checkSanitizerInterfaceFunction(M.getOrInsertFunction( SanCovTraceConstCmp2, VoidTy, Int16Ty, Int16Ty)); SanCovTraceConstCmpFunction[2] = checkSanitizerInterfaceFunction(M.getOrInsertFunction( SanCovTraceConstCmp4, VoidTy, Int32Ty, Int32Ty)); SanCovTraceConstCmpFunction[3] = checkSanitizerInterfaceFunction(M.getOrInsertFunction( SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty)); SanCovTraceDivFunction[0] = checkSanitizerInterfaceFunction(M.getOrInsertFunction( SanCovTraceDiv4, VoidTy, IRB.getInt32Ty())); SanCovTraceDivFunction[1] = checkSanitizerInterfaceFunction(M.getOrInsertFunction( SanCovTraceDiv8, VoidTy, Int64Ty)); SanCovTraceGepFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction( SanCovTraceGep, VoidTy, IntptrTy)); SanCovTraceSwitchFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction( SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy)); Constant *SanCovLowestStackConstant = M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy); SanCovLowestStack = cast(SanCovLowestStackConstant); SanCovLowestStack->setThreadLocalMode( GlobalValue::ThreadLocalMode::InitialExecTLSModel); if (Options.StackDepth && !SanCovLowestStack->isDeclaration()) SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy)); // Make sure smaller parameters are zero-extended to i64 as required by the // x86_64 ABI. if (TargetTriple.getArch() == Triple::x86_64) { for (int i = 0; i < 3; i++) { SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt); SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt); SanCovTraceConstCmpFunction[i]->addParamAttr(0, Attribute::ZExt); SanCovTraceConstCmpFunction[i]->addParamAttr(1, Attribute::ZExt); } SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt); } // We insert an empty inline asm after cov callbacks to avoid callback merge. EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false), StringRef(""), StringRef(""), /*hasSideEffects=*/true); SanCovTracePC = checkSanitizerInterfaceFunction( M.getOrInsertFunction(SanCovTracePCName, VoidTy)); SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction( SanCovTracePCGuardName, VoidTy, Int32PtrTy)); for (auto &F : M) runOnFunction(F); Function *Ctor = nullptr; if (FunctionGuardArray) Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy, SanCovGuardsSectionName); if (Function8bitCounterArray) Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy, SanCovCountersSectionName); if (Ctor && Options.PCTable) { auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy); Function *InitFunction = declareSanitizerInitFunction( M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy}); IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator()); IRBCtor.CreateCall(InitFunction, {IRB.CreatePointerCast(SecStartEnd.first, IntptrPtrTy), IRB.CreatePointerCast(SecStartEnd.second, IntptrPtrTy)}); } return true; } // True if block has successors and it dominates all of them. static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) { if (succ_begin(BB) == succ_end(BB)) return false; for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) { if (!DT->dominates(BB, SUCC)) return false; } return true; } // True if block has predecessors and it postdominates all of them. static bool isFullPostDominator(const BasicBlock *BB, const PostDominatorTree *PDT) { if (pred_begin(BB) == pred_end(BB)) return false; for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) { if (!PDT->dominates(BB, PRED)) return false; } return true; } static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB, const DominatorTree *DT, const PostDominatorTree *PDT, const SanitizerCoverageOptions &Options) { // Don't insert coverage for unreachable blocks: we will never call // __sanitizer_cov() for them, so counting them in // NumberOfInstrumentedBlocks() might complicate calculation of code coverage // percentage. Also, unreachable instructions frequently have no debug // locations. if (isa(BB->getTerminator())) return false; // Don't insert coverage into blocks without a valid insertion point // (catchswitch blocks). if (BB->getFirstInsertionPt() == BB->end()) return false; if (Options.NoPrune || &F.getEntryBlock() == BB) return true; if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function && &F.getEntryBlock() != BB) return false; // Do not instrument full dominators, or full post-dominators with multiple // predecessors. return !isFullDominator(BB, DT) && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor()); } bool SanitizerCoverageModule::runOnFunction(Function &F) { if (F.empty()) return false; if (F.getName().find(".module_ctor") != std::string::npos) return false; // Should not instrument sanitizer init functions. if (F.getName().startswith("__sanitizer_")) return false; // Don't instrument __sanitizer_* callbacks. // Don't touch available_externally functions, their actual body is elewhere. if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false; // Don't instrument MSVC CRT configuration helpers. They may run before normal // initialization. if (F.getName() == "__local_stdio_printf_options" || F.getName() == "__local_stdio_scanf_options") return false; // Don't instrument functions using SEH for now. Splitting basic blocks like // we do for coverage breaks WinEHPrepare. // FIXME: Remove this when SEH no longer uses landingpad pattern matching. if (F.hasPersonalityFn() && isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn()))) return false; if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge) SplitAllCriticalEdges(F); SmallVector IndirCalls; SmallVector BlocksToInstrument; SmallVector CmpTraceTargets; SmallVector SwitchTraceTargets; SmallVector DivTraceTargets; SmallVector GepTraceTargets; const DominatorTree *DT = &getAnalysis(F).getDomTree(); const PostDominatorTree *PDT = &getAnalysis(F).getPostDomTree(); + bool IsLeafFunc = true; for (auto &BB : F) { if (shouldInstrumentBlock(F, &BB, DT, PDT, Options)) BlocksToInstrument.push_back(&BB); for (auto &Inst : BB) { if (Options.IndirectCalls) { CallSite CS(&Inst); if (CS && !CS.getCalledFunction()) IndirCalls.push_back(&Inst); } if (Options.TraceCmp) { if (isa(&Inst)) CmpTraceTargets.push_back(&Inst); if (isa(&Inst)) SwitchTraceTargets.push_back(&Inst); } if (Options.TraceDiv) if (BinaryOperator *BO = dyn_cast(&Inst)) if (BO->getOpcode() == Instruction::SDiv || BO->getOpcode() == Instruction::UDiv) DivTraceTargets.push_back(BO); if (Options.TraceGep) if (GetElementPtrInst *GEP = dyn_cast(&Inst)) GepTraceTargets.push_back(GEP); - } + if (Options.StackDepth) + if (isa(Inst) || + (isa(Inst) && !isa(Inst))) + IsLeafFunc = false; + } } - InjectCoverage(F, BlocksToInstrument); + InjectCoverage(F, BlocksToInstrument, IsLeafFunc); InjectCoverageForIndirectCalls(F, IndirCalls); InjectTraceForCmp(F, CmpTraceTargets); InjectTraceForSwitch(F, SwitchTraceTargets); InjectTraceForDiv(F, DivTraceTargets); InjectTraceForGep(F, GepTraceTargets); return true; } GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection( size_t NumElements, Function &F, Type *Ty, const char *Section) { ArrayType *ArrayTy = ArrayType::get(Ty, NumElements); auto Array = new GlobalVariable( *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage, Constant::getNullValue(ArrayTy), "__sancov_gen_"); if (auto Comdat = F.getComdat()) Array->setComdat(Comdat); Array->setSection(getSectionName(Section)); Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize() : Ty->getPrimitiveSizeInBits() / 8); return Array; } void SanitizerCoverageModule::CreatePCArray(Function &F, ArrayRef AllBlocks) { size_t N = AllBlocks.size(); assert(N); SmallVector PCs; IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt()); for (size_t i = 0; i < N; i++) { if (&F.getEntryBlock() == AllBlocks[i]) { PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy)); PCs.push_back((Constant *)IRB.CreateIntToPtr( ConstantInt::get(IntptrTy, 1), IntptrPtrTy)); } else { PCs.push_back((Constant *)IRB.CreatePointerCast( BlockAddress::get(AllBlocks[i]), IntptrPtrTy)); PCs.push_back((Constant *)IRB.CreateIntToPtr( ConstantInt::get(IntptrTy, 0), IntptrPtrTy)); } } FunctionPCsArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy, SanCovPCsSectionName); FunctionPCsArray->setInitializer( ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs)); FunctionPCsArray->setConstant(true); // We don't reference the PCs array in any of our runtime functions, so we // need to prevent it from being dead stripped. appendToUsed(*F.getParent(), {FunctionPCsArray}); } void SanitizerCoverageModule::CreateFunctionLocalArrays( Function &F, ArrayRef AllBlocks) { if (Options.TracePCGuard) FunctionGuardArray = CreateFunctionLocalArrayInSection( AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName); if (Options.Inline8bitCounters) Function8bitCounterArray = CreateFunctionLocalArrayInSection( AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName); if (Options.PCTable) CreatePCArray(F, AllBlocks); } bool SanitizerCoverageModule::InjectCoverage(Function &F, - ArrayRef AllBlocks) { + ArrayRef AllBlocks, + bool IsLeafFunc) { if (AllBlocks.empty()) return false; CreateFunctionLocalArrays(F, AllBlocks); for (size_t i = 0, N = AllBlocks.size(); i < N; i++) - InjectCoverageAtBlock(F, *AllBlocks[i], i); + InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc); return true; } // On every indirect call we call a run-time function // __sanitizer_cov_indir_call* with two parameters: // - callee address, // - global cache array that contains CacheSize pointers (zero-initialized). // The cache is used to speed up recording the caller-callee pairs. // The address of the caller is passed implicitly via caller PC. // CacheSize is encoded in the name of the run-time function. void SanitizerCoverageModule::InjectCoverageForIndirectCalls( Function &F, ArrayRef IndirCalls) { if (IndirCalls.empty()) return; assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters); for (auto I : IndirCalls) { IRBuilder<> IRB(I); CallSite CS(I); Value *Callee = CS.getCalledValue(); if (isa(Callee)) continue; IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy)); } } // For every switch statement we insert a call: // __sanitizer_cov_trace_switch(CondValue, // {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... }) void SanitizerCoverageModule::InjectTraceForSwitch( Function &, ArrayRef SwitchTraceTargets) { for (auto I : SwitchTraceTargets) { if (SwitchInst *SI = dyn_cast(I)) { IRBuilder<> IRB(I); SmallVector Initializers; Value *Cond = SI->getCondition(); if (Cond->getType()->getScalarSizeInBits() > Int64Ty->getScalarSizeInBits()) continue; Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases())); Initializers.push_back( ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits())); if (Cond->getType()->getScalarSizeInBits() < Int64Ty->getScalarSizeInBits()) Cond = IRB.CreateIntCast(Cond, Int64Ty, false); for (auto It : SI->cases()) { Constant *C = It.getCaseValue(); if (C->getType()->getScalarSizeInBits() < Int64Ty->getScalarSizeInBits()) C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty); Initializers.push_back(C); } std::sort(Initializers.begin() + 2, Initializers.end(), [](const Constant *A, const Constant *B) { return cast(A)->getLimitedValue() < cast(B)->getLimitedValue(); }); ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size()); GlobalVariable *GV = new GlobalVariable( *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage, ConstantArray::get(ArrayOfInt64Ty, Initializers), "__sancov_gen_cov_switch_values"); IRB.CreateCall(SanCovTraceSwitchFunction, {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)}); } } } void SanitizerCoverageModule::InjectTraceForDiv( Function &, ArrayRef DivTraceTargets) { for (auto BO : DivTraceTargets) { IRBuilder<> IRB(BO); Value *A1 = BO->getOperand(1); if (isa(A1)) continue; if (!A1->getType()->isIntegerTy()) continue; uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType()); int CallbackIdx = TypeSize == 32 ? 0 : TypeSize == 64 ? 1 : -1; if (CallbackIdx < 0) continue; auto Ty = Type::getIntNTy(*C, TypeSize); IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx], {IRB.CreateIntCast(A1, Ty, true)}); } } void SanitizerCoverageModule::InjectTraceForGep( Function &, ArrayRef GepTraceTargets) { for (auto GEP : GepTraceTargets) { IRBuilder<> IRB(GEP); for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I) if (!isa(*I) && (*I)->getType()->isIntegerTy()) IRB.CreateCall(SanCovTraceGepFunction, {IRB.CreateIntCast(*I, IntptrTy, true)}); } } void SanitizerCoverageModule::InjectTraceForCmp( Function &, ArrayRef CmpTraceTargets) { for (auto I : CmpTraceTargets) { if (ICmpInst *ICMP = dyn_cast(I)) { IRBuilder<> IRB(ICMP); Value *A0 = ICMP->getOperand(0); Value *A1 = ICMP->getOperand(1); if (!A0->getType()->isIntegerTy()) continue; uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType()); int CallbackIdx = TypeSize == 8 ? 0 : TypeSize == 16 ? 1 : TypeSize == 32 ? 2 : TypeSize == 64 ? 3 : -1; if (CallbackIdx < 0) continue; // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1); auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx]; bool FirstIsConst = isa(A0); bool SecondIsConst = isa(A1); // If both are const, then we don't need such a comparison. if (FirstIsConst && SecondIsConst) continue; // If only one is const, then make it the first callback argument. if (FirstIsConst || SecondIsConst) { CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx]; if (SecondIsConst) std::swap(A0, A1); } auto Ty = Type::getIntNTy(*C, TypeSize); IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)}); } } } void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB, - size_t Idx) { + size_t Idx, + bool IsLeafFunc) { BasicBlock::iterator IP = BB.getFirstInsertionPt(); bool IsEntryBB = &BB == &F.getEntryBlock(); DebugLoc EntryLoc; if (IsEntryBB) { if (auto SP = F.getSubprogram()) EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP); // Keep static allocas and llvm.localescape calls in the entry block. Even // if we aren't splitting the block, it's nice for allocas to be before // calls. IP = PrepareToSplitEntryBlock(BB, IP); } else { EntryLoc = IP->getDebugLoc(); } IRBuilder<> IRB(&*IP); IRB.SetCurrentDebugLocation(EntryLoc); if (Options.TracePC) { IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC. IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge. } if (Options.TracePCGuard) { auto GuardPtr = IRB.CreateIntToPtr( IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy), ConstantInt::get(IntptrTy, Idx * 4)), Int32PtrTy); IRB.CreateCall(SanCovTracePCGuard, GuardPtr); IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge. } if (Options.Inline8bitCounters) { auto CounterPtr = IRB.CreateGEP( Function8bitCounterArray, {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)}); auto Load = IRB.CreateLoad(CounterPtr); auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1)); auto Store = IRB.CreateStore(Inc, CounterPtr); SetNoSanitizeMetadata(Load); SetNoSanitizeMetadata(Store); } - if (Options.StackDepth && IsEntryBB) { + if (Options.StackDepth && IsEntryBB && !IsLeafFunc) { // Check stack depth. If it's the deepest so far, record it. Function *GetFrameAddr = Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress); auto FrameAddrPtr = IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)}); auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy); auto LowestStack = IRB.CreateLoad(SanCovLowestStack); auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack); auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false); IRBuilder<> ThenIRB(ThenTerm); - ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack); + auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack); + SetNoSanitizeMetadata(LowestStack); + SetNoSanitizeMetadata(Store); } } std::string SanitizerCoverageModule::getSectionName(const std::string &Section) const { if (TargetTriple.getObjectFormat() == Triple::COFF) return ".SCOV$M"; if (TargetTriple.isOSBinFormatMachO()) return "__DATA,__" + Section; return "__" + Section; } std::string SanitizerCoverageModule::getSectionStart(const std::string &Section) const { if (TargetTriple.isOSBinFormatMachO()) return "\1section$start$__DATA$__" + Section; return "__start___" + Section; } std::string SanitizerCoverageModule::getSectionEnd(const std::string &Section) const { if (TargetTriple.isOSBinFormatMachO()) return "\1section$end$__DATA$__" + Section; return "__stop___" + Section; } char SanitizerCoverageModule::ID = 0; INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov", "SanitizerCoverage: TODO." "ModulePass", false, false) INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov", "SanitizerCoverage: TODO." "ModulePass", false, false) ModulePass *llvm::createSanitizerCoverageModulePass( const SanitizerCoverageOptions &Options) { return new SanitizerCoverageModule(Options); } diff --git a/llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll b/llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll index e88741553d5b..878295cd6533 100644 --- a/llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll +++ b/llvm/test/Instrumentation/SanitizerCoverage/stack-depth.ll @@ -1,48 +1,43 @@ ; This check verifies that stack depth instrumentation works correctly. ; RUN: opt < %s -sancov -sanitizer-coverage-level=1 \ -; RUN: -sanitizer-coverage-stack-depth -S | FileCheck %s --enable-var-scope +; RUN: -sanitizer-coverage-stack-depth -S | FileCheck %s ; RUN: opt < %s -sancov -sanitizer-coverage-level=3 \ ; RUN: -sanitizer-coverage-stack-depth -sanitizer-coverage-trace-pc-guard \ -; RUN: -S | FileCheck %s --enable-var-scope +; RUN: -S | FileCheck %s target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128" target triple = "x86_64-unknown-linux-gnu" ; CHECK: @__sancov_lowest_stack = thread_local(initialexec) global i64 -1 @__sancov_lowest_stack = thread_local global i64 0, align 8 define i32 @foo() { entry: ; CHECK-LABEL: define i32 @foo -; CHECK: [[framePtr:%[^ \t]+]] = call i8* @llvm.frameaddress(i32 0) -; CHECK: [[frameInt:%[^ \t]+]] = ptrtoint i8* [[framePtr]] to [[$intType:i[0-9]+]] -; CHECK: [[lowest:%[^ \t]+]] = load [[$intType]], [[$intType]]* @__sancov_lowest_stack -; CHECK: [[cmp:%[^ \t]+]] = icmp ult [[$intType]] [[frameInt]], [[lowest]] -; CHECK: br i1 [[cmp]], label %[[ifLabel:[^ \t]+]], label -; CHECK: