Repository navigation
Conversation
|
Hello @yskzalloc 👋 Thank you for submitting a Pull Request (PR) to the LLVM Project. Since this is your first PR, here are a few useful links covering our main contribution policies and review practices.
Please reply to this message to confirm that you have read these policies, especially the LLVM AI Tool Use Policy, and that any AI tool usage has been noted in the PR description. Frequently asked questionsHow do I add reviewers? This PR will be automatically labeled, and the relevant teams will be notified. For some parts of the project, reviewers may also be added automatically. You can also add reviewers manually using the Reviewers section on this page. If you cannot use that section, it is probably because you do not have write permissions for the repository. In that case, you can request a review by tagging reviewers in a comment using What if there are no comments? If you have not received any comments on your PR after a week, you can request a review by pinging the PR with a comment such as “Ping”. The common courtesy ping rate is once a week. Please remember that you are asking for volunteer time from other developers. Are any special GitHub settings required to contribute to LLVM? We only require contributors to have a public email address associated with their GitHub commits, see this section of LLVM Developer Policy for details. If you have questions, feel free to leave a comment on this PR, or ask on LLVM Discord or LLVM Discourse. Thank you, |
|
@llvm/pr-subscribers-llvm-transforms @llvm/pr-subscribers-clang-codegen Author: Yunseong Kim (yskzalloc) ChangesAdd 2 new SanitizerCoverage modes that emit callbacks at function entry and exit with argument/return value metadata, enabling per-task data-flow extraction. Unlike Flags
These can be used independently or together. Callbacks// Called at function entry with argument metadata
void __sanitizer_cov_trace_args(u64 type_marker, u64 pc, u64 meta, void *args_struct, ...);
// Called before function return with return value metadata
void __sanitizer_cov_trace_ret(u64 type_marker, u64 pc, u64 meta, void *ret_ptr);The MotivationThe Linux kernel uses this to implement
Using this infrastructure, I discovered two exploitable vulnerabilities in the Android binder driver (RLIMIT_NPROC bypass leading to OOM) that are invisible to KASAN, edge coverage, and ftrace. Relation to trace-pc-entry-exit
These are complementary features. Testing
References
This project is heavily influenced by [uftrace](https://uftrace.github.io/slide/#76), developed by Linux Kernel maintainer @namhyung and uftrace maintainer @honggyukim cc @vitalybuka @dvyukov Patch is 28.87 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/201410.diff 12 Files Affected:
diff --git a/clang/docs/SanitizerCoverage.rst b/clang/docs/SanitizerCoverage.rst
index c01863adebb2d..ed3509dd74fc1 100644
--- a/clang/docs/SanitizerCoverage.rst
+++ b/clang/docs/SanitizerCoverage.rst
@@ -348,6 +348,45 @@ will not be instrumented.
void __sanitizer_cov_store16(__int128 *addr);
+Tracking function arguments and return values
+==============================================
+
+With ``-fsanitize-coverage=dataflow-args`` and ``-fsanitize-coverage=dataflow-ret``
+the compiler will insert callbacks at function entry and before return instructions
+to track function arguments and return values, respectively.
+
+These flags are designed for the Linux kernel's KCOV dataflow subsystem, which uses
+the callbacks to capture struct field values for memory corruption analysis.
+
+When debug info is available (``-g``), the compiler uses ``DICompositeType`` metadata
+to extract struct field layouts (byte offset and size pairs). A FNV-1a hash of the
+struct type name is prepended to the offsets array for identification. Without ``-g``,
+the pass returns early and no callbacks are emitted.
+
+Both flags imply edge coverage when used alone.
+
+.. code-block:: c++
+
+ // Called at function entry for each argument.
+ // pc: address of the instrumented function
+ // arg_idx: zero-based argument index
+ // arg_size: size of the argument in bytes
+ // ptr: pointer to the argument value (stack-spilled for scalars)
+ // offsets: array of [byte_offset, byte_size] pairs for struct fields (null if not a struct pointer)
+ // num_fields: number of struct fields (0 if not a struct pointer)
+ void __sanitizer_cov_trace_args(uint64_t pc, uint32_t arg_idx, uint32_t arg_size,
+ void *ptr, uint64_t *offsets, uint32_t num_fields);
+
+ // Called before each return instruction.
+ // pc: address of the instrumented function
+ // ret_size: size of the return value in bytes
+ // ptr: pointer to the return value (stack-spilled for scalars, null for void)
+ // offsets: array of [byte_offset, byte_size] pairs for struct fields (null if not a struct pointer)
+ // num_fields: number of struct fields (0 if not a struct pointer)
+ void __sanitizer_cov_trace_ret(uint64_t pc, uint32_t ret_size,
+ void *ptr, uint64_t *offsets, uint32_t num_fields);
+
+
Tracing control flow
====================
diff --git a/clang/include/clang/Basic/CodeGenOptions.def b/clang/include/clang/Basic/CodeGenOptions.def
index 6cce4ada1dfd1..b4d69745b829b 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -328,6 +328,8 @@ CODEGENOPT(SanitizeCoverageStackDepth, 1, 0, Benign) ///< Enable max stack depth
VALUE_CODEGENOPT(SanitizeCoverageStackDepthCallbackMin , 32, 0, Benign) ///< Enable stack depth tracing callbacks.
CODEGENOPT(SanitizeCoverageTraceLoads, 1, 0, Benign) ///< Enable tracing of loads.
CODEGENOPT(SanitizeCoverageTraceStores, 1, 0, Benign) ///< Enable tracing of stores.
+CODEGENOPT(SanitizeCoverageDataflowArgs, 1, 0, Benign) ///< Enable tracing of function args.
+CODEGENOPT(SanitizeCoverageDataflowRet, 1, 0, Benign) ///< Enable tracing of return values.
CODEGENOPT(SanitizeBinaryMetadataCovered, 1, 0, Benign) ///< Emit PCs for covered functions.
CODEGENOPT(SanitizeBinaryMetadataAtomics, 1, 0, Benign) ///< Emit PCs for atomic operations.
CODEGENOPT(SanitizeBinaryMetadataUAR, 1, 0, Benign) ///< Emit PCs for start of functions
diff --git a/clang/include/clang/Basic/CodeGenOptions.h b/clang/include/clang/Basic/CodeGenOptions.h
index e43112b4bb98b..25fd3426767ea 100644
--- a/clang/include/clang/Basic/CodeGenOptions.h
+++ b/clang/include/clang/Basic/CodeGenOptions.h
@@ -655,7 +655,8 @@ class CodeGenOptions : public CodeGenOptionsBase {
bool hasSanitizeCoverage() const {
return SanitizeCoverageType || SanitizeCoverageIndirectCalls ||
SanitizeCoverageTraceCmp || SanitizeCoverageTraceLoads ||
- SanitizeCoverageTraceStores || SanitizeCoverageControlFlow;
+ SanitizeCoverageTraceStores || SanitizeCoverageControlFlow ||
+ SanitizeCoverageDataflowArgs || SanitizeCoverageDataflowRet;
}
// Check if any one of SanitizeBinaryMetadata* is enabled.
diff --git a/clang/include/clang/Options/Options.td b/clang/include/clang/Options/Options.td
index 025e8e7d7d761..e82972f3c7449 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -8061,6 +8061,16 @@ def fsanitize_coverage_trace_stores
Group<fsan_cov_Group>,
HelpText<"Enable tracing of stores">,
MarshallingInfoFlag<CodeGenOpts<"SanitizeCoverageTraceStores">>;
+def fsanitize_coverage_trace_args
+ : Flag<["-"], "fsanitize-coverage-dataflow-args">,
+ Group<fsan_cov_Group>,
+ HelpText<"Enable dataflow tracing of function arguments">,
+ MarshallingInfoFlag<CodeGenOpts<"SanitizeCoverageDataflowArgs">>;
+def fsanitize_coverage_trace_ret
+ : Flag<["-"], "fsanitize-coverage-dataflow-ret">,
+ Group<fsan_cov_Group>,
+ HelpText<"Enable dataflow tracing of return values">,
+ MarshallingInfoFlag<CodeGenOpts<"SanitizeCoverageDataflowRet">>;
def fexperimental_sanitize_metadata_EQ_covered
: Flag<["-"], "fexperimental-sanitize-metadata=covered">,
HelpText<"Emit PCs for code covered with binary analysis sanitizers">,
diff --git a/clang/lib/CodeGen/BackendUtil.cpp b/clang/lib/CodeGen/BackendUtil.cpp
index a46a25c4492f2..627ca7ad7d581 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -251,6 +251,8 @@ getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
Opts.StackDepthCallbackMin = CGOpts.SanitizeCoverageStackDepthCallbackMin;
Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
+ Opts.DataflowArgs = CGOpts.SanitizeCoverageDataflowArgs;
+ Opts.DataflowRet = CGOpts.SanitizeCoverageDataflowRet;
Opts.CollectControlFlow = CGOpts.SanitizeCoverageControlFlow;
return Opts;
}
diff --git a/clang/lib/Driver/SanitizerArgs.cpp b/clang/lib/Driver/SanitizerArgs.cpp
index 31660dd29407c..704110bda0e5c 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -109,6 +109,8 @@ enum CoverageFeature {
CoverageTraceStores = 1 << 17,
CoverageControlFlow = 1 << 18,
CoverageTracePCEntryExit = 1 << 19,
+ CoverageTraceArgs = 1 << 20,
+ CoverageTraceRet = 1 << 21,
};
enum BinaryMetadataFeature {
@@ -1043,6 +1045,7 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC,
int InstrumentationTypes = CoverageTracePC | CoverageTracePCEntryExit |
CoverageTracePCGuard | CoverageInline8bitCounters |
CoverageTraceLoads | CoverageTraceStores |
+ CoverageTraceArgs | CoverageTraceRet |
CoverageInlineBoolFlag | CoverageControlFlow;
if ((CoverageFeatures & InsertionPointTypes) &&
!(CoverageFeatures & InstrumentationTypes) && DiagnoseErrors) {
@@ -1054,9 +1057,10 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC,
// trace-pc w/o func/bb/edge implies edge.
if (!(CoverageFeatures & InsertionPointTypes)) {
- if (CoverageFeatures & (CoverageTracePC | CoverageTracePCEntryExit |
- CoverageTracePCGuard | CoverageInline8bitCounters |
- CoverageInlineBoolFlag | CoverageControlFlow))
+ if (CoverageFeatures &
+ (CoverageTracePC | CoverageTracePCEntryExit | CoverageTracePCGuard |
+ CoverageInline8bitCounters | CoverageInlineBoolFlag |
+ CoverageControlFlow | CoverageTraceArgs | CoverageTraceRet))
CoverageFeatures |= CoverageEdge;
if (CoverageFeatures & CoverageStackDepth)
@@ -1417,6 +1421,8 @@ void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args,
std::make_pair(CoverageStackDepth, "-fsanitize-coverage-stack-depth"),
std::make_pair(CoverageTraceLoads, "-fsanitize-coverage-trace-loads"),
std::make_pair(CoverageTraceStores, "-fsanitize-coverage-trace-stores"),
+ std::make_pair(CoverageTraceArgs, "-fsanitize-coverage-dataflow-args"),
+ std::make_pair(CoverageTraceRet, "-fsanitize-coverage-dataflow-ret"),
std::make_pair(CoverageControlFlow, "-fsanitize-coverage-control-flow")};
for (auto F : CoverageFlags) {
if (CoverageFeatures & F.first)
@@ -1804,6 +1810,8 @@ int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A,
.Case("stack-depth", CoverageStackDepth)
.Case("trace-loads", CoverageTraceLoads)
.Case("trace-stores", CoverageTraceStores)
+ .Case("dataflow-args", CoverageTraceArgs)
+ .Case("dataflow-ret", CoverageTraceRet)
.Case("control-flow", CoverageControlFlow)
.Default(0);
if (F == 0 && DiagnoseErrors)
diff --git a/clang/test/CodeGen/sanitizer-coverage-dataflow.c b/clang/test/CodeGen/sanitizer-coverage-dataflow.c
new file mode 100644
index 0000000000000..4ec82cdeab2e3
--- /dev/null
+++ b/clang/test/CodeGen/sanitizer-coverage-dataflow.c
@@ -0,0 +1,18 @@
+// Test that -fsanitize-coverage=dataflow-args and dataflow-ret emit the expected callbacks.
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -fsanitize-coverage-dataflow-args -fsanitize-coverage-type=3 -debug-info-kind=limited %s -o - | FileCheck %s --check-prefix=CHECK-ARGS
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -fsanitize-coverage-dataflow-ret -fsanitize-coverage-type=3 -debug-info-kind=limited %s -o - | FileCheck %s --check-prefix=CHECK-RET
+
+struct Foo {
+ int a;
+ long b;
+};
+
+void takes_struct_ptr(struct Foo *f) {
+}
+
+int returns_scalar(int x) {
+ return x + 1;
+}
+
+// CHECK-ARGS: call void @__sanitizer_cov_trace_args
+// CHECK-RET: call void @__sanitizer_cov_trace_ret
diff --git a/clang/test/Driver/fsanitize-coverage.c b/clang/test/Driver/fsanitize-coverage.c
index 21e2c16bfb1b7..149fb8434c680 100644
--- a/clang/test/Driver/fsanitize-coverage.c
+++ b/clang/test/Driver/fsanitize-coverage.c
@@ -170,3 +170,16 @@
// CHECK-NO-SHADOWCALLSTACK-NOT: unknown argument
// CHECK-NO-SHADOWCALLSTACK-NOT: -fsanitize=shadow-call-stack
// CHECK-NO-SHADOWCALLSTACK: -fsanitize-coverage-trace-pc-guard
+
+// RUN: %clang --target=x86_64-linux-gnu -fsanitize-coverage=dataflow-args %s -### 2>&1 | FileCheck %s --check-prefix=CHECK_DATAFLOW_ARGS
+// CHECK_DATAFLOW_ARGS: -fsanitize-coverage-type=3
+// CHECK_DATAFLOW_ARGS: -fsanitize-coverage-dataflow-args
+
+// RUN: %clang --target=x86_64-linux-gnu -fsanitize-coverage=dataflow-ret %s -### 2>&1 | FileCheck %s --check-prefix=CHECK_DATAFLOW_RET
+// CHECK_DATAFLOW_RET: -fsanitize-coverage-type=3
+// CHECK_DATAFLOW_RET: -fsanitize-coverage-dataflow-ret
+
+// RUN: %clang --target=x86_64-linux-gnu -fsanitize-coverage=edge,dataflow-args,dataflow-ret %s -### 2>&1 | FileCheck %s --check-prefix=CHECK_DATAFLOW_BOTH
+// CHECK_DATAFLOW_BOTH: -fsanitize-coverage-type=3
+// CHECK_DATAFLOW_BOTH: -fsanitize-coverage-dataflow-args
+// CHECK_DATAFLOW_BOTH: -fsanitize-coverage-dataflow-ret
\ No newline at end of file
diff --git a/llvm/include/llvm/Transforms/Utils/Instrumentation.h b/llvm/include/llvm/Transforms/Utils/Instrumentation.h
index 95a985ba3f0c4..1cb2d608ec0a1 100644
--- a/llvm/include/llvm/Transforms/Utils/Instrumentation.h
+++ b/llvm/include/llvm/Transforms/Utils/Instrumentation.h
@@ -163,6 +163,8 @@ struct SanitizerCoverageOptions {
bool StackDepth = false;
bool TraceLoads = false;
bool TraceStores = false;
+ bool DataflowArgs = false;
+ bool DataflowRet = false;
bool CollectControlFlow = false;
bool GatedCallbacks = false;
int StackDepthCallbackMin = 0;
diff --git a/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp b/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
index df9675a02824e..2858268133cbd 100644
--- a/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
+++ b/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp
@@ -15,9 +15,11 @@
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/GlobalsModRef.h"
#include "llvm/Analysis/PostDominators.h"
+#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
+#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/EHPersonalities.h"
#include "llvm/IR/Function.h"
@@ -46,6 +48,8 @@ const char SanCovTracePCIndirName[] = "__sanitizer_cov_trace_pc_indir";
const char SanCovTracePCName[] = "__sanitizer_cov_trace_pc";
const char SanCovTracePCEntryName[] = "__sanitizer_cov_trace_pc_entry";
const char SanCovTracePCExitName[] = "__sanitizer_cov_trace_pc_exit";
+const char SanCovTraceArgsName[] = "__sanitizer_cov_trace_args";
+const char SanCovTraceRetName[] = "__sanitizer_cov_trace_ret";
const char SanCovTraceCmp1[] = "__sanitizer_cov_trace_cmp1";
const char SanCovTraceCmp2[] = "__sanitizer_cov_trace_cmp2";
const char SanCovTraceCmp4[] = "__sanitizer_cov_trace_cmp4";
@@ -156,6 +160,15 @@ static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
cl::desc("Tracing of GEP instructions"),
cl::Hidden);
+static cl::opt<bool>
+ ClDataflowArgs("sanitizer-coverage-dataflow-args",
+ cl::desc("Dataflow tracing of function arguments"),
+ cl::Hidden);
+
+static cl::opt<bool>
+ ClDataflowRet("sanitizer-coverage-dataflow-ret",
+ cl::desc("Dataflow tracing of return values"), cl::Hidden);
+
static cl::opt<bool>
ClPruneBlocks("sanitizer-coverage-prune-blocks",
cl::desc("Reduce the number of instrumented blocks"),
@@ -226,10 +239,13 @@ SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
ClStackDepthCallbackMin.getValue());
Options.TraceLoads |= ClLoadTracing;
Options.TraceStores |= ClStoreTracing;
+ Options.DataflowArgs |= ClDataflowArgs;
+ Options.DataflowRet |= ClDataflowRet;
Options.GatedCallbacks |= ClGatedCallbacks;
if (!Options.TracePCGuard && !Options.TracePC && !Options.TracePCEntryExit &&
!Options.Inline8bitCounters && !Options.StackDepth &&
- !Options.InlineBoolFlag && !Options.TraceLoads && !Options.TraceStores)
+ !Options.InlineBoolFlag && !Options.TraceLoads && !Options.TraceStores &&
+ !Options.DataflowArgs && !Options.DataflowRet)
Options.TracePCGuard = true; // TracePCGuard is default.
Options.CollectControlFlow |= ClCollectCF;
return Options;
@@ -265,6 +281,8 @@ class ModuleSanitizerCoverage {
void InjectTraceForLoadsAndStores(Function &F, ArrayRef<LoadInst *> Loads,
ArrayRef<StoreInst *> Stores);
void InjectTraceForExits(Function &F);
+ void InjectTraceForArgs(Function &F);
+ void InjectTraceForRet(Function &F);
void InjectTraceForSwitch(Function &F,
ArrayRef<Instruction *> SwitchTraceTargets,
Value *&FunctionGateCmp);
@@ -298,6 +316,7 @@ class ModuleSanitizerCoverage {
FunctionCallee SanCovTracePCIndir;
FunctionCallee SanCovTracePC, SanCovTracePCGuard;
FunctionCallee SanCovTracePCEntry, SanCovTracePCExit;
+ FunctionCallee SanCovTraceArgsFunc, SanCovTraceRetFunc;
std::array<FunctionCallee, 4> SanCovTraceCmpFunction;
std::array<FunctionCallee, 4> SanCovTraceConstCmpFunction;
std::array<FunctionCallee, 5> SanCovLoadFunction;
@@ -542,6 +561,16 @@ bool ModuleSanitizerCoverage::instrumentModule() {
SanCovTracePCGuard =
M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, PtrTy);
+ // __sanitizer_cov_trace_args(i64 pc, i32 arg_idx, i32 arg_size, ptr arg, ptr
+ // offsets, i32 num_fields)
+ SanCovTraceArgsFunc =
+ M.getOrInsertFunction(SanCovTraceArgsName, VoidTy, Int64Ty, Int32Ty,
+ Int32Ty, PtrTy, PtrTy, Int32Ty);
+ // __sanitizer_cov_trace_ret(i64 pc, i32 ret_size, ptr ret_val, ptr offsets,
+ // i32 num_fields)
+ SanCovTraceRetFunc = M.getOrInsertFunction(
+ SanCovTraceRetName, VoidTy, Int64Ty, Int32Ty, PtrTy, PtrTy, Int32Ty);
+
SanCovStackDepthCallback =
M.getOrInsertFunction(SanCovStackDepthCallbackName, VoidTy);
@@ -767,6 +796,12 @@ void ModuleSanitizerCoverage::instrumentFunction(Function &F) {
if (Options.TracePCEntryExit)
InjectTraceForExits(F);
+
+ if (Options.DataflowArgs)
+ InjectTraceForArgs(F);
+
+ if (Options.DataflowRet)
+ InjectTraceForRet(F);
}
GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection(
@@ -1266,3 +1301,209 @@ void ModuleSanitizerCoverage::createFunctionControlFlow(Function &F) {
ConstantArray::get(ArrayType::get(PtrTy, CFs.size()), CFs));
FunctionCFsArray->setConstant(true);
}
+
+// Helper: Given a DIType, resolve typedefs/qualifiers to the underlying type.
+static DIType *stripDITypedefs(DIType *Ty) {
+ while (Ty) {
+ if (auto *Derived = dyn_cast<DIDerivedType>(Ty)) {
+ unsigned Tag = Derived->getTag();
+ if (Tag == dwarf::DW_TAG_typedef || Tag == dwarf::DW_TAG_const_type ||
+ Tag == dwarf::DW_TAG_volatile_type ||
+ Tag == dwarf::DW_TAG_restrict_type) {
+ Ty = Derived->getBaseType();
+ continue;
+ }
+ // pointer type - stop
+ break;
+ }
+ break;
+ }
+ return Ty;
+}
+
+// Helper: If Ty is a pointer to a struct (DICompositeType), collect byte
+// offsets of all scalar members. Returns the offsets array global and
+// num_fields.
+static std::pair<GlobalVariable *, unsigned>
+getStructFieldOffsets(DIType *Ty, Module &M, const DataLayout &DL) {
+ if (!Ty)
+ return {nullptr, 0};
+
+ Ty = stripDITypedefs(Ty);
+
+ // Must be a pointer to something
+ auto *PtrTy = dyn_cast_or_null<DIDerivedType>(Ty);
+ if (!PtrTy || PtrTy->getTag() != dwarf::DW_TAG_pointer_type)
+ return {nullptr, 0};
+
+ DIType *PointeeTy = stripDITypedefs(PtrTy->getBaseType());
+ auto *Composite = dyn_cast_or_null<DICompositeType>(PointeeTy);
+ if (!Composite || Composite->getTag() != dwarf::DW_TAG_structure_type)
+ return {nullptr, 0};
+
+ SmallVector<uint64_t, 16> Offsets;
+ for (auto *Element : Composite->getElements()) {
+ auto *Member = dyn_cast<DIDerivedType>(Element);
+ if (!Member || Member->getTag() != dwarf::DW_TAG_member)
+ continue;
+ uint64_t OffsetBits = Member->getOffsetInBits();
+ uint64_t SizeBits = Member->getSizeInBits();
+ if (SizeBits == 0)
+ continue;
+ // Record byte offset and size in bytes as pairs: [offset, size]
+ Offsets.push_back(OffsetBits / 8);
+ Offsets.push_back(SizeBits / 8);
+ }
+
+ if (Offsets.empty())
+ return {nullptr, 0};
+
+ // Enhance #4: Compute type name hash from struct name
+ uint64_t TypeHash = 0;
+ if (auto Name = Composite->getName(); !Name.empty()) {
+ // Simple FNV-1a hash of the struct name
+ TypeHash = 0xcbf29ce484222325ULL;
+ for (char C : Name) {
+ TypeHash ^= (uint64_t)(unsigned char)C;
+ TypeHash *= 0x100000001b3ULL;
+ }
+ }
+
+ // Layout: [type_hash, off0, sz0, off1, sz1, ...]
+ // We pass &array[1] as the offsets pointer, so kernel can read array[0] as
+ // hash
+ LLVMContext &C = M.getContext();
+ Type *I64Ty = Type::getInt64Ty(C);
+ SmallVector<Constant *, 16> OffsetConstants;
+ OffsetConstants.push_back(
+ ConstantInt::get(I64Ty, TypeHash)); // index 0 = hash
+ for (uint64_t V : Offsets)
+ OffsetConstants.push_back(ConstantInt::get(I64Ty, V));
+
+ ArrayType *ArrTy = ArrayType::get(I64Ty, OffsetConstants.size());
+ auto *GV = new GlobalVariable(M, ArrTy, true, GlobalVariable::PrivateLinkage,
+ ConstantArray::get(ArrTy, OffsetConstants),
+ "__sancov_offsets_");
+ GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
+ return {GV, (unsigned)(Offsets.size() / 2)};
+}
+
+void ModuleSanitizerCoverage::InjectTraceForArgs(Function &F) {
+ DISubprogram *SP = F.getSubprogram();
+ if (!SP)
+ return;
+
+ BasicBlock &EntryBB = F.getEntryBlock();
+ Instruction *InsertPt = &*EntryBB.getFirstInsertionPt();
+ InstrumentationIRBuilder IRB(InsertPt);
+
+ // Get PC as the function address cast to i64
+ Value *PC = IRB.CreatePtrToInt(&F, Int64Ty);
+
+ //...
[truncated]
|
|
This is complex enough that it needs LLVM RFC: https://llvm.org/docs/RFCProcess.html |
|
Thank you @melver for the suggestion. I completely agree that this is substantial enough to warrant an LLVM RFC, and I have already been preparing one for this feature. I will rewrite and submit the next version of this patch using the |
Re-naming from -fsanitize-coverage=dataflow-args,dataflow-ret to -fsanitize-coverage=trace-args,trace-ret for keeping naming convention in LLVM compiler. Link: llvm/llvm-project#201410 (comment) Signed-off-by: Yunseong Kim <[email protected]>
Re-naming from -fsanitize-coverage=dataflow-args,dataflow-ret to -fsanitize-coverage=trace-args,trace-ret for keeping naming convention in LLVM compiler. Link: llvm/llvm-project#201410 (comment) Signed-off-by: Yunseong Kim <[email protected]>
function argument and return values at instrumented function boundaries.
Motivation
==========
Coverage-guided kernel fuzzers use KCOV edge coverage as their sole
feedback signal. This cannot distinguish two executions of the same
function with different argument values. Fuzzers plateau on stateful
subsystems where security-critical behavior depends on runtime values
rather than control-flow topology.
Existing tracing tools address parts of this problem:
- ftrace/kprobes provide dynamic tracing but capture no argument values
and do not work on Rust kernel modules (-mfentry not emitted by rustc)
- eBPF is programmable but requires manual struct layout specification
None provide per-task tracking of function argument values with automatic
struct field expansion derived from compiler debug metadata.
Approach
========
An LLVM SanitizerCoverage pass inserts callbacks at function entry/exit
that record argument values into a per-task mmap'd ring buffer. The
kernel backend reads struct fields via copy_from_kernel_nofault(). When
not enabled for a task, the cost is a single boolean check.
The system captures:
- Function argument values at entry (with automatic struct field expansion)
- Return values at exit
- Per-task isolation (no interference between processes)
- Both C and Rust kernel modules
Design
======
- Independent from existing /sys/kernel/debug/kcov
- Separate device: /sys/kernel/debug/kcov_dataflow
- Separate ioctl namespace ('d'), separate per-task buffer
- Lock-free write path: READ_ONCE/WRITE_ONCE (portable to ARM64)
- Safe pointer reads: copy_from_kernel_nofault()
- in_task() guard rejects interrupt/NMI context
- Per-module opt-in: KCOV_DATAFLOW_file.o := y
- Optional global: CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL
- Compiler flags: -fsanitize-coverage=trace-args,trace-ret
(Kconfig uses cc-option to verify compiler support)
Performance
===========
Per-module instrumentation (recording active):
+8.3% on instrumented paths, ~27ns per callback
Global instrumentation (INSTRUMENT_ALL, recording disabled):
.text: +9.5%, .data: +44%, boot: +71%, syscall latency: +133%
Patches
=======
1/13: Core implementation (kernel/kcov_dataflow.c, task_struct fields,
Kconfig, Makefile.kcov, Makefile.lib)
2/13: Fix INIT_TRACK race (double-alloc on concurrent ioctl)
3/13: Add barriers to recursion guard
4/13: Reject enable on multiple dataflow fds simultaneously
5/13: Clear dataflow fields on fork
6/13: Clean up dataflow state on task exit
7/13: Exclude kcov_dataflow.o from sanitizer instrumentation
8/13: Add trigger-view.py visualization tool
9/13: Add user_ioctl selftest (9 TAP test cases)
10/13: Add eight_args_c test module (1-8 argument functions)
11/13: Add eight_args_rust test module
12/13: Add rust_ffi_contract test module
13/13: Documentation (Documentation/dev-tools/kcov-dataflow.rst)
Prerequisites
=============
Requires custom LLVM/Clang with trace-args/trace-ret passes:
git clone --recursive --depth 1 --shallow-submodules \
--jobs $(nproc) https://github.com/yskzalloc/kcov-dataflow.git
cd kcov-dataflow
cd llvm-project
cmake -S llvm -B build -G Ninja \
-DCMAKE_BUILD_TYPE=Release \
-DLLVM_ENABLE_PROJECTS="clang;lld" \
-DLLVM_TARGETS_TO_BUILD="X86;AArch64"
ninja -C build
cd ..
export PATH="$PWD/llvm-project/build/bin:$PATH"
cd linux
make LLVM=1 CC=clang defconfig
scripts/config --enable KCOV \
--enable KCOV_DATAFLOW_ARGS \
--enable KCOV_DATAFLOW_RET \
--enable DEBUG_INFO
make LLVM=1 CC=clang olddefconfig
make LLVM=1 CC=clang -j$(nproc)
I've been usually tested on Github CI using vng:
vng --build \
--configitem CONFIG_KCOV=y \
--configitem CONFIG_KCOV_DATAFLOW_ARGS=y \
--configitem CONFIG_KCOV_DATAFLOW_RET=y \
--configitem CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL=y \
--configitem CONFIG_DEBUG_INFO=y \
--configitem CONFIG_DEBUG_INFO_DWARF5=y \
--configitem CONFIG_RUST=y \
LLVM=1 CC=clang RUSTC=$RUSTC RUST_LIB_SRC=$RUST_LIB_SRC
For Rust module support, build rustc against the custom LLVM:
https://github.com/yskzalloc/rust
Testing
=======
Tested on linux-next 7.1.0-rc6 (next-20260608) with custom clang/LLVM 23
and rustc 1.98-nightly. Verified on both x86_64 and arm64:
- user_ioctl: 9/9 TAP tests pass
- eight_args_c: nested call tree with df_func2..8 + struct (65 context records)
- eight_args_rust: nested call tree with rdf_func2..8 + struct (65 context records)
- rust_ffi_contract: FFI contract violation detected (60 context records)
CI results: https://github.com/yskzalloc/kcov-dataflow/actions
Links
=====
LLVM RFC: https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
LLVM PR: llvm/llvm-project#201410
Repository: https://github.com/yskzalloc/kcov-dataflow
Paper: https://arxiv.org/pdf/2606.00455
---
Changelog:
Changes since v1(https://lore.kernel.org/all/[email protected]/):
- Separate from /sys/kernel/debug/kcov (own device, own ioctl namespace)
- Per-module opt-in via KCOV_DATAFLOW_file.o := y
- Rename internal symbols to avoid collision with existing kcov
- Add CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL for whole-kernel capture
- Add selftests (user_ioctl, eight_args_c, eight_args_rust, rust_ffi_contract)
- Add Documentation/dev-tools/kcov-dataflow.rst
- Fix INIT_TRACK race, fork cleanup, task exit cleanup
- Add recursion guard barriers
- Reject concurrent enable on multiple fds
- Move from tools to kselftest
Cc: Peter Zijlstra <[email protected]>
Cc: Nicolas Schier <[email protected]>
Cc: Alexander Potapenko <[email protected]>
Signed-off-by: Yunseong Kim <[email protected]>
--- b4-submit-tracking ---
# This section is used internally by b4 prep for tracking purposes.
{
"series": {
"revision": 2,
"change-id": "20260611-b4-kcov-dataflow-v2-5bed05b6c568",
"prefixes": []
}
}
…lues Add a new tracking mechanism that captures function arguments/return values at instrumented function boundaries via submitted as an LLVM RFC SanitizerCoverage callbacks: __sanitizer_cov_trace_args __sanitizer_cov_trace_ret LLVM RFC: https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026 LLVM PR: llvm/llvm-project#201410 This requires a custom LLVM/Clang build with the trace-args/ret passes. Clone and build toolchain: git clone --recursive --depth 1 --shallow-submodules \ --jobs `nproc` https://github.com/yskzalloc/kcov-dataflow.git cd kcov-dataflow cd llvm-project cmake -S llvm -B build -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_C_COMPILER=clang \ -DCMAKE_CXX_COMPILER=clang++ \ -DLLVM_ENABLE_LLD=ON \ -DLLVM_ENABLE_PROJECTS="clang;lld" \ -DLLVM_TARGETS_TO_BUILD="X86;AArch64" ninja -C build cd .. Build and boot kernel (using virtme-ng): export PATH=$PWD/llvm-project/build/bin:$PATH cd linux vng --build \ --configitem CONFIG_KCOV=y \ --configitem CONFIG_KCOV_DATAFLOW_ARGS=y \ --configitem CONFIG_KCOV_DATAFLOW_RET=y \ --configitem CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL=y \ --configitem CONFIG_DEBUG_INFO=y \ --configitem CONFIG_RUST=y # for rust module kselftest LLVM=1 CC=clang Core implementation in kernel/kcov_dataflow.c (separating from kcov.c as Alexander's request): - Per-task lock-free ring buffer via debugfs kcov_dataflow device - READ_ONCE/WRITE_ONCE atomic pattern (tested on arm64) - copy_from_kernel_nofault() for safe struct field reads - in_task() guard rejects interrupt context - Bit-31 recursion guard prevents INSTRUMENT_ALL re-entry Build system (scripts/Makefile.kcov, scripts/Makefile.lib): - CFLAGS_KCOV_DATAFLOW: -fsanitize-coverage=trace-args,trace-ret - RUSTFLAGS_KCOV_DATAFLOW: -Cllvm-args=-sanitizer-coverage-trace-args/ret - Per-file opt-in: KCOV_DATAFLOW_file.o := y - Respects KCOV_INSTRUMENT := n for noinstr exclusion - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL for whole-kernel Kconfig (lib/Kconfig.debug): - CONFIG_KCOV_DATAFLOW_ARGS / CONFIG_KCOV_DATAFLOW_RET - Depends on CONFIG_KCOV and CONFIG_DEBUG_INFO - CONFIG_KCOV_DATAFLOW_NO_INLINE (default n) - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL Also fix rust/kernel/str.rs unused import (flags::* -> flags::GFP_KERNEL) which newer rustc (1.98-nightly) rejects as a hard error. Rust support requires rustc built against the custom LLVM with trace-args/ret passes compiled in: https://github.com/yskzalloc/rust Link: https://github.com/yskzalloc/kcov-dataflow/ Cc: Alexander Potapenko <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Nicolas Schier <[email protected]> Signed-off-by: Yunseong Kim <[email protected]>
…lues Add a new tracking mechanism that captures function arguments/return values at instrumented function boundaries via submitted as an LLVM RFC SanitizerCoverage callbacks: __sanitizer_cov_trace_args __sanitizer_cov_trace_ret LLVM RFC: https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026 LLVM PR: llvm/llvm-project#201410 This requires a custom LLVM/Clang build with the trace-args/ret passes. Clone and build toolchain: git clone --recursive --depth 1 --shallow-submodules \ --jobs `nproc` https://github.com/yskzalloc/kcov-dataflow.git cd kcov-dataflow cd llvm-project cmake -S llvm -B build -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_C_COMPILER=clang \ -DCMAKE_CXX_COMPILER=clang++ \ -DLLVM_ENABLE_LLD=ON \ -DLLVM_ENABLE_PROJECTS="clang;lld" \ -DLLVM_TARGETS_TO_BUILD="X86;AArch64" ninja -C build cd .. Build and boot kernel (using virtme-ng): export PATH=$PWD/llvm-project/build/bin:$PATH cd linux vng --build \ --configitem CONFIG_KCOV=y \ --configitem CONFIG_KCOV_DATAFLOW_ARGS=y \ --configitem CONFIG_KCOV_DATAFLOW_RET=y \ --configitem CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL=y \ --configitem CONFIG_DEBUG_INFO=y \ --configitem CONFIG_RUST=y # for rust module kselftest LLVM=1 CC=clang Core implementation in kernel/kcov_dataflow.c (separating from kcov.c as Alexander's request): - Per-task lock-free ring buffer via debugfs kcov_dataflow device - READ_ONCE/WRITE_ONCE atomic pattern (tested on arm64) - copy_from_kernel_nofault() for safe struct field reads - in_task() guard rejects interrupt context - Bit-31 recursion guard prevents INSTRUMENT_ALL re-entry Build system (scripts/Makefile.kcov, scripts/Makefile.lib): - CFLAGS_KCOV_DATAFLOW: -fsanitize-coverage=trace-args,trace-ret - RUSTFLAGS_KCOV_DATAFLOW: -Cllvm-args=-sanitizer-coverage-trace-args/ret - Per-file opt-in: KCOV_DATAFLOW_file.o := y - Respects KCOV_INSTRUMENT := n for noinstr exclusion - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL for whole-kernel Kconfig (lib/Kconfig.debug): - CONFIG_KCOV_DATAFLOW_ARGS / CONFIG_KCOV_DATAFLOW_RET - Depends on CONFIG_KCOV and CONFIG_DEBUG_INFO - CONFIG_KCOV_DATAFLOW_NO_INLINE (default n) - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL Also fix rust/kernel/str.rs unused import (flags::* -> flags::GFP_KERNEL) which newer rustc (1.98-nightly) rejects as a hard error. Rust support requires rustc built against the custom LLVM with trace-args/ret passes compiled in: https://github.com/yskzalloc/rust Link: https://github.com/yskzalloc/kcov-dataflow/ Cc: Alexander Potapenko <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Nicolas Schier <[email protected]> Signed-off-by: Yunseong Kim <[email protected]>
…lues Add a new tracking mechanism that captures function arguments/return values at instrumented function boundaries via submitted as an LLVM RFC SanitizerCoverage callbacks: __sanitizer_cov_trace_args __sanitizer_cov_trace_ret LLVM RFC: https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026 LLVM PR: llvm/llvm-project#201410 This requires a custom LLVM/Clang build with the trace-args/ret passes. Clone and build toolchain: git clone --recursive --depth 1 --shallow-submodules \ --jobs `nproc` https://github.com/yskzalloc/kcov-dataflow.git cd kcov-dataflow cd llvm-project cmake -S llvm -B build -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_C_COMPILER=clang \ -DCMAKE_CXX_COMPILER=clang++ \ -DLLVM_ENABLE_LLD=ON \ -DLLVM_ENABLE_PROJECTS="clang;lld" \ -DLLVM_TARGETS_TO_BUILD="X86;AArch64" ninja -C build cd .. Build and boot kernel (using virtme-ng): export PATH=$PWD/llvm-project/build/bin:$PATH cd linux vng --build \ --configitem CONFIG_KCOV=y \ --configitem CONFIG_KCOV_DATAFLOW_ARGS=y \ --configitem CONFIG_KCOV_DATAFLOW_RET=y \ --configitem CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL=y \ --configitem CONFIG_DEBUG_INFO=y \ --configitem CONFIG_RUST=y # for rust module kselftest LLVM=1 CC=clang Core implementation in kernel/kcov_dataflow.c (separating from kcov.c as Alexander's request): - Per-task lock-free ring buffer via debugfs kcov_dataflow device - READ_ONCE/WRITE_ONCE atomic pattern (tested on arm64) - copy_from_kernel_nofault() for safe struct field reads - in_task() guard rejects interrupt context - Bit-31 recursion guard prevents INSTRUMENT_ALL re-entry Build system (scripts/Makefile.kcov, scripts/Makefile.lib): - CFLAGS_KCOV_DATAFLOW: -fsanitize-coverage=trace-args,trace-ret - RUSTFLAGS_KCOV_DATAFLOW: -Cllvm-args=-sanitizer-coverage-trace-args/ret - Per-file opt-in: KCOV_DATAFLOW_file.o := y - Respects KCOV_INSTRUMENT := n for noinstr exclusion - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL for whole-kernel Kconfig (lib/Kconfig.debug): - CONFIG_KCOV_DATAFLOW_ARGS / CONFIG_KCOV_DATAFLOW_RET - Depends on CONFIG_KCOV and CONFIG_DEBUG_INFO - CONFIG_KCOV_DATAFLOW_NO_INLINE (default n) - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL Also fix rust/kernel/str.rs unused import (flags::* -> flags::GFP_KERNEL) which newer rustc (1.98-nightly) rejects as a hard error. Rust support requires rustc built against the custom LLVM with trace-args/ret passes compiled in: https://github.com/yskzalloc/rust Link: https://github.com/yskzalloc/kcov-dataflow/ Cc: Alexander Potapenko <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Nicolas Schier <[email protected]> Signed-off-by: Yunseong Kim <[email protected]>
…lues Add a new tracking mechanism that captures function arguments/return values at instrumented function boundaries via submitted as an LLVM RFC SanitizerCoverage callbacks: __sanitizer_cov_trace_args __sanitizer_cov_trace_ret This requires a custom LLVM/Clang build with the trace-args/ret passes: LLVM RFC: https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026 LLVM PR: llvm/llvm-project#201410 Clone and build toolchain: git clone --recursive --depth 1 --shallow-submodules \ --jobs `nproc` https://github.com/yskzalloc/kcov-dataflow.git cd kcov-dataflow cd llvm-project cmake -S llvm -B build -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_C_COMPILER=clang \ -DCMAKE_CXX_COMPILER=clang++ \ -DLLVM_ENABLE_LLD=ON \ -DLLVM_ENABLE_PROJECTS="clang;lld" \ -DLLVM_TARGETS_TO_BUILD="X86;AArch64" ninja -C build cd .. Build and boot kernel (using virtme-ng): export PATH=$PWD/llvm-project/build/bin:$PATH cd linux vng --build \ --configitem CONFIG_KCOV=y \ --configitem CONFIG_KCOV_DATAFLOW_ARGS=y \ --configitem CONFIG_KCOV_DATAFLOW_RET=y \ --configitem CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL=y \ --configitem CONFIG_DEBUG_INFO=y \ --configitem CONFIG_RUST=y # for rust module kselftest LLVM=1 CC=clang Core implementation in kernel/kcov_dataflow.c (separating from kcov.c as Alexander's request): - Per-task lock-free ring buffer via debugfs kcov_dataflow device - READ_ONCE/WRITE_ONCE atomic pattern (tested on arm64) - copy_from_kernel_nofault() for safe struct field reads - in_task() guard rejects interrupt context - Bit-31 recursion guard prevents INSTRUMENT_ALL re-entry Build system (scripts/Makefile.kcov, scripts/Makefile.lib): - CFLAGS_KCOV_DATAFLOW: -fsanitize-coverage=trace-args,trace-ret - RUSTFLAGS_KCOV_DATAFLOW: -Cllvm-args=-sanitizer-coverage-trace-args/ret - Per-file opt-in: KCOV_DATAFLOW_file.o := y - Respects KCOV_INSTRUMENT := n for noinstr exclusion - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL for whole-kernel Kconfig (lib/Kconfig.debug): - CONFIG_KCOV_DATAFLOW_ARGS / CONFIG_KCOV_DATAFLOW_RET - Depends on CONFIG_KCOV and CONFIG_DEBUG_INFO - CONFIG_KCOV_DATAFLOW_NO_INLINE (default n) - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL Also fix rust/kernel/str.rs unused import (flags::* -> flags::GFP_KERNEL) which newer rustc (1.98-nightly) rejects as a hard error. Rust support requires rustc built against the custom LLVM with trace-args/ret passes compiled in: https://github.com/yskzalloc/rust Link: https://github.com/yskzalloc/kcov-dataflow/ Cc: Alexander Potapenko <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Nicolas Schier <[email protected]> Signed-off-by: Yunseong Kim <[email protected]>
…lues Add a new tracking mechanism that captures function arguments/return values at instrumented function boundaries via submitted as an LLVM RFC SanitizerCoverage callbacks: __sanitizer_cov_trace_args __sanitizer_cov_trace_ret This requires a custom LLVM/Clang build with the trace-args/ret passes: LLVM RFC: https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026 LLVM PR: llvm/llvm-project#201410 Clone and build toolchain: git clone --recursive --depth 1 --shallow-submodules \ --jobs `nproc` https://github.com/yskzalloc/kcov-dataflow.git cd kcov-dataflow cd llvm-project cmake -S llvm -B build -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_C_COMPILER=clang \ -DCMAKE_CXX_COMPILER=clang++ \ -DLLVM_ENABLE_LLD=ON \ -DLLVM_ENABLE_PROJECTS="clang;lld" \ -DLLVM_TARGETS_TO_BUILD="X86;AArch64" ninja -C build cd .. Build and boot kernel (using virtme-ng): export PATH=$PWD/llvm-project/build/bin:$PATH cd linux vng --build \ --configitem CONFIG_KCOV=y \ --configitem CONFIG_KCOV_DATAFLOW_ARGS=y \ --configitem CONFIG_KCOV_DATAFLOW_RET=y \ --configitem CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL=y \ --configitem CONFIG_DEBUG_INFO=y \ --configitem CONFIG_RUST=y # for rust module kselftest LLVM=1 CC=clang Core implementation in kernel/kcov_dataflow.c (separating from kcov.c as Alexander's request): - Per-task lock-free ring buffer via debugfs kcov_dataflow device - READ_ONCE/WRITE_ONCE atomic pattern (tested on arm64) - copy_from_kernel_nofault() for safe struct field reads - in_task() guard rejects interrupt context - Bit-31 recursion guard prevents INSTRUMENT_ALL re-entry Build system (scripts/Makefile.kcov, scripts/Makefile.lib): - CFLAGS_KCOV_DATAFLOW: -fsanitize-coverage=trace-args,trace-ret - RUSTFLAGS_KCOV_DATAFLOW: -Cllvm-args=-sanitizer-coverage-trace-args/ret - Per-file opt-in: KCOV_DATAFLOW_file.o := y - Respects KCOV_INSTRUMENT := n for noinstr exclusion - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL for whole-kernel Kconfig (lib/Kconfig.debug): - CONFIG_KCOV_DATAFLOW_ARGS / CONFIG_KCOV_DATAFLOW_RET - Depends on CONFIG_KCOV and CONFIG_DEBUG_INFO - CONFIG_KCOV_DATAFLOW_NO_INLINE (default n) - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL Also fix rust/kernel/str.rs unused import (flags::* -> flags::GFP_KERNEL) which newer rustc (1.98-nightly) rejects as a hard error. Rust support requires rustc built against the custom LLVM with trace-args/ret passes compiled in: https://github.com/yskzalloc/rust Link: https://github.com/yskzalloc/kcov-dataflow/ Cc: Alexander Potapenko <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Nicolas Schier <[email protected]> Signed-off-by: Yunseong Kim <[email protected]>
…lues Add a new tracking mechanism that captures function arguments/return values at instrumented function boundaries via submitted as an LLVM RFC SanitizerCoverage callbacks: __sanitizer_cov_trace_args __sanitizer_cov_trace_ret This requires a custom LLVM/Clang build with the trace-args/ret passes: LLVM RFC: https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026 LLVM PR: llvm/llvm-project#201410 Core implementation in kernel/kcov_dataflow.c (separating from kcov.c as Alexander's request): - Per-task lock-free ring buffer via debugfs kcov_dataflow device - READ_ONCE/WRITE_ONCE atomic pattern (tested on arm64) - copy_from_kernel_nofault() for safe struct field reads - in_task() guard rejects interrupt context - Bit-31 recursion guard prevents INSTRUMENT_ALL re-entry - Barriers after setting/clearing guard and enable/disable to ensure correct ordering (paired comments document each barrier) Build system (scripts/Makefile.kcov, scripts/Makefile.lib): - CFLAGS_KCOV_DATAFLOW: -fsanitize-coverage=trace-args,trace-ret - RUSTFLAGS_KCOV_DATAFLOW: -Cllvm-args=-sanitizer-coverage-trace-args/ret - Per-file opt-in: KCOV_DATAFLOW_file.o := y - Respects KCOV_INSTRUMENT := n for noinstr exclusion - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL for whole-kernel Kconfig (lib/Kconfig.debug): - CONFIG_KCOV_DATAFLOW_ARGS / CONFIG_KCOV_DATAFLOW_RET - Depends on CONFIG_KCOV and CONFIG_DEBUG_INFO - CONFIG_KCOV_DATAFLOW_NO_INLINE - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL Safety: - Exclude kcov_dataflow.o from KCOV, KASAN, KCSAN, UBSAN, and KMSAN instrumentation to prevent infinite recursion - Reject enable on multiple dataflow fds simultaneously - Clear dataflow fields on fork (prevent parent buffer sharing) - Clean up dataflow state on task exit (prevent use-after-free) - Fix INIT_TRACK race by rechecking df->area after re-acquiring lock Rust support requires rustc built against the custom LLVM with trace-args/ret passes compiled in: https://github.com/yskzalloc/rust Also fix rust/kernel/str.rs unused import (flags::* -> flags::GFP_KERNEL) which newer rustc (1.98-nightly) rejects as a hard error. Clone and build toolchain: git clone --recursive --depth 1 --shallow-submodules \ --jobs `nproc` https://github.com/yskzalloc/kcov-dataflow.git cd kcov-dataflow cd llvm-project cmake -S llvm -B build -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_C_COMPILER=clang \ -DCMAKE_CXX_COMPILER=clang++ \ -DLLVM_ENABLE_LLD=ON \ -DLLVM_ENABLE_PROJECTS="clang;lld" \ -DLLVM_TARGETS_TO_BUILD="X86;AArch64" ninja -C build cd .. Build and boot kernel (using virtme-ng): export PATH=$PWD/llvm-project/build/bin:$PATH cd linux vng --build \ --configitem CONFIG_KCOV=y \ --configitem CONFIG_KCOV_DATAFLOW_ARGS=y \ --configitem CONFIG_KCOV_DATAFLOW_RET=y \ --configitem CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL=y \ --configitem CONFIG_DEBUG_INFO=y \ --configitem CONFIG_RUST=y \ LLVM=1 CC=clang Link: https://github.com/yskzalloc/kcov-dataflow/ Cc: Peter Zijlstra <[email protected]> Cc: Alexander Potapenko <[email protected]> Cc: Nicolas Schier <[email protected]> Signed-off-by: Yunseong Kim <[email protected]>
…lues Add a new tracking mechanism that captures function arguments/return values at instrumented function boundaries via submitted as an LLVM RFC SanitizerCoverage callbacks: __sanitizer_cov_trace_args __sanitizer_cov_trace_ret This requires a custom LLVM/Clang build with the trace-args/ret passes: LLVM RFC: https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026 LLVM PR: llvm/llvm-project#201410 Core implementation in kernel/kcov_dataflow.c (separating from kcov.c as Alexander's request): - Per-task lock-free ring buffer via debugfs kcov_dataflow device - READ_ONCE/WRITE_ONCE atomic pattern (tested on arm64) - copy_from_kernel_nofault() for safe struct field reads - in_task() guard rejects interrupt context - Bit-31 recursion guard prevents INSTRUMENT_ALL re-entry - Barriers after setting/clearing guard and enable/disable to ensure correct ordering (paired comments document each barrier) Build system (scripts/Makefile.kcov, scripts/Makefile.lib): - CFLAGS_KCOV_DATAFLOW: -fsanitize-coverage=trace-args,trace-ret - RUSTFLAGS_KCOV_DATAFLOW: -Cllvm-args=-sanitizer-coverage-trace-args/ret - Per-file opt-in: KCOV_DATAFLOW_file.o := y - Respects KCOV_INSTRUMENT := n for noinstr exclusion - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL for whole-kernel Kconfig (lib/Kconfig.debug): - CONFIG_KCOV_DATAFLOW_ARGS / CONFIG_KCOV_DATAFLOW_RET - Depends on CONFIG_KCOV and CONFIG_DEBUG_INFO - CONFIG_KCOV_DATAFLOW_NO_INLINE - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL Safety: - Exclude kcov_dataflow.o from KCOV, KASAN, KCSAN, UBSAN, and KMSAN instrumentation to prevent infinite recursion - Reject enable on multiple dataflow fds simultaneously - Clear dataflow fields on fork (prevent parent buffer sharing) - Clean up dataflow state on task exit (prevent use-after-free) - Fix INIT_TRACK race by rechecking df->area after re-acquiring lock Rust support requires rustc built against the custom LLVM with trace-args/ret passes compiled in: https://github.com/yskzalloc/rust Also fix rust/kernel/str.rs unused import (flags::* -> flags::GFP_KERNEL) which newer rustc (1.98-nightly) rejects as a hard error. Clone and build toolchain: git clone --recursive --depth 1 --shallow-submodules \ --jobs `nproc` https://github.com/yskzalloc/kcov-dataflow.git cd kcov-dataflow cd llvm-project cmake -S llvm -B build -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_C_COMPILER=clang \ -DCMAKE_CXX_COMPILER=clang++ \ -DLLVM_ENABLE_LLD=ON \ -DLLVM_ENABLE_PROJECTS="clang;lld" \ -DLLVM_TARGETS_TO_BUILD="X86;AArch64" ninja -C build cd .. Build and boot kernel (using virtme-ng): export PATH=$PWD/llvm-project/build/bin:$PATH cd linux vng --build \ --configitem CONFIG_KCOV=y \ --configitem CONFIG_KCOV_DATAFLOW_ARGS=y \ --configitem CONFIG_KCOV_DATAFLOW_RET=y \ --configitem CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL=y \ --configitem CONFIG_DEBUG_INFO=y \ --configitem CONFIG_RUST=y \ LLVM=1 CC=clang Link: https://github.com/yskzalloc/kcov-dataflow/ Cc: Peter Zijlstra <[email protected]> Cc: Alexander Potapenko <[email protected]> Cc: Nicolas Schier <[email protected]> Signed-off-by: Yunseong Kim <[email protected]>
…lues Add a new tracking mechanism that captures function arguments/return values at instrumented function boundaries via submitted as an LLVM RFC SanitizerCoverage callbacks: __sanitizer_cov_trace_args __sanitizer_cov_trace_ret This requires a custom LLVM/Clang build with the trace-args/ret passes: LLVM RFC: https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026 LLVM PR: llvm/llvm-project#201410 Core implementation in kernel/kcov_dataflow.c (separating from kcov.c as Alexander's request): - Per-task lock-free ring buffer via debugfs kcov_dataflow device - READ_ONCE/WRITE_ONCE atomic pattern (tested on arm64) - copy_from_kernel_nofault() for safe struct field reads - in_task() guard rejects interrupt context - Bit-31 recursion guard prevents INSTRUMENT_ALL re-entry - Barriers after setting/clearing guard and enable/disable to ensure correct ordering (paired comments document each barrier) Build system (scripts/Makefile.kcov, scripts/Makefile.lib): - CFLAGS_KCOV_DATAFLOW: -fsanitize-coverage=trace-args,trace-ret - RUSTFLAGS_KCOV_DATAFLOW: -Cllvm-args=-sanitizer-coverage-trace-args/ret - Per-file opt-in: KCOV_DATAFLOW_file.o := y - Respects KCOV_INSTRUMENT := n for noinstr exclusion - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL for whole-kernel Kconfig (lib/Kconfig.debug): - CONFIG_KCOV_DATAFLOW_ARGS / CONFIG_KCOV_DATAFLOW_RET - Depends on CONFIG_KCOV and CONFIG_DEBUG_INFO - CONFIG_KCOV_DATAFLOW_NO_INLINE - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL Safety: - Exclude kcov_dataflow.o from KCOV, KASAN, KCSAN, UBSAN, and KMSAN instrumentation to prevent infinite recursion - Reject enable on multiple dataflow fds simultaneously - Clear dataflow fields on fork (prevent parent buffer sharing) - Clean up dataflow state on task exit (prevent use-after-free) - Fix INIT_TRACK race by rechecking df->area after re-acquiring lock Rust support requires rustc built against the custom LLVM with trace-args/ret passes compiled in: https://github.com/yskzalloc/rust Also fix rust/kernel/str.rs unused import (flags::* -> flags::GFP_KERNEL) which newer rustc (1.98-nightly) rejects as a hard error. Clone and build toolchain: git clone --recursive --depth 1 --shallow-submodules \ --jobs `nproc` https://github.com/yskzalloc/kcov-dataflow.git cd kcov-dataflow cd llvm-project cmake -S llvm -B build -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_C_COMPILER=clang \ -DCMAKE_CXX_COMPILER=clang++ \ -DLLVM_ENABLE_LLD=ON \ -DLLVM_ENABLE_PROJECTS="clang;lld" \ -DLLVM_TARGETS_TO_BUILD="X86;AArch64" ninja -C build cd .. Build and boot kernel (using virtme-ng): export PATH=$PWD/llvm-project/build/bin:$PATH cd linux vng --build \ --configitem CONFIG_KCOV=y \ --configitem CONFIG_KCOV_DATAFLOW_ARGS=y \ --configitem CONFIG_KCOV_DATAFLOW_RET=y \ --configitem CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL=y \ --configitem CONFIG_DEBUG_INFO=y \ --configitem CONFIG_RUST=y \ LLVM=1 CC=clang Link: https://github.com/yskzalloc/kcov-dataflow/ Cc: Peter Zijlstra <[email protected]> Cc: Alexander Potapenko <[email protected]> Cc: Nicolas Schier <[email protected]> Signed-off-by: Yunseong Kim <[email protected]>
…lues Add a new tracking mechanism that captures function arguments/return values at instrumented function boundaries via submitted as an LLVM RFC SanitizerCoverage callbacks: __sanitizer_cov_trace_args __sanitizer_cov_trace_ret This requires a custom LLVM/Clang build with the trace-args/ret passes: LLVM RFC: https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026 LLVM PR: llvm/llvm-project#201410 Core implementation in kernel/kcov_dataflow.c (separating from kcov.c as Alexander's request): - Per-task lock-free ring buffer via debugfs kcov_dataflow device - READ_ONCE/WRITE_ONCE atomic pattern (tested on arm64) - copy_from_kernel_nofault() for safe struct field reads - in_task() guard rejects interrupt context - Bit-31 recursion guard prevents INSTRUMENT_ALL re-entry - Barriers after setting/clearing guard and enable/disable to ensure correct ordering (paired comments document each barrier) Build system (scripts/Makefile.kcov, scripts/Makefile.lib): - CFLAGS_KCOV_DATAFLOW: -fsanitize-coverage=trace-args,trace-ret - RUSTFLAGS_KCOV_DATAFLOW: -Cllvm-args=-sanitizer-coverage-trace-args/ret - Per-file opt-in: KCOV_DATAFLOW_file.o := y - Respects KCOV_INSTRUMENT := n for noinstr exclusion - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL for whole-kernel Kconfig (lib/Kconfig.debug): - CONFIG_KCOV_DATAFLOW_ARGS / CONFIG_KCOV_DATAFLOW_RET - Depends on CONFIG_KCOV and CONFIG_DEBUG_INFO - CONFIG_KCOV_DATAFLOW_NO_INLINE - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL Safety: - Exclude kcov_dataflow.o from KCOV, KASAN, KCSAN, UBSAN, and KMSAN instrumentation to prevent infinite recursion - Reject enable on multiple dataflow fds simultaneously - Clear dataflow fields on fork (prevent parent buffer sharing) - Clean up dataflow state on task exit (prevent use-after-free) - Fix INIT_TRACK race by rechecking df->area after re-acquiring lock Rust support requires rustc built against the custom LLVM with trace-args/ret passes compiled in: https://github.com/yskzalloc/rust Also fix rust/kernel/str.rs unused import (flags::* -> flags::GFP_KERNEL) which newer rustc (1.98-nightly) rejects as a hard error. Clone and build toolchain: git clone --recursive --depth 1 --shallow-submodules \ --jobs `nproc` https://github.com/yskzalloc/kcov-dataflow.git cd kcov-dataflow cd llvm-project cmake -S llvm -B build -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_C_COMPILER=clang \ -DCMAKE_CXX_COMPILER=clang++ \ -DLLVM_ENABLE_LLD=ON \ -DLLVM_ENABLE_PROJECTS="clang;lld" \ -DLLVM_TARGETS_TO_BUILD="X86;AArch64" ninja -C build cd .. Build and boot kernel (using virtme-ng): export PATH=$PWD/llvm-project/build/bin:$PATH cd linux vng --build \ --configitem CONFIG_KCOV=y \ --configitem CONFIG_KCOV_DATAFLOW_ARGS=y \ --configitem CONFIG_KCOV_DATAFLOW_RET=y \ --configitem CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL=y \ --configitem CONFIG_DEBUG_INFO=y \ --configitem CONFIG_RUST=y \ LLVM=1 CC=clang Link: https://github.com/yskzalloc/kcov-dataflow/ Cc: Peter Zijlstra <[email protected]> Cc: Alexander Potapenko <[email protected]> Cc: Nicolas Schier <[email protected]> Signed-off-by: Yunseong Kim <[email protected]>
…lues Add a new tracking mechanism that captures function arguments/return values at instrumented function boundaries via submitted as an LLVM RFC SanitizerCoverage callbacks: __sanitizer_cov_trace_args __sanitizer_cov_trace_ret This requires a custom LLVM/Clang build with the trace-args/ret passes: LLVM RFC: https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026 LLVM PR: llvm/llvm-project#201410 Core implementation in kernel/kcov_dataflow.c (separating from kcov.c as Alexander's request): - Per-task lock-free ring buffer via debugfs kcov_dataflow device - READ_ONCE/WRITE_ONCE atomic pattern (tested on arm64) - copy_from_kernel_nofault() for safe struct field reads - in_task() guard rejects interrupt context - Bit-31 recursion guard prevents INSTRUMENT_ALL re-entry - Barriers after setting/clearing guard and enable/disable to ensure correct ordering (paired comments document each barrier) Build system (scripts/Makefile.kcov, scripts/Makefile.lib): - CFLAGS_KCOV_DATAFLOW: -fsanitize-coverage=trace-args,trace-ret - RUSTFLAGS_KCOV_DATAFLOW: -Cllvm-args=-sanitizer-coverage-trace-args/ret - Per-file opt-in: KCOV_DATAFLOW_file.o := y - Respects KCOV_INSTRUMENT := n for noinstr exclusion - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL for whole-kernel Kconfig (lib/Kconfig.debug): - CONFIG_KCOV_DATAFLOW_ARGS / CONFIG_KCOV_DATAFLOW_RET - Depends on CONFIG_KCOV and CONFIG_DEBUG_INFO - CONFIG_KCOV_DATAFLOW_NO_INLINE - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL Safety: - Exclude kcov_dataflow.o from KCOV, KASAN, KCSAN, UBSAN, and KMSAN instrumentation to prevent infinite recursion - Reject enable on multiple dataflow fds simultaneously - Clear dataflow fields on fork (prevent parent buffer sharing) - Clean up dataflow state on task exit (prevent use-after-free) - Fix INIT_TRACK race by rechecking df->area after re-acquiring lock Rust support requires rustc built against the custom LLVM with trace-args/ret passes compiled in: https://github.com/yskzalloc/rust Also fix rust/kernel/str.rs unused import (flags::* -> flags::GFP_KERNEL) which newer rustc (1.98-nightly) rejects as a hard error. Clone and build toolchain: git clone --recursive --depth 1 --shallow-submodules \ --jobs `nproc` https://github.com/yskzalloc/kcov-dataflow.git cd kcov-dataflow cd llvm-project cmake -S llvm -B build -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_C_COMPILER=clang \ -DCMAKE_CXX_COMPILER=clang++ \ -DLLVM_ENABLE_LLD=ON \ -DLLVM_ENABLE_PROJECTS="clang;lld" \ -DLLVM_TARGETS_TO_BUILD="X86;AArch64" ninja -C build cd .. Build and boot kernel (using virtme-ng): export PATH=$PWD/llvm-project/build/bin:$PATH cd linux vng --build \ --configitem CONFIG_KCOV=y \ --configitem CONFIG_KCOV_DATAFLOW_ARGS=y \ --configitem CONFIG_KCOV_DATAFLOW_RET=y \ --configitem CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL=y \ --configitem CONFIG_DEBUG_INFO=y \ --configitem CONFIG_RUST=y \ LLVM=1 CC=clang Link: https://github.com/yskzalloc/kcov-dataflow/ Cc: Peter Zijlstra <[email protected]> Cc: Alexander Potapenko <[email protected]> Cc: Nicolas Schier <[email protected]> Signed-off-by: Yunseong Kim <[email protected]>
…lues Add a new tracking mechanism that captures function arguments/return values at instrumented function boundaries via submitted as an LLVM RFC SanitizerCoverage callbacks: __sanitizer_cov_trace_args __sanitizer_cov_trace_ret This requires a custom LLVM/Clang build with the trace-args/ret passes: LLVM RFC: https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026 LLVM PR: llvm/llvm-project#201410 Core implementation in kernel/kcov_dataflow.c (separating from kcov.c as Alexander's request): - Per-task lock-free ring buffer via debugfs kcov_dataflow device - READ_ONCE/WRITE_ONCE atomic pattern (tested on arm64) - copy_from_kernel_nofault() for safe struct field reads - in_task() guard rejects interrupt context - Bit-31 recursion guard prevents INSTRUMENT_ALL re-entry - Barriers after setting/clearing guard and enable/disable to ensure correct ordering (paired comments document each barrier) Build system (scripts/Makefile.kcov, scripts/Makefile.lib): - CFLAGS_KCOV_DATAFLOW: -fsanitize-coverage=trace-args,trace-ret - RUSTFLAGS_KCOV_DATAFLOW: -Cllvm-args=-sanitizer-coverage-trace-args/ret - Per-file opt-in: KCOV_DATAFLOW_file.o := y - Respects KCOV_INSTRUMENT := n for noinstr exclusion - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL for whole-kernel Kconfig (lib/Kconfig.debug): - CONFIG_KCOV_DATAFLOW_ARGS / CONFIG_KCOV_DATAFLOW_RET - Depends on CONFIG_KCOV and CONFIG_DEBUG_INFO - CONFIG_KCOV_DATAFLOW_NO_INLINE - CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL Safety: - Exclude kcov_dataflow.o from KCOV, KASAN, KCSAN, UBSAN, and KMSAN instrumentation to prevent infinite recursion - Reject enable on multiple dataflow fds simultaneously - Clear dataflow fields on fork (prevent parent buffer sharing) - Clean up dataflow state on task exit (prevent use-after-free) - Fix INIT_TRACK race by rechecking df->area after re-acquiring lock Rust support requires rustc built against the custom LLVM with trace-args/ret passes compiled in: https://github.com/yskzalloc/rust Also fix rust/kernel/str.rs unused import (flags::* -> flags::GFP_KERNEL) which newer rustc (1.98-nightly) rejects as a hard error. Clone and build toolchain: git clone --recursive --depth 1 --shallow-submodules \ --jobs `nproc` https://github.com/yskzalloc/kcov-dataflow.git cd kcov-dataflow cd llvm-project cmake -S llvm -B build -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_C_COMPILER=clang \ -DCMAKE_CXX_COMPILER=clang++ \ -DLLVM_ENABLE_LLD=ON \ -DLLVM_ENABLE_PROJECTS="clang;lld" \ -DLLVM_TARGETS_TO_BUILD="X86;AArch64" ninja -C build cd .. Build and boot kernel (using virtme-ng): export PATH=$PWD/llvm-project/build/bin:$PATH cd linux vng --build \ --configitem CONFIG_KCOV=y \ --configitem CONFIG_KCOV_DATAFLOW_ARGS=y \ --configitem CONFIG_KCOV_DATAFLOW_RET=y \ --configitem CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL=y \ --configitem CONFIG_DEBUG_INFO=y \ --configitem CONFIG_RUST=y \ LLVM=1 CC=clang Link: https://github.com/yskzalloc/kcov-dataflow/ Cc: Peter Zijlstra <[email protected]> Cc: Alexander Potapenko <[email protected]> Cc: Nicolas Schier <[email protected]> Signed-off-by: Yunseong Kim <[email protected]>
|
#218254 is marked #218265 is maybe interesting, but it's merged into kernel (which doesn't use compiler-rt, libgcc, or any compiler runtime), then I care less about userspace having an equivalent. |
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
|
I would like to thank @melver and @nickdesaulniers for reviewing my v1 implementation. The initial version was primarily focused on functionality. I've been working on v2, improving the PR structure and addressing the feedback. Thank you! |
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
…lues
KCOV records which code a task reached. kcov_dataflow records what values
flowed through it: the arguments an instrumented function was called with
and the value it returned, per task, in execution order. This gives a
coverage-guided fuzzer a signal that plain edge coverage cannot provide
two calls to the same function with different arguments look identical to
edge coverage but differ here.
The values come from two SanitizerCoverage callbacks the compiler inserts
at function boundaries:
__sanitizer_cov_trace_args at entry, once per argument
__sanitizer_cov_trace_ret at return
For a pointer to a struct the callback passes the field offset table the
compiler derived from DWARF, and the kernel expands the struct into its
individual field values rather than recording an opaque address. Reads of
traced memory use copy_from_kernel_nofault() (a typed get_kernel_nofault()
for the 1/2/4/8-byte scalar cases), so a NULL or ERR_PTR the callee
received is recorded as KCOV_DF_MAGIC_BAD instead of faulting.
The passes are not upstream; they need a clang/rustc built with the
trace-args/trace-ret RFC [1]. When a task has no session enabled
the whole path is one boolean check.
Core (kernel/kcov_dataflow.c, split out of kcov.c on request):
- Own debugfs device /sys/kernel/debug/kcov_dataflow with its own ioctl
namespace ('d') and per-task mmap'd buffer, independent of KCOV, so
both can run at once.
- The session is a refcounted object (kcov_df_get/put) with a
back-pointer from the task, mirroring mainline kcov's t->kcov: fd close
from a sibling thread, a forked child, and task exit can no longer race
into a use-after-free. task_struct gains kcov_df and the small
kcov_df_* working set (include/linux/sched.h); fork clears it
(kernel/fork.c) and exit tears any session down (kernel/exit.c).
- Local (KCOV_DF_ENABLE) writes reserve buffer space with a plain area[0]
update; remote (KCOV_DF_REMOTE_ENABLE) writes merge with a bounded
atomic64_try_cmpxchg() loop. The two are mutually exclusive on one
buffer, so they never both update area[0].
- kcov_df_inert_context() rejects !in_task() and, crucially,
pagefault_disabled() context. The trace-cmp callback is reachable from
the ORC unwinder that KASAN runs on every slab free
(stack_trace_save()); copy_from_kernel_nofault() brackets its loads
with pagefault_disable(), so gating on that flag contains a whole class
of self-instrumentation storms that would otherwise trip the
soft-lockup watchdog, with no coverage exclusion needed in mm/ or arch/.
- A per-task sequence guard (bit 31) suppresses re-entry nested inside
our own callback under INSTRUMENT_ALL.
uapi (include/uapi/linux/kcov_dataflow.h): area[0] counts the record words
that follow; each record is a header word (sequence, type, value count,
size, argument index), the instrumented PC with the KASLR offset removed
like the PCs mainline kcov records, the traced pointer (ENTRY/RET) or the
comparison type (CMP), then the value words.
kcov.c: the __sanitizer_cov_trace_cmp*() / trace_switch() callbacks now
route their operand pairs through kcov_trace_cmp() in <linux/kcov.h>,
which feeds both the existing KCOV_MODE_TRACE_CMP buffer and, when a
dataflow session is live, the dataflow buffer; kcov.c itself no longer
references dataflow. kcov_check_handle() moves to <linux/kcov.h> as a
static inline so kcov_dataflow.c can validate KCOV_DF_REMOTE_ENABLE
handles with it.
objtool (tools/objtool/check.c): list kcov_df_trace_cmp() and the two
trace-args/ret entry points in uaccess_safe_builtin[], next to their
mainline peer write_comp_data(). The compiler emits the cmp callbacks
inside user_access_begin()/end() regions, and calling out of such a region
is only allowed to listed functions. They qualify on the same grounds:
notrace, __no_sanitize_coverage, no locks, no allocation, storing only
into the task's own buffer; kcov_df_reserve() is __always_inline so the
property does not depend on an inlining decision.
Build system (scripts/Makefile.kcov, scripts/Makefile.lib):
- CFLAGS_KCOV_DATAFLOW = -fsanitize-coverage=trace-args,trace-ret (plus
-fno-inline under CONFIG_KCOV_DATAFLOW_NO_INLINE), and the matching
RUSTFLAGS for Rust objects.
- Per-file opt-in KCOV_DATAFLOW_<obj>.o := y, or whole-kernel with
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL; KCOV_INSTRUMENT := n still excludes
noinstr objects.
- kcov_dataflow.o is built without KCOV, KASAN, KCSAN, UBSAN or KMSAN
instrumentation to keep the collector from tracing itself.
Kconfig (lib/Kconfig.debug): CONFIG_KCOV_DATAFLOW_ARGS / _RET (depend on
KCOV, CC_IS_CLANG, DEBUG_INFO and the cc-option/rustc-option probe for the
pass), CONFIG_KCOV_DATAFLOW_NO_INLINE and
CONFIG_KCOV_DATAFLOW_INSTRUMENT_ALL. Because the options gate on
cc-option, a stock clang simply leaves them unset rather than failing.
[1] https://discourse.llvm.org/t/rfc-sanitizercoverage-add-fsanitize-coverage-trace-args-trace-ret/91026
[2] llvm/llvm-project#201410
[3] llvm/llvm-project#218254
[4] llvm/llvm-project#218265
Link: https://github.com/yskzalloc/kcov-dataflow/
Signed-off-by: Yunseong Kim <[email protected]>
| #include "llvm/IR/Constant.h" | ||
| #include "llvm/IR/Constants.h" | ||
| #include "llvm/IR/DataLayout.h" | ||
| #include "llvm/IR/DebugInfoMetadata.h" |
There was a problem hiding this comment.
Before this works, Line 997, DILocation::get and DISubprogram were already used in InjectCoverageAtBlock prior to this patch (transitively included via llvm/IR/IntrinsicInst.h), but I added the header explicitly following IWYU. Happy to remove it if reviewer prefer keeping includes minimal.
|
Based on reviewer's feedback at Linux Plumbers, I've implemented a minimal version. I've checked GitHub CI result and confirmed that tracing works correctly for function scalar arguments and Object return value, both x86_64 and arm64 at the linux kernel side, I haven't sent v4 yet. I'll send the kernel patch once the LLVM side is ready. |
melver
left a comment
There was a problem hiding this comment.
Good simplification, but still several issues.
| // read, so they are read as bytes: the table of a byte array that long. | ||
| FieldOffsets Offsets = | ||
| getObjectOffsets(ArrayType::get(IRB.getInt8Ty(), Bytes)); | ||
| if (!isGuaranteedNotToBeUndefOrPoison(Ptr)) |
There was a problem hiding this comment.
dereferenceable(N) without noundef does not exclude poison; freeze of poison is an arbitrary address, which the runtime then reads N bytes from. Gate on noundef instead and drop the freeze - in callers:
else if (uint64_t Bytes = Arg.hasAttribute(Attribute::NoUndef) ? getPointeeBytes(...) : 0)
and F.hasRetAttribute(Attribute::NoUndef) for returns.
There was a problem hiding this comment.
I have updated both InjectTraceForArgs and InjectTraceForRet to gate pointee snapshotting on NoUndef (Arg.hasAttribute(Attribute::NoUndef) and F.hasRetAttribute(Attribute::NoUndef)).
Pointers without noundef now safely fall back to traceValue (reported by value with num_fields == 0), and the redundant CreateFreeze inside tracePointee has been removed.
| // void __sanitizer_cov_trace_args(u32 arg_idx, u32 size, u64 val, | ||
| // u64 *offsets, u32 num_fields) | ||
| SanCovTraceArgsFunc = M.getOrInsertFunction( | ||
| SanCovTraceArgsName, VoidTy, Int32Ty, Int32Ty, Int64Ty, PtrTy, Int32Ty); |
There was a problem hiding this comment.
Three bare i32 params, no zeroext/signext. On RV64/MIPS64/PPC64 the callee may rely on extension; SanCovTraceCmpZeroExtAL exists in this file for exactly this. Prefer a signature with no sub-register ints: pack arg_idx<<32|size into one u64 like trace_cmp's (type_size<<32)|predicate.
There was a problem hiding this comment.
Thanks again for the suggestion. I have updated the callback signatures to eliminate all sub-register integer parameters. arg_idx (high 32 bits) and size (low 32 bits) are now packed into a single u64 tag ((arg_idx << 32) | size), mirroring the (type_size << 32) | predicate pattern used by trace_cmp.
| @@ -1183,3 +1258,352 @@ void ModuleSanitizerCoverage::createFunctionControlFlow(Function &F) { | |||
| ConstantArray::get(ArrayType::get(PtrTy, CFs.size()), CFs)); | |||
| FunctionCFsArray->setConstant(true); | |||
| } | |||
|
|
|||
| //===----------------------------------------------------------------------===// | |||
There was a problem hiding this comment.
Is the table needed at all? The pointee path already ships raw 8-byte pieces, [N x T] is flattened too, and the stated model is "consumer cuts with DWARF offline". With it gone the contract is (arg_idx, size, val, by_address): FieldOffsets, getObjectOffsets, ObjectOffsetsCache, __sancov_offsets_* and ~90 lines disappear, 2 params per call with them.
If it must stay: count in table[0] as __sanitizer_cov_trace_switch does with Cases[0], and drop num_fields.
Either way, move this text to clang/docs/SanitizerCoverage.md (#227614) and leave a one-line pointer.
There was a problem hiding this comment.
Thank you @melver for this fundamental design feedback. I especially appreciate you considering the "if it must stay" case as well. You rightly note that offline DWARF symbolization does not need this table.
I believe the table should be retained because it is essential for future online consumers operating without DWARF, which are planned for follow-up patches:
libFuzzer(-use_value_profile=1): Needs field boundaries to slice aggregates and fold distinct member values into the value-profile map at runtime without the heavy overhead of an in-process DWARF parser.- Linux Kernel KCOV: Collects structured observations in-kernel where DWARF is unavailable.
I have adopted your table[0] suggestion (mirroring __sanitizer_cov_trace_switch with Cases[0]).
Combined with packing (arg_idx << 32) | size, the callback signature slims down to just 3 arguments, forming a self-describing TLV contract:
// TLV contract:
// - tag: (Tag: arg_idx << 32) | (Length: byte size)
// - val: Value (scalar bits, or payload buffer address)
// - offsets: nullptr for scalars; otherwise layout descriptor:
// offsets[0] = NumFields, followed by NumFields [offset, size] pairs.
void __sanitizer_cov_trace_args(uint64_t tag, uint64_t val, const uint64_t *offsets);
void __sanitizer_cov_trace_ret (uint64_t size, uint64_t val, const uint64_t *offsets);For aggregate objects, offsets acts as an in-memory descriptor enabling online consumers to unpack the val payload into individual field values without DWARF metadata.
I will also move the lengthy rationale block from SanitizerCoverage.cpp into clang/docs/SanitizerCoverage.md, leaving only a concise one-line pointer in the source as suggested.
|
|
||
| void ModuleSanitizerCoverage::InjectTraceForArgs(Function &F) { | ||
| BasicBlock &EntryBB = F.getEntryBlock(); | ||
| BasicBlock::iterator IP = EntryBB.getFirstInsertionPt(); |
There was a problem hiding this comment.
Entry block cannot be an EH pad; getFirstInsertionPt() never returns end() here. Dead check.
Use PrepareToSplitEntryBlock(EntryBB, IP) like InjectCoverageAtBlock, otherwise with allocas in the entry block the order is args; alloca; pc_entry. With it, inserting before the same anchor twice preserves order and you get pc_entry; args.
There was a problem hiding this comment.
Done. Removed the dead IP == EntryBB.end() check. Added IP = PrepareToSplitEntryBlock(EntryBB, IP); as suggested, ensuring all static allocas remain grouped at the top of the entry block and preserving the canonical instrumentation order (pc_entry; args).
| @@ -684,6 +753,12 @@ void ModuleSanitizerCoverage::instrumentFunction(Function &F) { | |||
|
|
|||
| if (Options.TracePCEntryExit) | |||
| InjectTraceForExits(F); | |||
|
|
|||
| if (Options.TraceArgs) | |||
| InjectTraceForArgs(F); | |||
There was a problem hiding this comment.
Run InjectTraceForRet before InjectTraceForExits so the order at a return is ret_val; pc_exit; ret, matching entry; args at the top. Currently it is pc_exit; ret_val.
There was a problem hiding this comment.
Done. Moved InjectTraceForRet before InjectTraceForExits, establishing the canonical return order: ret_val; pc_exit; ret (symmetrically mirroring pc_entry; args on entry).
| @@ -0,0 +1,36 @@ | |||
| ; Debug information must not change the machine code of trace-args/trace-ret | |||
There was a problem hiding this comment.
This proves that identical IR modulo debug metadata yields identical .text - an LLVM-wide invariant, not this pass's. Instrumentation tests do not run llc. The IR-level diff in trace-args-debug-invariance.ll is the real property. Drop.
| @@ -0,0 +1,36 @@ | |||
| ; Debug information must not change the machine code of trace-args/trace-ret | |||
There was a problem hiding this comment.
This proves that identical IR modulo debug metadata yields identical .text - an LLVM-wide invariant, not this pass's. Instrumentation tests do not run llc. The IR-level diff in trace-args-debug-invariance.ll is the real property. Drop.
| @@ -0,0 +1,67 @@ | |||
| ; Neither mode ever creates memory to report a value from, on any target: a | |||
There was a problem hiding this comment.
The property is now structural (no CreateAlloca in the pass). One ; CHECK-NOT: alloca in trace-args.ll; the rbx narrative is v2 history.
There was a problem hiding this comment.
Done. Deleted trace-no-spill.ll since the pass structurally does not emit allocas (no CreateAlloca exists in the pass), and added a ; CHECK-NOT: alloca check in trace-args.ll.
| ; CHECK-NOT: call void @__sanitizer_cov_trace_args( | ||
|
|
||
| ; The calls go at the first insertion point of the entry block, after its PHI | ||
| ; nodes and EH pad, where every argument is available. They are never tail |
There was a problem hiding this comment.
Entry block has neither PHIs nor an EH pad. The test shows the call is first and notail; say that.
There was a problem hiding this comment.
I fixed it as ; The calls are first in the entry block and are notail: the runtime identifies an observation by its call's return address.
| @@ -0,0 +1,230 @@ | |||
| ; Argument tracing: one __sanitizer_cov_trace_args call per IR argument, in the | |||
There was a problem hiding this comment.
Please add: a nested first-class aggregate ({ i64, { i32, i32 } }) and a function with an alloca in the entry block together with -sanitizer-coverage-trace-pc-entry-exit, checking pc_entry precedes trace_args.
There was a problem hiding this comment.
- I've added added
@nested_aggregatetesting{ i64, { i32, i32 } }noundef arguments, verifying recursive leaf extraction and tagging under the samearg_idx. - I've added a RUN line with
-sanitizer-coverage-trace-pc-entry-exitand@entry_alloca, and updatedInjectTraceForArgsinSanitizerCoverage.cppto advance pastpc_entry/pcafterPrepareToSplitEntryBlock, ensuring static allocas remain first followed bypc_entrybeforetrace_args.
Add two SanitizerCoverage modes that report the values flowing into and
out of instrumented functions. trace-args emits one call per IR argument
at function entry; trace-ret emits one call before every return:
void __sanitizer_cov_trace_args(u64 tag, u64 val, const u64 *offsets);
void __sanitizer_cov_trace_ret(u64 size, u64 val, const u64 *offsets);
`tag` is (arg_idx << 32) | size, where arg_idx is the position in the IR
parameter list. If `offsets` is null, `val` is the value itself,
zero-extended to 64 bits. Otherwise `val` is the address of `size`
bytes, and `offsets` points to a constant table: offsets[0] is the
number N of {byte offset, byte size} pairs that follow, each at most
8 bytes. This form reports byval/byref/inalloca/preallocated arguments
and sret buffers, described by the elements of their IR type, and
pointers that are noundef and dereferenceable(N) or
dereferenceable_or_null(N), snapshotted up to
-sanitizer-coverage-trace-pointee-bytes (default 64). A size of 0 means
nothing was reported.
The modes are enabled through SanitizerCoverageOptions::TraceArgs and
TraceRet or, for opt, -sanitizer-coverage-trace-args and
-sanitizer-coverage-trace-ret. Like the other modes, they need a
coverage level. They do not imply trace-pc-guard.
What is emitted depends only on the IR. Debug information gives the
calls a location and nothing else, so -g does not change the
instrumentation. The pass creates no allocas. The calls are notail and
nomerge, because a runtime identifies an observation by its return
address, as with trace-cmp.
Assisted-by: Kiro CLI (Claude Opus 5.5)
Signed-off-by: Yunseong Kim <[email protected]>
Adds two SanitizerCoverage modes that report the values flowing into and out of instrumented functions.
trace-argsemits one call per IR argument at function entry, andtrace-retemits one call before every return.The modes are enabled through
SanitizerCoverageOptions::TraceArgsandTraceRet, or, foropt,-sanitizer-coverage-trace-argsand-sanitizer-coverage-trace-ret. Like the other modes, they need a coverage level. They do not implytrace-pc-guard.This is PR 1 of a 4-PR stack:
-fsanitize-coverage=trace-args,trace-retdriver and frontend support, [Clang][SanitizerCoverage] Add -fsanitize-coverage=trace-args,trace-ret #218254Callback contract
tagis(arg_idx << 32) | size.arg_idxis the position in the IR parameter list, which is the ABI's view of the signature, not the source parameter number. Ansretpointer and a Swift error slot are not observed, but they keep their positions.What
valholds depends onoffsets:offsets == nullptr:valis the value itself, zero-extended to 64 bits. This covers integers, pointers (the address they hold), floating-point values and vectors (their bit pattern). A first-class aggregate is reported one leaf element per call, all under itsarg_idx.offsets != nullptr:valis the address ofsizebytes, andoffsetspoints to a constant table.offsets[0]is the number N of{byte offset, byte size}pairs that follow, none wider than 8 bytes. This form is used for:byval,byref,inallocaandpreallocatedarguments, and thesretbuffer of an indirect return, described by the elements of their IR type;noundefanddereferenceable(N)ordereferenceable_or_null(N), snapshotted up to-sanitizer-coverage-trace-pointee-bytesbytes (default 64).Nothing else causes a read behind a pointer.
A
sizeof 0 means nothing was reported: avoidreturn, a value with no fixed-size bit pattern, or an object the function does not use.What is emitted depends only on the IR. Debug information gives the calls a location and nothing else, so
-gdoes not change the instrumentation. The pass creates no allocas.Call sites
Neither callback is told which function it reports for. A runtime identifies an observation by its own return address, as with the
trace-cmpcallbacks. That is why the calls arenotailandnomerge.With
trace-pc-entry-exit, the order ispc_entry; trace_argsat entry andtrace_ret; pc_exit; retat each return.Motivation
Relation to trace-pc-entry-exit
__sanitizer_cov_trace_pc_entry()__sanitizer_cov_trace_args(...), one per IR argument__sanitizer_cov_trace_pc_exit()__sanitizer_cov_trace_ret(...), before every returnThe two are complementary:
trace-pc-entry-exitshows which functions ran and in what order, whiletrace-args/trace-retshow what values flowed through them.Testing
trace-args.llcovers:sretandswifterror;noundef, unused, another address space);notailcalls and no allocas;trace-pc-entry-exit.trace-ret.llcovers every kind of return, includingsret, aggregate,musttailand unwinding returns.trace-args-debug-invariance.llchecks that instrumenting then stripping debug information gives the same module as stripping then instrumenting.I used an AI coding assistant (Kiro CLI) while preparing this change and its tests for double checking, and I reviewed and verified everything myself.
References
trace-pc-entry-exit)This project is heavily influenced by uftrace, developed by Linux kernel maintainer @namhyung and uftrace maintainer @honggyukim.
cc @vitalybuka @dvyukov