Skip to content

Commit 027ff82

Browse files
committed
[sancov] Introduce optional callback for stack-depth tracking
Normally -fsanitize-coverage=stack-depth inserts inline arithmetic to update thread_local __sancov_lowest_stack. To support stack depth tracking in the Linux kernel, which does not implement traditional thread_local storage, provide the option to call a function instead. This matches the existing "stackleak" implementation that is supported in Linux via a GCC plugin. To make this coverage more performant, a minimum estimated stack depth can be chosen to enable the callback mode, skipping instrumentation of functions with smaller stacks. With -fsanitize-coverage-stack-depth-callback-min set greater than 0, the __sanitize_cov_stack_depth() callback will be injected when the estimated stack depth is greater than or equal to the given minimum.
1 parent f46ff4c commit 027ff82

File tree

9 files changed

+353
-15
lines changed

9 files changed

+353
-15
lines changed

clang/include/clang/Basic/CodeGenOptions.def

+1
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,7 @@ CODEGENOPT(SanitizeCoveragePCTable, 1, 0) ///< Create a PC Table.
305305
CODEGENOPT(SanitizeCoverageControlFlow, 1, 0) ///< Collect control flow
306306
CODEGENOPT(SanitizeCoverageNoPrune, 1, 0) ///< Disable coverage pruning.
307307
CODEGENOPT(SanitizeCoverageStackDepth, 1, 0) ///< Enable max stack depth tracing
308+
VALUE_CODEGENOPT(SanitizeCoverageStackDepthCallbackMin , 32, 0) ///< Enable stack depth tracing callbacks.
308309
CODEGENOPT(SanitizeCoverageTraceLoads, 1, 0) ///< Enable tracing of loads.
309310
CODEGENOPT(SanitizeCoverageTraceStores, 1, 0) ///< Enable tracing of stores.
310311
CODEGENOPT(SanitizeBinaryMetadataCovered, 1, 0) ///< Emit PCs for covered functions.

clang/include/clang/Driver/Options.td

+7
Original file line numberDiff line numberDiff line change
@@ -2361,6 +2361,13 @@ def fsanitize_coverage_ignorelist : Joined<["-"], "fsanitize-coverage-ignorelist
23612361
HelpText<"Disable sanitizer coverage instrumentation for modules and functions "
23622362
"that match the provided special case list, even the allowed ones">,
23632363
MarshallingInfoStringVector<CodeGenOpts<"SanitizeCoverageIgnorelistFiles">>;
2364+
def fsanitize_coverage_stack_depth_callback_min_EQ
2365+
: Joined<["-"], "fsanitize-coverage-stack-depth-callback-min=">,
2366+
Group<f_clang_Group>,
2367+
MetaVarName<"<M>">,
2368+
HelpText<"Use callback for max stack depth tracing with minimum stack "
2369+
"depth M">,
2370+
MarshallingInfoInt<CodeGenOpts<"SanitizeCoverageStackDepthCallbackMin">>;
23642371
def fexperimental_sanitize_metadata_EQ : CommaJoined<["-"], "fexperimental-sanitize-metadata=">,
23652372
Group<f_Group>,
23662373
HelpText<"Specify the type of metadata to emit for binary analysis sanitizers">;

clang/include/clang/Driver/SanitizerArgs.h

+1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ class SanitizerArgs {
3434
std::vector<std::string> CoverageIgnorelistFiles;
3535
std::vector<std::string> BinaryMetadataIgnorelistFiles;
3636
int CoverageFeatures = 0;
37+
int CoverageStackDepthCallbackMin = 0;
3738
int BinaryMetadataFeatures = 0;
3839
int OverflowPatternExclusions = 0;
3940
int MsanTrackOrigins = 0;

clang/lib/CodeGen/BackendUtil.cpp

+1
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,7 @@ getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
255255
Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
256256
Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
257257
Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
258+
Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
258259
Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
259260
Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
260261
Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;

clang/lib/Driver/SanitizerArgs.cpp

+16
Original file line numberDiff line numberDiff line change
@@ -751,6 +751,17 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC,
751751
options::OPT_fno_sanitize_ignorelist,
752752
clang::diag::err_drv_malformed_sanitizer_ignorelist, DiagnoseErrors);
753753

754+
// Verify that -fsanitize-coverage-stack-depth-callback-min is >= 0.
755+
if (Arg *A = Args.getLastArg(
756+
options::OPT_fsanitize_coverage_stack_depth_callback_min_EQ)) {
757+
StringRef S = A->getValue();
758+
if (S.getAsInteger(0, CoverageStackDepthCallbackMin) ||
759+
CoverageStackDepthCallbackMin < 0) {
760+
if (DiagnoseErrors)
761+
D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
762+
}
763+
}
764+
754765
// Parse -f[no-]sanitize-memory-track-origins[=level] options.
755766
if (AllAddedKinds & SanitizerKind::Memory) {
756767
if (Arg *A =
@@ -1269,6 +1280,11 @@ void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args,
12691280
addSpecialCaseListOpt(Args, CmdArgs, "-fsanitize-coverage-ignorelist=",
12701281
CoverageIgnorelistFiles);
12711282

1283+
if (CoverageStackDepthCallbackMin)
1284+
CmdArgs.push_back(
1285+
Args.MakeArgString("-fsanitize-coverage-stack-depth-callback-min=" +
1286+
Twine(CoverageStackDepthCallbackMin)));
1287+
12721288
if (!GPUSanitize) {
12731289
// Translate available BinaryMetadataFeatures to corresponding clang-cc1
12741290
// flags. Does not depend on any other sanitizers. Unsupported on GPUs.

clang/test/Driver/fsanitize-coverage.c

+13
Original file line numberDiff line numberDiff line change
@@ -87,11 +87,24 @@
8787
// RUN: %clang --target=x86_64-linux-gnu \
8888
// RUN: -fsanitize-coverage=trace-pc-guard,stack-depth %s -### 2>&1 | \
8989
// RUN: FileCheck %s --check-prefix=CHECK-STACK-DEPTH-PC-GUARD
90+
// RUN: %clang --target=x86_64-linux-gnu \
91+
// RUN: -fsanitize-coverage-stack-depth-callback-min=100 %s -### 2>&1 | \
92+
// RUN: FileCheck %s --check-prefix=CHECK-STACK-DEPTH-CALLBACK
93+
// RUN: %clang --target=x86_64-linux-gnu \
94+
// RUN: -fsanitize-coverage-stack-depth-callback-min=0 %s -### 2>&1 | \
95+
// RUN: FileCheck %s --check-prefix=CHECK-STACK-DEPTH-CALLBACK-ZERO
96+
// RUN: %clang --target=x86_64-linux-gnu \
97+
// RUN: -fsanitize-coverage-stack-depth-callback-min=-10 %s -### 2>&1 | \
98+
// RUN: FileCheck %s --check-prefix=CHECK-STACK-DEPTH-CALLBACK-NEGATIVE
9099
// CHECK-STACK-DEPTH: -fsanitize-coverage-type=1
91100
// CHECK-STACK-DEPTH: -fsanitize-coverage-stack-depth
92101
// CHECK-STACK-DEPTH-PC-GUARD: -fsanitize-coverage-type=3
93102
// CHECK-STACK-DEPTH-PC-GUARD: -fsanitize-coverage-trace-pc-guard
94103
// CHECK-STACK-DEPTH-PC-GUARD: -fsanitize-coverage-stack-depth
104+
// CHECK-STACK-DEPTH-CALLBACK-NOT: error:
105+
// CHECK-STACK-DEPTH-CALLBACK: -fsanitize-coverage-stack-depth-callback-min=100
106+
// CHECK-STACK-DEPTH-CALLBACK-ZERO-NOT: -fsanitize-coverage-stack-depth-callback-min=0
107+
// CHECK-STACK-DEPTH-CALLBACK-NEGATIVE: error: invalid value '-10' not allowed with '-fsanitize-coverage-stack-depth-callback-min=-10'
95108

96109
// RUN: %clang --target=x86_64-linux-gnu -fsanitize=address -fsanitize-coverage=trace-cmp,indirect-calls %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-NO-TYPE-NECESSARY
97110
// CHECK-NO-TYPE-NECESSARY-NOT: error:

llvm/include/llvm/Transforms/Utils/Instrumentation.h

+1
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ struct SanitizerCoverageOptions {
158158
bool PCTable = false;
159159
bool NoPrune = false;
160160
bool StackDepth = false;
161+
int StackDepthCallbackMin = 0;
161162
bool TraceLoads = false;
162163
bool TraceStores = false;
163164
bool CollectControlFlow = false;

llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp

+59-15
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
#include "llvm/Support/CommandLine.h"
3434
#include "llvm/Support/SpecialCaseList.h"
3535
#include "llvm/Support/VirtualFileSystem.h"
36+
#include "llvm/Support/raw_ostream.h"
3637
#include "llvm/TargetParser/Triple.h"
3738
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
3839
#include "llvm/Transforms/Utils/ModuleUtils.h"
@@ -86,6 +87,7 @@ const char SanCovPCsSectionName[] = "sancov_pcs";
8687
const char SanCovCFsSectionName[] = "sancov_cfs";
8788
const char SanCovCallbackGateSectionName[] = "sancov_gate";
8889

90+
const char SanCovStackDepthCallbackName[] = "__sanitizer_cov_stack_depth";
8991
const char SanCovLowestStackName[] = "__sancov_lowest_stack";
9092
const char SanCovCallbackGateName[] = "__sancov_should_track";
9193

@@ -152,6 +154,12 @@ static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
152154
cl::desc("max stack depth tracing"),
153155
cl::Hidden);
154156

157+
static cl::opt<int> ClStackDepthCallbackMin(
158+
"sanitizer-coverage-stack-depth-callback-min",
159+
cl::desc("max stack depth tracing should use callback and only when "
160+
"stack depth more than specified"),
161+
cl::Hidden);
162+
155163
static cl::opt<bool>
156164
ClCollectCF("sanitizer-coverage-control-flow",
157165
cl::desc("collect control flow for each function"), cl::Hidden);
@@ -202,6 +210,8 @@ SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
202210
Options.PCTable |= ClCreatePCTable;
203211
Options.NoPrune |= !ClPruneBlocks;
204212
Options.StackDepth |= ClStackDepth;
213+
Options.StackDepthCallbackMin = std::max(Options.StackDepthCallbackMin,
214+
ClStackDepthCallbackMin.getValue());
205215
Options.TraceLoads |= ClLoadTracing;
206216
Options.TraceStores |= ClStoreTracing;
207217
Options.GatedCallbacks |= ClGatedCallbacks;
@@ -271,6 +281,7 @@ class ModuleSanitizerCoverage {
271281
DomTreeCallback DTCallback;
272282
PostDomTreeCallback PDTCallback;
273283

284+
FunctionCallee SanCovStackDepthCallback;
274285
FunctionCallee SanCovTracePCIndir;
275286
FunctionCallee SanCovTracePC, SanCovTracePCGuard;
276287
std::array<FunctionCallee, 4> SanCovTraceCmpFunction;
@@ -514,6 +525,9 @@ bool ModuleSanitizerCoverage::instrumentModule() {
514525
SanCovTracePCGuard =
515526
M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, PtrTy);
516527

528+
SanCovStackDepthCallback =
529+
M.getOrInsertFunction(SanCovStackDepthCallbackName, VoidTy);
530+
517531
for (auto &F : M)
518532
instrumentFunction(F);
519533

@@ -1029,6 +1043,8 @@ void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
10291043
if (IsEntryBB) {
10301044
if (auto SP = F.getSubprogram())
10311045
EntryLoc = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
1046+
// FIXME: stack-depth does not correctly instrument dynamic allocas.
1047+
//
10321048
// Keep static allocas and llvm.localescape calls in the entry block. Even
10331049
// if we aren't splitting the block, it's nice for allocas to be before
10341050
// calls.
@@ -1078,22 +1094,50 @@ void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
10781094
Store->setNoSanitizeMetadata();
10791095
}
10801096
if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
1081-
// Check stack depth. If it's the deepest so far, record it.
10821097
Module *M = F.getParent();
1083-
auto FrameAddrPtr = IRB.CreateIntrinsic(
1084-
Intrinsic::frameaddress,
1085-
IRB.getPtrTy(M->getDataLayout().getAllocaAddrSpace()),
1086-
{Constant::getNullValue(Int32Ty)});
1087-
auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
1088-
auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
1089-
auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
1090-
auto ThenTerm = SplitBlockAndInsertIfThen(
1091-
IsStackLower, &*IP, false,
1092-
MDBuilder(IRB.getContext()).createUnlikelyBranchWeights());
1093-
IRBuilder<> ThenIRB(ThenTerm);
1094-
auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
1095-
LowestStack->setNoSanitizeMetadata();
1096-
Store->setNoSanitizeMetadata();
1098+
if (Options.StackDepthCallbackMin) {
1099+
// In callback mode, only add call when stack depth reaches minimum.
1100+
const DataLayout &DL = M->getDataLayout();
1101+
uint32_t EstimatedStackSize = 0;
1102+
1103+
// Make an estimate on the stack usage.
1104+
for (auto &I : F.getEntryBlock()) {
1105+
if (auto *AI = dyn_cast<AllocaInst>(&I)) {
1106+
if (AI->isStaticAlloca()) {
1107+
uint32_t Bytes = DL.getTypeAllocSize(AI->getAllocatedType());
1108+
if (AI->isArrayAllocation()) {
1109+
if (const ConstantInt *arraySize =
1110+
dyn_cast<ConstantInt>(AI->getArraySize()))
1111+
Bytes *= arraySize->getZExtValue();
1112+
}
1113+
EstimatedStackSize += Bytes;
1114+
} else {
1115+
// Dynamic alloca: require we always perform callback.
1116+
EstimatedStackSize = Options.StackDepthCallbackMin;
1117+
break;
1118+
}
1119+
}
1120+
}
1121+
1122+
if (EstimatedStackSize >= Options.StackDepthCallbackMin)
1123+
IRB.CreateCall(SanCovStackDepthCallback)->setCannotMerge();
1124+
} else {
1125+
// Check stack depth. If it's the deepest so far, record it.
1126+
auto FrameAddrPtr = IRB.CreateIntrinsic(
1127+
Intrinsic::frameaddress,
1128+
IRB.getPtrTy(M->getDataLayout().getAllocaAddrSpace()),
1129+
{Constant::getNullValue(Int32Ty)});
1130+
auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
1131+
auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
1132+
auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
1133+
auto ThenTerm = SplitBlockAndInsertIfThen(
1134+
IsStackLower, &*IP, false,
1135+
MDBuilder(IRB.getContext()).createUnlikelyBranchWeights());
1136+
IRBuilder<> ThenIRB(ThenTerm);
1137+
auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
1138+
LowestStack->setNoSanitizeMetadata();
1139+
Store->setNoSanitizeMetadata();
1140+
}
10971141
}
10981142
}
10991143

0 commit comments

Comments
 (0)