mm/ksw: Introduce real-time KStackWatch debugging tool
Subsystems (8)
v5 cover mm/ksw: Introduce real-time KStackWatch debugging tool
This patch series introduces KStackWatch, a lightweight debugging tool to detect kernel stack corruption in real time. It installs a hardware breakpoint (watchpoint) at a function's specified offset using kprobe.post_handler and removes it in fprobe.exit_handler. This covers the full execution window and reports corruption immediately with time, location, and a call stack.
The motivation comes from scenarios where corruption occurs silently in one function but manifests later in another, without a direct call trace linking the two. Such bugs are often extremely hard to debug with existing tools. These scenarios are demonstrated in test 3–5 (silent corruption test, patch 20).
Key features include:
* Immediate and precise corruption detection
* Support multiple watchpoints for concurrently called functions
* Lockless design, usable in any context
* Depth filter for recursive calls
* Minimal impact on reproducibility
* Flexible procfs configuration with key=val syntax
To validate the approach, the patch includes a test module and a test script.
There is a workflow example described in detail in the documentation (patch 22). Please read the document first if you want an overview.
---
Patches 1–3 of this series are also used in the wprobe work proposed by Masami Hiramatsu, so there may be some overlap between our patches. Patch 3 comes directly from Masami Hiramatsu (thanks).
---
Changelog
V5:
* Support key=value input format
* Support multiple watchpoints
* Support watching instruction inside loop
* Support recursion depth tracking with generation
* Ignore triggers from fprobe trampoline
* Split watch_on into watch_get and watch_on to fail fast
* Handle ksw_stack_prepare_watch error
* Rewrite silent corruption test
* Add multiple watchpoints test
* Add an example in documentation
V4:
https://lore.kernel.org/all/[email protected]/
* Solve the lockdep issues with:
* per-task KStackWatch context to track depth
* atomic flag to protect watched_addr
* Use refactored version of arch_reinstall_hw_breakpoint
V3:
https://lore.kernel.org/all/[email protected]/
* Use modify_wide_hw_breakpoint_local() (from Masami)
* Add atomic flag to restrict /proc/kstackwatch to a single opener
* Protect stack probe with an atomic PID flag
* Handle CPU hotplug for watchpoints
* Add preempt_disable/enable in ksw_watch_on_local_cpu()
* Introduce const struct ksw_config *ksw_get_config(void) and use it
* Switch to global watch_attr, remove struct watch_info
* Validate local_var_len in parser()
* Handle case when canary is not found
* Use dump_stack() instead of show_regs() to allow module build
* Reduce logging and comments
* Format logs with KBUILD_MODNAME
* Remove unused headers
* Add new document
V2:
https://lore.kernel.org/all/[email protected]/
* Make hardware breakpoint and stack operations architecture-independent.
V1:
https://lore.kernel.org/all/[email protected]/
* Replaced kretprobe with fprobe for function exit hooking, as suggested by Masami Hiramatsu
* Introduced per-task depth logic to track recursion across scheduling
* Removed the use of workqueue for a more efficient corruption check
* Reordered patches for better logical flow
* Simplified and improved commit messages throughout the series
* Removed initial archcheck which should be improved later
* Replaced the multiple-thread test with silent corruption test
* Split self-tests into a separate patch to improve clarity.
* Added a new entry for KStackWatch to the MAINTAINERS file.
RFC:
https://lore.kernel.org/lkml/[email protected]/
---
The series is structured as follows:
Jinchao Wang (22):
x86/hw_breakpoint: Unify breakpoint install/uninstall x86/hw_breakpoint: Add arch_reinstall_hw_breakpoint mm/ksw: add build system support
mm/ksw: add ksw_config struct and parser mm/ksw: add singleton /proc/kstackwatch interface mm/ksw: add HWBP pre-allocation
mm/ksw: Add atomic watchpoint management api mm/ksw: ignore false positives from exit trampolines mm/ksw: support CPU hotplug
sched: add per-task context
mm/ksw: add entry kprobe and exit fprobe management mm/ksw: add per-task ctx tracking
mm/ksw: resolve stack watch addr and len mm/ksw: manage probe and HWBP lifecycle via procfs mm/ksw: add self-debug helpers
mm/ksw: add test module
mm/ksw: add stack overflow test
mm/ksw: add recursive depth test
mm/ksw: add multi-thread corruption test cases tools/ksw: add test script
docs: add KStackWatch document
MAINTAINERS: add entry for KStackWatch
Masami Hiramatsu (Google) (1):
HWBP: Add modify_wide_hw_breakpoint_local() API
Documentation/dev-tools/index.rst | 1 + Documentation/dev-tools/kstackwatch.rst | 316 ++++++++++++++++++++++ MAINTAINERS | 8 + arch/Kconfig | 10 + arch/x86/Kconfig | 1 + arch/x86/include/asm/hw_breakpoint.h | 8 + arch/x86/kernel/hw_breakpoint.c | 148 ++++++----- include/linux/hw_breakpoint.h | 6 + include/linux/kstackwatch_types.h | 14 + include/linux/sched.h | 5 + kernel/events/hw_breakpoint.c | 37 +++ mm/Kconfig.debug | 18 ++ mm/Makefile | 1 + mm/kstackwatch/Makefile | 8 + mm/kstackwatch/kernel.c | 263 +++++++++++++++++++ mm/kstackwatch/kstackwatch.h | 58 +++++ mm/kstackwatch/stack.c | 240 +++++++++++++++++ mm/kstackwatch/test.c | 332 ++++++++++++++++++++++++ mm/kstackwatch/watch.c | 305 ++++++++++++++++++++++ tools/kstackwatch/kstackwatch_test.sh | 52 ++++ 20 files changed, 1769 insertions(+), 62 deletions(-) create mode 100644 Documentation/dev-tools/kstackwatch.rst create mode 100644 include/linux/kstackwatch_types.h create mode 100644 mm/kstackwatch/Makefile create mode 100644 mm/kstackwatch/kernel.c create mode 100644 mm/kstackwatch/kstackwatch.h create mode 100644 mm/kstackwatch/stack.c create mode 100644 mm/kstackwatch/test.c create mode 100644 mm/kstackwatch/watch.c create mode 100755 tools/kstackwatch/kstackwatch_test.sh
Signature · 1 line
2.43.0
PATCH v5 1/23 x86/hw_breakpoint: Unify breakpoint install/uninstall
Consolidate breakpoint management to reduce code duplication. The diffstat was misleading, so the stripped code size is compared instead. After refactoring, it is reduced from 11976 bytes to 11448 bytes on my x86_64 system built with clang.
This also makes it easier to introduce arch_reinstall_hw_breakpoint().
In addition, including linux/types.h to fix a missing build dependency.
--- arch/x86/include/asm/hw_breakpoint.h | 6 ++ arch/x86/kernel/hw_breakpoint.c | 141 +++++++++++++++------------ 2 files changed, 84 insertions(+), 63 deletions(-)
arch/x86/include/asm/hw_breakpoint.h +6 -0
@@ -5,6 +5,7 @@#include <uapi/asm/hw_breakpoint.h> #define __ARCH_HW_BREAKPOINT_H +#include <linux/types.h> /* * The name should probably be something dealt in
@@ -18,6 +19,11 @@ struct arch_hw_breakpoint {u8 type; }; +enum bp_slot_action { +BP_SLOT_ACTION_INSTALL , +BP_SLOT_ACTION_UNINSTALL , +}; +#include <linux/kdebug.h> #include <linux/percpu.h> #include <linux/list.h>
arch/x86/kernel/hw_breakpoint.c +78 -63
181 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH v5 2/23 x86/hw_breakpoint: Add arch_reinstall_hw_breakpoint
In reply to Jinchao WangThe new arch_reinstall_hw_breakpoint() function can be used in an atomic context, unlike the more expensive free and re-allocation path. This allows callers to efficiently re-establish an existing breakpoint.
--- arch/x86/include/asm/hw_breakpoint.h | 2 ++ arch/x86/kernel/hw_breakpoint.c | 9 +++++++++ 2 files changed, 11 insertions(+)
arch/x86/include/asm/hw_breakpoint.h +2 -0
@@ -21,6 +21,7 @@ struct arch_hw_breakpoint {enum bp_slot_action {BP_SLOT_ACTION_INSTALL , +BP_SLOT_ACTION_REINSTALL ,BP_SLOT_ACTION_UNINSTALL , };
@@ -65,6 +66,7 @@ extern int hw_breakpoint_exceptions_notify(struct notifier_block *unused,int arch_install_hw_breakpoint (struct perf_event *bp); +int arch_reinstall_hw_breakpoint (struct perf_event *bp);void arch_uninstall_hw_breakpoint (struct perf_event *bp);void hw_breakpoint_pmu_read (struct perf_event *bp);void hw_breakpoint_pmu_unthrottle (struct perf_event *bp);
arch/x86/kernel/hw_breakpoint.c +9 -0
@@ -99,6 +99,10 @@ static int manage_bp_slot(struct perf_event *bp, enum bp_slot_action action) old_bp =NULL ; new_bp = bp;break ; +case BP_SLOT_ACTION_REINSTALL : + old_bp = bp; + new_bp = bp; +break ;case BP_SLOT_ACTION_UNINSTALL : old_bp = bp; new_bp =NULL ;
@@ -187,6 +191,11 @@ int arch_install_hw_breakpoint(struct perf_event *bp)return arch_manage_bp (bp,BP_SLOT_ACTION_INSTALL ); } +int arch_reinstall_hw_breakpoint (struct perf_event *bp) +{ +return arch_manage_bp (bp,BP_SLOT_ACTION_REINSTALL ); +} +void arch_uninstall_hw_breakpoint (struct perf_event *bp) {arch_manage_bp (bp,BP_SLOT_ACTION_UNINSTALL );
Signature · 1 line
2.43.0
PATCH v5 3/23 HWBP: Add modify_wide_hw_breakpoint_local() API
In reply to Jinchao WangFrom: "Masami Hiramatsu (Google)" <[email protected]>
Add modify_wide_hw_breakpoint_local() arch-wide interface which allows hwbp users to update watch address on-line. This is available if the arch supports CONFIG_HAVE_REINSTALL_HW_BREAKPOINT.
Note that this allows to change the type only for compatible types, because it does not release and reserve the hwbp slot based on type. For instance, you can not change HW_BREAKPOINT_W to HW_BREAKPOINT_X.
--- arch/Kconfig | 10 ++++++++++ arch/x86/Kconfig | 1 + include/linux/hw_breakpoint.h | 6 ++++++ kernel/events/hw_breakpoint.c | 37 +++++++++++++++++++++++++++++++++++ 4 files changed, 54 insertions(+)
arch/Kconfig +10 -0
@@ -418,6 +418,16 @@ config HAVE_MIXED_BREAKPOINTS_REGS Select this option if your arch implements breakpoints under the latter fashion. +config HAVE_REINSTALL_HW_BREAKPOINT + bool + depends on HAVE_HW_BREAKPOINT + help + Depending on the arch implementation of hardware breakpoints, + some of them are able to update the breakpoint configuration + without release and reserve the hardware breakpoint register. + What configuration is able to update depends on hardware and + software implementation. + config HAVE_USER_RETURN_NOTIFIER bool
arch/x86/Kconfig +1 -0
@@ -247,6 +247,7 @@ config X86 select HAVE_FUNCTION_TRACER select HAVE_GCC_PLUGINS select HAVE_HW_BREAKPOINT + select HAVE_REINSTALL_HW_BREAKPOINT select HAVE_IOREMAP_PROT select HAVE_IRQ_EXIT_ON_IRQ_STACK if X86_64 select HAVE_IRQ_TIME_ACCOUNTING
include/linux/hw_breakpoint.h +6 -0
@@ -81,6 +81,9 @@ register_wide_hw_breakpoint(struct perf_event_attr *attr,perf_overflow_handler_t triggered, void *context); +extern int modify_wide_hw_breakpoint_local (struct perf_event *bp, +struct perf_event_attr *attr); +extern int register_perf_hw_breakpoint (struct perf_event *bp);extern void unregister_hw_breakpoint (struct perf_event *bp);extern void unregister_wide_hw_breakpoint (struct perf_event *__percpu *cpu_events);
@@ -124,6 +127,9 @@ register_wide_hw_breakpoint(struct perf_event_attr *attr,perf_overflow_handler_t triggered, void *context) { return NULL; }static inline int +modify_wide_hw_breakpoint_local (struct perf_event *bp, +struct perf_event_attr *attr) {return -ENOSYS ; } +static inline int register_perf_hw_breakpoint (struct perf_event *bp) {return -ENOSYS ; }static inline void unregister_hw_breakpoint (struct perf_event *bp) { } static inline void
kernel/events/hw_breakpoint.c +37 -0
@@ -887,6 +887,43 @@ void unregister_wide_hw_breakpoint(struct perf_event * __percpu *cpu_events) }EXPORT_SYMBOL_GPL (unregister_wide_hw_breakpoint); +/** +* modify_wide_hw_breakpoint_local - update breakpoint config for local CPU +* @bp: the hwbp perf event for this CPU +* @attr: the new attribute for @bp +* +* This does not release and reserve the slot of a HWBP; it just reuses the +* current slot on local CPU. So the users must update the other CPUs by +* themselves. +* Also, since this does not release/reserve the slot, this can not change the +* type to incompatible type of the HWBP. +* Return err if attr is invalid or the CPU fails to update debug register +* for new @attr. +*/ +#ifdef CONFIG_HAVE_REINSTALL_HW_BREAKPOINT +int modify_wide_hw_breakpoint_local (struct perf_event *bp, +struct perf_event_attr *attr) +{ +int ret; + +if (find_slot_idx (bp->attr.bp_type) !=find_slot_idx (attr->bp_type)) +return -EINVAL ; + + ret =hw_breakpoint_arch_parse (bp, attr,counter_arch_bp (bp)); +if (ret) +return ret; + +return arch_reinstall_hw_breakpoint (bp); +} +#else +int modify_wide_hw_breakpoint_local (struct perf_event *bp, +struct perf_event_attr *attr) +{ +return -EOPNOTSUPP ; +} +#endif +EXPORT_SYMBOL_GPL (modify_wide_hw_breakpoint_local); +/** * hw_breakpoint_is_used - check if breakpoints are currently used *
Signature · 1 line
2.43.0
PATCH v5 4/23 mm/ksw: add build system support
In reply to Jinchao WangAdd Kconfig and Makefile infrastructure.
The implementation is located under mm/kstackwatch/.
--- mm/Kconfig.debug | 8 ++++++++ mm/Makefile | 1 + mm/kstackwatch/Makefile | 2 ++ mm/kstackwatch/kernel.c | 23 +++++++++++++++++++++++ mm/kstackwatch/kstackwatch.h | 5 +++++ mm/kstackwatch/stack.c | 1 + mm/kstackwatch/watch.c | 1 + 7 files changed, 41 insertions(+) create mode 100644 mm/kstackwatch/Makefile create mode 100644 mm/kstackwatch/kernel.c create mode 100644 mm/kstackwatch/kstackwatch.h create mode 100644 mm/kstackwatch/stack.c create mode 100644 mm/kstackwatch/watch.c
mm/Kconfig.debug +8 -0
@@ -309,3 +309,11 @@ config PER_VMA_LOCK_STATS overhead in the page fault path. If in doubt, say N. + +config KSTACK_WATCH + bool "Kernel Stack Watch" + depends on HAVE_HW_BREAKPOINT && KPROBES && FPROBE && STACKTRACE + help + A lightweight real-time debugging tool to detect stack corrupting. + + If unsure, say N.
mm/Makefile +1 -0
@@ -92,6 +92,7 @@ obj-$(CONFIG_PAGE_POISONING) += page_poison.o obj-$(CONFIG_KASAN) += kasan/ obj-$(CONFIG_KFENCE) += kfence/ obj-$(CONFIG_KMSAN) += kmsan/ +obj-$(CONFIG_KSTACK_WATCH) += kstackwatch/ obj-$(CONFIG_FAILSLAB) += failslab.o obj-$(CONFIG_FAIL_PAGE_ALLOC) += fail_page_alloc.o obj-$(CONFIG_MEMTEST) += memtest.o
mm/kstackwatch/Makefile new file +2 -0
@@ -0,0 +1,2 @@ +obj-$(CONFIG_KSTACK_WATCH) += kstackwatch.o +kstackwatch-y := kernel.o stack.o watch.o
mm/kstackwatch/kernel.c new file +23 -0
@@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0 +#define pr_fmt (fmt) KBUILD_MODNAME ": " fmt + +#include <linux/module.h> + +static int __init kstackwatch_init (void ) +{ +pr_info ("module loaded\n" ); +return 0 ; +} + +static void __exit kstackwatch_exit(void) +{ +pr_info ("module unloaded\n" ); +} + +module_init (kstackwatch_init); +module_exit (kstackwatch_exit); + +MODULE_AUTHOR ("Jinchao Wang" ); +MODULE_DESCRIPTION ("Kernel Stack Watch" ); +MODULE_LICENSE ("GPL" ); +
mm/kstackwatch/kstackwatch.h new file +5 -0
@@ -0,0 +1,5 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _KSTACKWATCH_H +#define _KSTACKWATCH_H + +#endif /* _KSTACKWATCH_H */
mm/kstackwatch/stack.c new file +1 -0
@@ -0,0 +1 @@ +// SPDX-License-Identifier: GPL-2.0
mm/kstackwatch/watch.c new file +1 -0
@@ -0,0 +1 @@ +// SPDX-License-Identifier: GPL-2.0
Signature · 1 line
2.43.0
Randy Dunlap
reviewerRe: [PATCH v5 04/23] mm/ksw: add build system support
Quoted 25 lines · Jinchao Wang
Add
KconfigandMakefileinfrastructure.The implementation is located under
mm/kstackwatch/.Signed-off-by Jinchao Wang <[email protected]>--- mm/Kconfig.debug | 8 ++++++++ mm/Makefile | 1 + mm/kstackwatch/Makefile | 2 ++ mm/kstackwatch/kernel.c | 23 +++++++++++++++++++++++ mm/kstackwatch/kstackwatch.h | 5 +++++ mm/kstackwatch/stack.c | 1 + mm/kstackwatch/watch.c | 1 + 7 files changed, 41 insertions(+) create mode 100644 mm/kstackwatch/Makefile create mode 100644 mm/kstackwatch/kernel.c create mode 100644 mm/kstackwatch/kstackwatch.h create mode 100644 mm/kstackwatch/stack.c create mode 100644 mm/kstackwatch/watch.cmm/Kconfig.debug +0
-0
mm/Kconfig.debug config PER_VMA_LOCK_STATS · line 317
Quoted 9 lines
mm/Kconfig.debug +6
-0@@ -309,3 +309,11 @@ config PER_VMA_LOCK_STATS overhead in the page fault path. If in doubt, say N. + +config KSTACK_WATCH + bool "Kernel Stack Watch" + depends on HAVE_HW_BREAKPOINT && KPROBES && FPROBE && STACKTRACE + help + A lightweight real-time debugging tool to detect stack corrupting.
corruption.
Quoted 2 lines
mm/Kconfig.debug +2
-0+ + If unsure, say N.
Signature · 1 line
~Randy
Re: [PATCH v5 04/23] mm/ksw: add build system support
Quoted 30 lines · Randy Dunlap
Quoted 27 lines · Jinchao Wang
Add
KconfigandMakefileinfrastructure.The implementation is located under
mm/kstackwatch/.Signed-off-by Jinchao Wang <[email protected]>--- mm/Kconfig.debug | 8 ++++++++ mm/Makefile | 1 + mm/kstackwatch/Makefile | 2 ++ mm/kstackwatch/kernel.c | 23 +++++++++++++++++++++++ mm/kstackwatch/kstackwatch.h | 5 +++++ mm/kstackwatch/stack.c | 1 + mm/kstackwatch/watch.c | 1 + 7 files changed, 41 insertions(+) create mode 100644 mm/kstackwatch/Makefile create mode 100644 mm/kstackwatch/kernel.c create mode 100644 mm/kstackwatch/kstackwatch.h create mode 100644 mm/kstackwatch/stack.c create mode 100644 mm/kstackwatch/watch.cmm/Kconfig.debug +0
-0@@ -309,3 +309,11 @@ config PER_VMA_LOCK_STATS overhead in the page fault path.
Quoted 9 lines
mm/Kconfig.debug config PER_VMA_LOCK_STATS · line 317
Quoted 7 lines
mm/Kconfig.debug +6
-0If in doubt, say N. + +config KSTACK_WATCH + bool "Kernel Stack Watch" + depends on HAVE_HW_BREAKPOINT && KPROBES && FPROBE && STACKTRACE + help + A lightweight real-time debugging tool to detect stack corrupting.corruption.
Thanks, will fix in next version.
Quoted 8 lines
Quoted 3 lines
mm/Kconfig.debug +2
-0+ + If unsure, say N.Signature · 1 line
~Randy
Signature · 1 line
Jinchao
PATCH v5 5/23 mm/ksw: add ksw_config struct and parser
In reply to Jinchao WangAdd struct ksw_config and ksw_parse_config() to parse user string.
--- mm/kstackwatch/kernel.c | 112 +++++++++++++++++++++++++++++++++++ mm/kstackwatch/kstackwatch.h | 27 +++++++++ 2 files changed, 139 insertions(+)
mm/kstackwatch/kernel.c +112 -0
@@ -1,16 +1,128 @@// SPDX-License-Identifier: GPL-2.0 #define pr_fmt (fmt) KBUILD_MODNAME ": " fmt +#include <linux/kstrtox.h> #include <linux/module.h> +#include <linux/string.h> + +#include "kstackwatch.h" + +static struct ksw_config *ksw_config; + +struct param_map { +const char *name;/* long name */ +const char *short_name;/* short name (2 letters) */ +size_t offset;/* offsetof(struct ksw_config, field) */ +bool is_string;/* true for string */ +}; + +/* macro generates both long and short name automatically */ +#define PMAP (field, short, is_str) \ + { #field, #short, offsetof(struct ksw_config, field), is_str } + +static const struct param_map ksw_params[] = { +PMAP (func_name, fn, true), +PMAP (func_offset, fo, false), +PMAP (depth, dp, false), +PMAP (max_watch, mw, false), +PMAP (sp_offset, so, false), +PMAP (watch_len, wl, false), +}; + +static int ksw_parse_param (struct ksw_config *config,const char *key, +const char *val) +{ +const struct param_map *pm =NULL ; +int ret; + +for (int i =0 ; i <ARRAY_SIZE (ksw_params); i++) { +if (strcmp (key, ksw_params[i].name) ==0 || +strcmp (key, ksw_params[i].short_name) ==0 ) { + pm = &ksw_params[i]; +break ; + } + } + +if (!pm) +return -EINVAL ; + +if (pm->is_string) { +char **dst = (char **)((char *)config + pm->offset); + *dst =kstrdup (val,GFP_KERNEL ); +if (!*dst) +return -ENOMEM ; + }else { + ret =kstrtou16 (val,0 , (u16 *)((char *)config + pm->offset)); +if (ret) +return ret; + } + +return 0 ; +} + +/* +* Configuration string format: +* param_name=<value> [param_name=<value> ...] +* +* Required parameters: +* - func_name |fn (str) : target function name +* - func_offset|fo (u16) : instruction pointer offset +* +* Optional parameters: +* - depth |dp (u16) : recursion depth +* - max_watch |mw (u16) : maximum number of watchpoints +* - sp_offset |so (u16) : offset from stack pointer at func_offset +* - watch_len |wl (u16) : watch length (1,2,4,8) +*/ +static int __maybe_unused ksw_parse_config (char *buf,struct ksw_config *config) +{ +char *part, *key, *val; +int ret; + +kfree (config->func_name); +kfree (config->user_input); +memset (ksw_config,0 ,sizeof (*ksw_config)); + + buf =strim (buf); + config->user_input =kstrdup (buf,GFP_KERNEL ); +if (!config->user_input) +return -ENOMEM ; + +while ((part =strsep (&buf," \t\n" )) !=NULL ) { +if (*part =='\0' ) +continue ; + + key =strsep (&part,"=" ); + val = part; +if (!key || !val) +continue ; + ret =ksw_parse_param (config, key, val); +if (ret) +pr_warn ("unsupported param %s=%s" , key, val); + } + +if (!config->func_name || !config->func_offset) { +pr_err ("Missing required parameters: function or func_offset\n" ); +return -EINVAL ; + } + +return 0 ; +}static int __init kstackwatch_init (void ) { + ksw_config =kzalloc (sizeof (*ksw_config),GFP_KERNEL ); +if (!ksw_config) +return -ENOMEM ; +pr_info ("module loaded\n" );return 0 ; } static void __exit kstackwatch_exit(void) { +kfree (ksw_config); +pr_info ("module unloaded\n" ); }
mm/kstackwatch/kstackwatch.h +27 -0
@@ -2,4 +2,31 @@#ifndef _KSTACKWATCH_H#define _KSTACKWATCH_H +#include <linux/types.h> + +#define MAX_CONFIG_STR_LEN 128 + +struct ksw_config { +char *func_name; +u16 depth; + +/* +* watched variable info: +* - func_offset : instruction offset in the function, typically the +* assignment of the watched variable, where ksw +* registers a kprobe post-handler. +* - sp_offset : offset from stack pointer at func_offset. Usually 0. +* - watch_len : size of the watched variable (1, 2, 4, or 8 bytes). +*/ +u16 func_offset; +u16 sp_offset; +u16 watch_len; + +/* max number of hwbps that can be used */ +u16 max_watch; + +/* save to show */ +char *user_input; +}; +#endif /* _KSTACKWATCH_H */
Signature · 1 line
2.43.0
PATCH v5 6/23 mm/ksw: add singleton /proc/kstackwatch interface
In reply to Jinchao WangProvide the /proc/kstackwatch file to read or update the configuration. Only a single process can open this file at a time, enforced using atomic config_file_busy, to prevent concurrent access.
ksw_get_config() exposes the configuration pointer as const.
--- mm/kstackwatch/kernel.c | 77 +++++++++++++++++++++++++++++++++++- mm/kstackwatch/kstackwatch.h | 3 ++ 2 files changed, 79 insertions(+), 1 deletion(-)
mm/kstackwatch/kernel.c +76 -1
@@ -3,11 +3,15 @@#include <linux/kstrtox.h> #include <linux/module.h> +#include <linux/proc_fs.h> +#include <linux/seq_file.h> #include <linux/string.h> +#include <linux/uaccess.h> #include "kstackwatch.h" static struct ksw_config *ksw_config; +static atomic_t config_file_busy =ATOMIC_INIT (0 );struct param_map {const char *name;/* long name */
@@ -74,7 +78,7 @@ static int ksw_parse_param(struct ksw_config *config, const char *key,* - sp_offset |so (u16) : offset from stack pointer at func_offset * - watch_len |wl (u16) : watch length (1,2,4,8) */ -static int __maybe_unused ksw_parse_config (char *buf,struct ksw_config *config) +static int ksw_parse_config (char *buf,struct ksw_config *config) {char *part, *key, *val;int ret;
@@ -109,18 +113,89 @@ static int __maybe_unused ksw_parse_config(char *buf, struct ksw_config *config)return 0 ; } +static ssize_t kstackwatch_proc_write (struct file *file, +const char __user *buffer,size_t count, +loff_t *pos) +{ +char input[MAX_CONFIG_STR_LEN ]; +int ret; + +if (count ==0 || count >=sizeof (input)) +return -EINVAL ; + +if (copy_from_user (input, buffer, count)) +return -EFAULT ; + + input[count] ='\0' ; +strim (input); + +if (!strlen (input)) { +pr_info ("config cleared\n" ); +return count; + } + + ret =ksw_parse_config (input, ksw_config); +if (ret) { +pr_err ("Failed to parse config %d\n" , ret); +return ret; + } + +return count; +} + +static int kstackwatch_proc_show (struct seq_file *m,void *v) +{ +seq_printf (m,"%s\n" , ksw_config->user_input); +return 0 ; +} + +static int kstackwatch_proc_open (struct inode *inode,struct file *file) +{ +if (atomic_cmpxchg (&config_file_busy,0 ,1 )) +return -EBUSY ; + +return single_open (file, kstackwatch_proc_show,NULL ); +} + +static int kstackwatch_proc_release (struct inode *inode,struct file *file) +{ +atomic_set (&config_file_busy,0 ); +return single_release (inode, file); +} + +static const struct proc_ops kstackwatch_proc_ops = { + .proc_open = kstackwatch_proc_open, + .proc_read = seq_read, + .proc_write = kstackwatch_proc_write, + .proc_lseek = seq_lseek, + .proc_release = kstackwatch_proc_release, +}; + +const struct ksw_config *ksw_get_config (void ) +{ +return ksw_config; +}static int __init kstackwatch_init (void ) { ksw_config =kzalloc (sizeof (*ksw_config),GFP_KERNEL );if (!ksw_config)return -ENOMEM ; +if (!proc_create ("kstackwatch" ,0600 ,NULL , &kstackwatch_proc_ops)) { +pr_err ("create proc kstackwatch fail" ); +kfree (ksw_config); +return -ENOMEM ; + } +pr_info ("module loaded\n" );return 0 ; } static void __exit kstackwatch_exit(void) { +remove_proc_entry ("kstackwatch" ,NULL ); +kfree (ksw_config->func_name); +kfree (ksw_config->user_input);kfree (ksw_config);pr_info ("module unloaded\n" );
mm/kstackwatch/kstackwatch.h +3 -0
@@ -29,4 +29,7 @@ struct ksw_config { char *user_input; }; +// singleton, only modified in kernel.c +const struct ksw_config *ksw_get_config (void ); +#endif /* _KSTACKWATCH_H */
Signature · 1 line
2.43.0
Re: [PATCH v5 06/23] mm/ksw: add singleton /proc/kstackwatch interface
Quoted 4 lines · Jinchao Wang
Provide the
/proc/kstackwatchfile to read or update the configuration. Only a single process can open this file at a time, enforced using atomicconfig_file_busy, to prevent concurrent access.
Why is this in /proc and not debugfs?
Quoted 146 lines
ksw_get_config()exposes the configuration pointer as const.Signed-off-by Jinchao Wang <[email protected]>--- mm/kstackwatch/kernel.c | 77 +++++++++++++++++++++++++++++++++++- mm/kstackwatch/kstackwatch.h | 3 ++ 2 files changed, 79 insertions(+), 1 deletion(-)mm/kstackwatch/kernel.c +76
-1@@ -3,11 +3,15 @@#include <linux/kstrtox.h> #include <linux/module.h> +#include <linux/proc_fs.h> +#include <linux/seq_file.h> #include <linux/string.h> +#include <linux/uaccess.h> #include "kstackwatch.h" static struct ksw_config *ksw_config; +static atomic_t config_file_busy =ATOMIC_INIT (0 );struct param_map {const char *name;/* long name */ @@ -74,7 +78,7 @@ static int ksw_parse_param(struct ksw_config *config, const char *key,* - sp_offset |so (u16) : offset from stack pointer at func_offset * - watch_len |wl (u16) : watch length (1,2,4,8) */ -static int __maybe_unused ksw_parse_config (char *buf,struct ksw_config *config) +static int ksw_parse_config (char *buf,struct ksw_config *config) {char *part, *key, *val;int ret;@@ -109,18 +113,89 @@ static int __maybe_unused ksw_parse_config(char *buf, struct ksw_config *config)return 0 ; } +static ssize_t kstackwatch_proc_write (struct file *file, +const char __user *buffer,size_t count, +loff_t *pos) +{ +char input[MAX_CONFIG_STR_LEN ]; +int ret; + +if (count ==0 || count >=sizeof (input)) +return -EINVAL ; + +if (copy_from_user (input, buffer, count)) +return -EFAULT ; + + input[count] ='\0' ; +strim (input); + +if (!strlen (input)) { +pr_info ("config cleared\n" ); +return count; + } + + ret =ksw_parse_config (input, ksw_config); +if (ret) { +pr_err ("Failed to parse config %d\n" , ret); +return ret; + } + +return count; +} + +static int kstackwatch_proc_show (struct seq_file *m,void *v) +{ +seq_printf (m,"%s\n" , ksw_config->user_input); +return 0 ; +} + +static int kstackwatch_proc_open (struct inode *inode,struct file *file) +{ +if (atomic_cmpxchg (&config_file_busy,0 ,1 )) +return -EBUSY ; + +return single_open (file, kstackwatch_proc_show,NULL ); +} + +static int kstackwatch_proc_release (struct inode *inode,struct file *file) +{ +atomic_set (&config_file_busy,0 ); +return single_release (inode, file); +} + +static const struct proc_ops kstackwatch_proc_ops = { + .proc_open = kstackwatch_proc_open, + .proc_read = seq_read, + .proc_write = kstackwatch_proc_write, + .proc_lseek = seq_lseek, + .proc_release = kstackwatch_proc_release, +}; + +const struct ksw_config *ksw_get_config (void ) +{ +return ksw_config; +}static int __init kstackwatch_init (void ) { ksw_config =kzalloc (sizeof (*ksw_config),GFP_KERNEL );if (!ksw_config)return -ENOMEM ; +if (!proc_create ("kstackwatch" ,0600 ,NULL , &kstackwatch_proc_ops)) { +pr_err ("create proc kstackwatch fail" ); +kfree (ksw_config); +return -ENOMEM ; + } +pr_info ("module loaded\n" );return 0 ; } static void __exit kstackwatch_exit(void) { +remove_proc_entry ("kstackwatch" ,NULL ); +kfree (ksw_config->func_name); +kfree (ksw_config->user_input);kfree (ksw_config);pr_info ("module unloaded\n" );mm/kstackwatch/kstackwatch.h +3
-1@@ -29,4 +29,7 @@ struct ksw_config { char *user_input; }; +// singleton, only modified in kernel.c +const struct ksw_config *ksw_get_config (void ); +#endif /* _KSTACKWATCH_H */ --2.43.0
--
You received this message because you are subscribed to the Google Groups "kasan-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion visit https://groups.google.com/d/msgid/kasan-dev/20250924115124.194940-7-wangjinchao600%40gmail.com.
Re: [PATCH v5 06/23] mm/ksw: add singleton /proc/kstackwatch interface
Quoted 7 lines · Marco Elver
Quoted 4 lines · Jinchao Wang
Provide the
/proc/kstackwatchfile to read or update the configuration. Only a single process can open this file at a time, enforced using atomicconfig_file_busy, to prevent concurrent access.Why is this in /proc and not debugfs?
Thanks, will fix in next version.
Quoted 147 lines
Quoted 147 lines
ksw_get_config()exposes the configuration pointer as const.Signed-off-by Jinchao Wang <[email protected]>--- mm/kstackwatch/kernel.c | 77 +++++++++++++++++++++++++++++++++++- mm/kstackwatch/kstackwatch.h | 3 ++ 2 files changed, 79 insertions(+), 1 deletion(-)mm/kstackwatch/kernel.c +76
-1@@ -3,11 +3,15 @@#include <linux/kstrtox.h> #include <linux/module.h> +#include <linux/proc_fs.h> +#include <linux/seq_file.h> #include <linux/string.h> +#include <linux/uaccess.h> #include "kstackwatch.h" static struct ksw_config *ksw_config; +static atomic_t config_file_busy =ATOMIC_INIT (0 );struct param_map {const char *name;/* long name */ @@ -74,7 +78,7 @@ static int ksw_parse_param(struct ksw_config *config, const char *key,* - sp_offset |so (u16) : offset from stack pointer at func_offset * - watch_len |wl (u16) : watch length (1,2,4,8) */ -static int __maybe_unused ksw_parse_config (char *buf,struct ksw_config *config) +static int ksw_parse_config (char *buf,struct ksw_config *config) {char *part, *key, *val;int ret;@@ -109,18 +113,89 @@ static int __maybe_unused ksw_parse_config(char *buf, struct ksw_config *config)return 0 ; } +static ssize_t kstackwatch_proc_write (struct file *file, +const char __user *buffer,size_t count, +loff_t *pos) +{ +char input[MAX_CONFIG_STR_LEN ]; +int ret; + +if (count ==0 || count >=sizeof (input)) +return -EINVAL ; + +if (copy_from_user (input, buffer, count)) +return -EFAULT ; + + input[count] ='\0' ; +strim (input); + +if (!strlen (input)) { +pr_info ("config cleared\n" ); +return count; + } + + ret =ksw_parse_config (input, ksw_config); +if (ret) { +pr_err ("Failed to parse config %d\n" , ret); +return ret; + } + +return count; +} + +static int kstackwatch_proc_show (struct seq_file *m,void *v) +{ +seq_printf (m,"%s\n" , ksw_config->user_input); +return 0 ; +} + +static int kstackwatch_proc_open (struct inode *inode,struct file *file) +{ +if (atomic_cmpxchg (&config_file_busy,0 ,1 )) +return -EBUSY ; + +return single_open (file, kstackwatch_proc_show,NULL ); +} + +static int kstackwatch_proc_release (struct inode *inode,struct file *file) +{ +atomic_set (&config_file_busy,0 ); +return single_release (inode, file); +} + +static const struct proc_ops kstackwatch_proc_ops = { + .proc_open = kstackwatch_proc_open, + .proc_read = seq_read, + .proc_write = kstackwatch_proc_write, + .proc_lseek = seq_lseek, + .proc_release = kstackwatch_proc_release, +}; + +const struct ksw_config *ksw_get_config (void ) +{ +return ksw_config; +}static int __init kstackwatch_init (void ) { ksw_config =kzalloc (sizeof (*ksw_config),GFP_KERNEL );if (!ksw_config)return -ENOMEM ; +if (!proc_create ("kstackwatch" ,0600 ,NULL , &kstackwatch_proc_ops)) { +pr_err ("create proc kstackwatch fail" ); +kfree (ksw_config); +return -ENOMEM ; + } +pr_info ("module loaded\n" );return 0 ; } static void __exit kstackwatch_exit(void) { +remove_proc_entry ("kstackwatch" ,NULL ); +kfree (ksw_config->func_name); +kfree (ksw_config->user_input);kfree (ksw_config);pr_info ("module unloaded\n" );mm/kstackwatch/kstackwatch.h +3
-1@@ -29,4 +29,7 @@ struct ksw_config { char *user_input; }; +// singleton, only modified in kernel.c +const struct ksw_config *ksw_get_config (void ); +#endif /* _KSTACKWATCH_H */ --2.43.0
--
You received this message because you are subscribed to the Google Groups "kasan-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion visit https://groups.google.com/d/msgid/kasan-dev/20250924115124.194940-7-wangjinchao600%40gmail.com.
Signature · 1 line
Jinchao
PATCH v5 7/23 mm/ksw: add HWBP pre-allocation
In reply to Jinchao WangPre-allocate per-CPU hardware breakpoints at init with a place holder address, which will be retargeted dynamically in kprobe handler. This avoids allocation in atomic context.
At most max_watch breakpoints are allocated (0 means no limit).
--- mm/kstackwatch/kstackwatch.h | 13 +++++ mm/kstackwatch/watch.c | 97 ++++++++++++++++++++++++++++++++++++ 2 files changed, 110 insertions(+)
mm/kstackwatch/kstackwatch.h +13 -0
@@ -2,6 +2,9 @@#ifndef _KSTACKWATCH_H#define _KSTACKWATCH_H +#include <linux/llist.h> +#include <linux/percpu.h> +#include <linux/perf_event.h> #include <linux/types.h> #define MAX_CONFIG_STR_LEN 128
@@ -32,4 +35,14 @@ struct ksw_config {// singleton, only modified in kernel.c const struct ksw_config *ksw_get_config (void ); +/* watch management */ +struct ksw_watchpoint { +struct perf_event *__percpu *event; +struct perf_event_attr attr; +struct llist_node node;// for atomic watch_on and off +struct list_head list;// for cpu online and offline +}; +int ksw_watch_init (void ); +void ksw_watch_exit (void ); +#endif /* _KSTACKWATCH_H */
mm/kstackwatch/watch.c +97 -0
98 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH v5 8/23 mm/ksw: Add atomic watchpoint management api
In reply to Jinchao WangAdd three functions for atomic lifecycle management of watchpoints:
- ksw_watch_get(): Acquires a watchpoint from a llist.
- ksw_watch_on(): Enables the watchpoint on all online CPUs.
- ksw_watch_off(): Disables the watchpoint and returns it to the llist.
For cross-CPU synchronization, updates are propagated using direct modification on the local CPU and asynchronous IPIs for remote CPUs.
--- mm/kstackwatch/kstackwatch.h | 4 ++ mm/kstackwatch/watch.c | 85 +++++++++++++++++++++++++++++++++++- 2 files changed, 88 insertions(+), 1 deletion(-)
mm/kstackwatch/kstackwatch.h +4 -0
@@ -38,11 +38,15 @@ const struct ksw_config *ksw_get_config(void);/* watch management */ struct ksw_watchpoint {struct perf_event *__percpu *event; +call_single_data_t __percpu *csd;struct perf_event_attr attr;struct llist_node node;// for atomic watch_on and off struct list_head list;// for cpu online and offline };int ksw_watch_init (void );void ksw_watch_exit (void ); +int ksw_watch_get (struct ksw_watchpoint **out_wp); +int ksw_watch_on (struct ksw_watchpoint *wp,ulong watch_addr,u16 watch_len); +int ksw_watch_off (struct ksw_watchpoint *wp);#endif /* _KSTACKWATCH_H */
mm/kstackwatch/watch.c +84 -1
120 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH v5 9/23 mm/ksw: ignore false positives from exit trampolines
In reply to Jinchao WangBecause trampolines run after the watched function returns but before the exit_handler is called, and in the original stack frame, so the trampoline code may overwrite the watched stack address.
These false positives should be ignored. is_ftrace_trampoline() does not cover all trampolines, so add a local check to handle the remaining cases.
--- mm/kstackwatch/watch.c | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+)
mm/kstackwatch/watch.c +38 -0
@@ -2,6 +2,7 @@#define pr_fmt (fmt) KBUILD_MODNAME ": " fmt#include <linux/cpuhotplug.h> +#include <linux/ftrace.h> #include <linux/hw_breakpoint.h> #include <linux/irqflags.h> #include <linux/mutex.h>
@@ -18,10 +19,46 @@ bool panic_on_catch;module_param (panic_on_catch, bool,0644 );MODULE_PARM_DESC (panic_on_catch,"panic immediately on corruption catch" ); +#define TRAMPOLINE_NAME "return_to_handler" +#define TRAMPOLINE_DEPTH 16 + +/* Resolved once, then reused */ +static unsigned long tramp_start, tramp_end; + +static void ksw_watch_resolve_trampoline (void ) +{ +unsigned long sz, off; + +if (likely (tramp_start && tramp_end)) +return ; + + tramp_start =kallsyms_lookup_name (TRAMPOLINE_NAME ); +if (tramp_start &&kallsyms_lookup_size_offset (tramp_start, &sz, &off)) + tramp_end = tramp_start + sz; +} + +static bool ksw_watch_in_trampoline (unsigned long ip) +{ +if (tramp_start && tramp_end && ip >= tramp_start && ip < tramp_end) +return true; +return false; +}static void ksw_watch_handler (struct perf_event *bp,struct perf_sample_data *data,struct pt_regs *regs) { +unsigned long entries[TRAMPOLINE_DEPTH ]; +int i, nr =0 ; + + nr =stack_trace_save_regs (regs, entries,TRAMPOLINE_DEPTH ,0 ); +for (i =0 ; i < nr; i++) { +//ignore trampoline +if (is_ftrace_trampoline (entries[i])) +return ; +if (ksw_watch_in_trampoline (entries[i])) +return ; + } +pr_err ("========== KStackWatch: Caught stack corruption =======\n" );pr_err ("config %s\n" ,ksw_get_config ()->user_input);dump_stack ();
@@ -168,6 +205,7 @@ int ksw_watch_init(void) {int ret; +ksw_watch_resolve_trampoline (); ret =ksw_watch_alloc ();if (ret <=0 )return -EBUSY ;
Signature · 1 line
2.43.0
PATCH v5 10/23 mm/ksw: support CPU hotplug
In reply to Jinchao WangRegister CPU online/offline callbacks via cpuhp_setup_state_nocalls() so stack watches are installed/removed dynamically as CPUs come online or go offline.
When a new CPU comes online, register a hardware breakpoint for the holder, avoiding races with watch_on()/watch_off() that may run on another CPU. The watch address will be updated the next time watch_on() is called.
--- mm/kstackwatch/watch.c | 52 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+)
mm/kstackwatch/watch.c +52 -0
@@ -89,6 +89,48 @@ static void ksw_watch_on_local_cpu(void *info)WARN (ret,"fail to reinstall HWBP on CPU%d ret %d" , cpu, ret); } +static int ksw_watch_cpu_online (unsigned int cpu) +{ +struct perf_event_attr attr; +struct ksw_watchpoint *wp; +call_single_data_t *csd; +struct perf_event *bp; + +mutex_lock (&all_wp_mutex); +list_for_each_entry (wp, &all_wp_list, list) { + attr = wp->attr; + attr.bp_addr = (u64)&holder; + bp =perf_event_create_kernel_counter (&attr, cpu,NULL , + ksw_watch_handler, wp); +if (IS_ERR (bp)) { +pr_warn ("%s failed to create watch on CPU %d: %ld\n" , + __func__, cpu,PTR_ERR (bp)); +continue ; + } + +per_cpu (*wp->event, cpu) = bp; + csd =per_cpu_ptr (wp->csd, cpu); +INIT_CSD (csd, ksw_watch_on_local_cpu, wp); + } +mutex_unlock (&all_wp_mutex); +return 0 ; +} + +static int ksw_watch_cpu_offline (unsigned int cpu) +{ +struct ksw_watchpoint *wp; +struct perf_event *bp; + +mutex_lock (&all_wp_mutex); +list_for_each_entry (wp, &all_wp_list, list) { + bp =per_cpu (*wp->event, cpu); +if (bp) +unregister_hw_breakpoint (bp); + } +mutex_unlock (&all_wp_mutex); +return 0 ; +} +static void ksw_watch_update (struct ksw_watchpoint *wp,ulong addr,u16 len) {call_single_data_t *csd;
@@ -210,6 +252,16 @@ int ksw_watch_init(void)if (ret <=0 )return -EBUSY ; + ret =cpuhp_setup_state_nocalls (CPUHP_AP_ONLINE_DYN , +"kstackwatch:online" , + ksw_watch_cpu_online, + ksw_watch_cpu_offline); +if (ret <0 ) { +ksw_watch_free (); +pr_err ("Failed to register CPU hotplug notifier\n" ); +return ret; + } +return 0 ; }
Signature · 1 line
2.43.0
PATCH v5 11/23 sched: add per-task context
In reply to Jinchao WangIntroduce struct ksw_ctx to enable lockless per-task state tracking. This is required because KStackWatch operates in NMI context (via kprobe handler) where traditional locking is unsafe.
--- include/linux/kstackwatch_types.h | 14 ++++++++++++++ include/linux/sched.h | 5 +++++ 2 files changed, 19 insertions(+) create mode 100644 include/linux/kstackwatch_types.h
include/linux/kstackwatch_types.h new file +14 -0
@@ -0,0 +1,14 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _LINUX_KSTACK_WATCH_TYPES_H +#define _LINUX_KSTACK_WATCH_TYPES_H +#include <linux/types.h> + +struct ksw_watchpoint ; +struct ksw_ctx { +struct ksw_watchpoint *wp; +ulong sp; +u16 depth; +u16 generation; +}; + +#endif /* _LINUX_KSTACK_WATCH_TYPES_H */
include/linux/sched.h +5 -0
@@ -22,6 +22,7 @@#include <linux/sem_types.h> #include <linux/shm.h> #include <linux/kmsan_types.h> +#include <linux/kstackwatch_types.h> #include <linux/mutex_types.h> #include <linux/plist_types.h> #include <linux/hrtimer_types.h>
@@ -1481,6 +1482,10 @@ struct task_struct {struct kmsan_ctx kmsan_ctx;#endif +#if IS_ENABLED (CONFIG_KSTACK_WATCH ) +struct ksw_ctx ksw_ctx; +#endif +#if IS_ENABLED (CONFIG_KUNIT )struct kunit *kunit_test;#endif
Signature · 1 line
2.43.0
PATCH v5 12/23 mm/ksw: add entry kprobe and exit fprobe management
In reply to Jinchao WangProvide ksw_stack_init() and ksw_stack_exit() to manage entry and exit probes for the target function from ksw_get_config().
--- mm/kstackwatch/kstackwatch.h | 4 ++ mm/kstackwatch/stack.c | 101 +++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+)
mm/kstackwatch/kstackwatch.h +4 -0
@@ -35,6 +35,10 @@ struct ksw_config {// singleton, only modified in kernel.c const struct ksw_config *ksw_get_config (void ); +/* stack management */ +int ksw_stack_init (void ); +void ksw_stack_exit (void ); +/* watch management */ struct ksw_watchpoint {struct perf_event *__percpu *event;
mm/kstackwatch/stack.c +101 -0
102 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH v5 13/23 mm/ksw: add per-task ctx tracking
In reply to Jinchao WangEach task tracks its depth, stack pointer, and generation. A watchpoint is enabled only when the configured depth is reached, and disabled on function exit.
The context is reset when probes are disabled, generation changes, or exit depth becomes inconsistent.
Duplicate arming on the same frame is skipped.
--- mm/kstackwatch/stack.c | 67 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+)
mm/kstackwatch/stack.c +67 -0
@@ -12,6 +12,53 @@static struct kprobe entry_probe;static struct fprobe exit_probe; +static bool probe_enable; +static u16 probe_generation; + +static void ksw_reset_ctx (void ) +{ +struct ksw_ctx *ctx = ¤t->ksw_ctx; + +if (ctx->wp) +ksw_watch_off (ctx->wp); + + ctx->wp =NULL ; + ctx->sp =0 ; + ctx->depth =0 ; + ctx->generation =READ_ONCE (probe_generation); +} + +static bool ksw_stack_check_ctx (bool entry) +{ +struct ksw_ctx *ctx = ¤t->ksw_ctx; +u16 cur_enable =READ_ONCE (probe_enable); +u16 cur_generation =READ_ONCE (probe_generation); +u16 cur_depth, target_depth =ksw_get_config ()->depth; + +if (!cur_enable) { +ksw_reset_ctx (); +return false; + } + +if (ctx->generation != cur_generation) +ksw_reset_ctx (); + +if (!entry && !ctx->depth) { +ksw_reset_ctx (); +return false; + } + +if (entry) + cur_depth = ctx->depth++; +else + cur_depth = --ctx->depth; + +if (cur_depth == target_depth) +return true; +else +return false; +} +static int ksw_stack_prepare_watch (struct pt_regs *regs,const struct ksw_config *config,ulong *watch_addr,u16 *watch_len)
@@ -26,10 +73,22 @@ static void ksw_stack_entry_handler(struct kprobe *p, struct pt_regs *regs, unsigned long flags) {struct ksw_ctx *ctx = ¤t->ksw_ctx; +ulong stack_pointer;ulong watch_addr;u16 watch_len;int ret; + stack_pointer =kernel_stack_pointer (regs); + +/* +* triggered more than once, may be in a loop +*/ +if (ctx->wp && ctx->sp == stack_pointer) +return ; + +if (!ksw_stack_check_ctx (true)) +return ; + ret =ksw_watch_get (&ctx->wp);if (ret)return ;
@@ -50,6 +109,7 @@ static void ksw_stack_entry_handler(struct kprobe *p, struct pt_regs *regs,return ; } + ctx->sp = stack_pointer; } static void ksw_stack_exit_handler(struct fprobe *fp, unsigned long ip,
@@ -58,6 +118,8 @@ static void ksw_stack_exit_handler(struct fprobe *fp, unsigned long ip, {struct ksw_ctx *ctx = ¤t->ksw_ctx; +if (!ksw_stack_check_ctx (false)) +return ;if (ctx->wp) {ksw_watch_off (ctx->wp);
@@ -92,11 +154,16 @@ int ksw_stack_init(void)return ret; } +WRITE_ONCE (probe_generation,READ_ONCE (probe_generation) +1 ); +WRITE_ONCE (probe_enable, true); +return 0 ; }void ksw_stack_exit (void ) { +WRITE_ONCE (probe_enable, false); +WRITE_ONCE (probe_generation,READ_ONCE (probe_generation) +1 );unregister_fprobe (&exit_probe);unregister_kprobe (&entry_probe); }
Signature · 1 line
2.43.0
PATCH v5 14/23 mm/ksw: resolve stack watch addr and len
In reply to Jinchao WangAdd helpers to find the stack canary or a local variable addr and len for the probed function based on ksw_get_config(). For canary search, limits search to a fixed number of steps to avoid scanning the entire stack. Validates that the computed address and length are within the kernel stack.
--- mm/kstackwatch/stack.c | 77 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 74 insertions(+), 3 deletions(-)
mm/kstackwatch/stack.c +74 -3
@@ -9,6 +9,7 @@#include "kstackwatch.h" +#define MAX_CANARY_SEARCH_STEPS 128static struct kprobe entry_probe;static struct fprobe exit_probe;
@@ -59,13 +60,83 @@ static bool ksw_stack_check_ctx(bool entry)return false; } +static unsigned long ksw_find_stack_canary_addr (struct pt_regs *regs) +{ +unsigned long *stack_ptr, *stack_end, *stack_base; +unsigned long expected_canary; +unsigned int i; + + stack_ptr = (unsigned long *)kernel_stack_pointer (regs); + + stack_base = (unsigned long *)(current->stack); + +// TODO: limit it to the current frame + stack_end = (unsigned long *)((char *)current->stack +THREAD_SIZE ); + + expected_canary = current->stack_canary; + +if (stack_ptr < stack_base || stack_ptr >= stack_end) { +pr_err ("Stack pointer 0x%lx out of bounds [0x%lx, 0x%lx)\n" , + (unsigned long )stack_ptr, (unsigned long )stack_base, + (unsigned long )stack_end); +return 0 ; + } + +for (i =0 ; i <MAX_CANARY_SEARCH_STEPS ; i++) { +if (&stack_ptr[i] >= stack_end) +break ; + +if (stack_ptr[i] == expected_canary) { +pr_debug ("canary found i:%d 0x%lx\n" , i, + (unsigned long )&stack_ptr[i]); +return (unsigned long )&stack_ptr[i]; + } + } + +pr_debug ("canary not found in first %d steps\n" , +MAX_CANARY_SEARCH_STEPS ); +return 0 ; +} + +static int ksw_stack_validate_addr (unsigned long addr,size_t size) +{ +unsigned long stack_start, stack_end; + +if (!addr || !size) +return -EINVAL ; + + stack_start = (unsigned long )current->stack; + stack_end = stack_start +THREAD_SIZE ; + +if (addr < stack_start || (addr + size) > stack_end) +return -ERANGE ; + +return 0 ; +} +static int ksw_stack_prepare_watch (struct pt_regs *regs,const struct ksw_config *config,ulong *watch_addr,u16 *watch_len) { -/* implement logic will be added in following patches */ - *watch_addr =0 ; - *watch_len =0 ; +ulong addr; +u16 len; + +// default is to watch the canary +if (!ksw_get_config ()->watch_len) { + addr =ksw_find_stack_canary_addr (regs); + len =sizeof (ulong); + }else { + addr =kernel_stack_pointer (regs) +ksw_get_config ()->sp_offset; + len =ksw_get_config ()->watch_len; + } + +if (ksw_stack_validate_addr (addr, len)) { +pr_err ("invalid stack addr:0x%lx len :%u\n" , addr, len); +return -EINVAL ; + } + + *watch_addr = addr; + *watch_len = len;return 0 ; }
Signature · 1 line
2.43.0
PATCH v5 15/23 mm/ksw: manage probe and HWBP lifecycle via procfs
In reply to Jinchao WangAllow dynamic enabling/disabling of KStackWatch through user input of proc. With this patch, the entire system becomes functional.
--- mm/kstackwatch/kernel.c | 55 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-)
mm/kstackwatch/kernel.c +54 -1
@@ -13,6 +13,43 @@static struct ksw_config *ksw_config;static atomic_t config_file_busy =ATOMIC_INIT (0 ); +static bool watching_active; + +static int ksw_start_watching (void ) +{ +int ret; + +/* +* Watch init will preallocate the HWBP, +* so it must happen before stack init +*/ + ret =ksw_watch_init (); +if (ret) { +pr_err ("ksw_watch_init ret: %d\n" , ret); +return ret; + } + + ret =ksw_stack_init (); +if (ret) { +pr_err ("ksw_stack_init ret: %d\n" , ret); +ksw_watch_exit (); +return ret; + } + watching_active = true; + +pr_info ("start watching: %s\n" , ksw_config->user_input); +return 0 ; +} + +static void ksw_stop_watching (void ) +{ +ksw_stack_exit (); +ksw_watch_exit (); + watching_active = false; + +pr_info ("stop watching: %s\n" , ksw_config->user_input); +} +struct param_map {const char *name;/* long name */ const char *short_name;/* short name (2 letters) */
@@ -126,6 +163,9 @@ static ssize_t kstackwatch_proc_write(struct file *file,if (copy_from_user (input, buffer, count))return -EFAULT ; +if (watching_active) +ksw_stop_watching (); + input[count] ='\0' ;strim (input);
@@ -140,12 +180,22 @@ static ssize_t kstackwatch_proc_write(struct file *file,return ret; } + ret =ksw_start_watching (); +if (ret) { +pr_err ("Failed to start watching with %d\n" , ret); +return ret; + } +return count; }static int kstackwatch_proc_show (struct seq_file *m,void *v) { -seq_printf (m,"%s\n" , ksw_config->user_input); +if (watching_active) +seq_printf (m,"%s\n" , ksw_config->user_input); +else +seq_puts (m,"not watching\n" ); +return 0 ; }
@@ -193,6 +243,9 @@ static int __init kstackwatch_init(void) static void __exit kstackwatch_exit(void) { +if (watching_active) +ksw_stop_watching (); +remove_proc_entry ("kstackwatch" ,NULL );kfree (ksw_config->func_name);kfree (ksw_config->user_input);
Signature · 1 line
2.43.0
PATCH v5 16/23 mm/ksw: add self-debug helpers
In reply to Jinchao WangProvide two debug helpers:
- ksw_watch_show(): print the current watch target address and length.
- ksw_watch_fire(): intentionally trigger the watchpoint immediately by writing to the watched address, useful for testing HWBP behavior.
--- mm/kstackwatch/kstackwatch.h | 2 ++ mm/kstackwatch/watch.c | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+)
mm/kstackwatch/kstackwatch.h +2 -0
@@ -52,5 +52,7 @@ void ksw_watch_exit(void);int ksw_watch_get (struct ksw_watchpoint **out_wp);int ksw_watch_on (struct ksw_watchpoint *wp,ulong watch_addr,u16 watch_len);int ksw_watch_off (struct ksw_watchpoint *wp); +void ksw_watch_show (void ); +void ksw_watch_fire (void );#endif /* _KSTACKWATCH_H */
mm/kstackwatch/watch.c +34 -0
@@ -269,3 +269,37 @@ void ksw_watch_exit(void) {ksw_watch_free (); } + +/* self debug function */ +void ksw_watch_show (void ) +{ +struct ksw_watchpoint *wp = current->ksw_ctx.wp; + +if (!wp) { +pr_info ("nothing to show\n" ); +return ; + } + +pr_info ("watch target bp_addr: 0x%llx len:%llu\n" , wp->attr.bp_addr, + wp->attr.bp_len); +} +EXPORT_SYMBOL_GPL (ksw_watch_show); + +/* self debug function */ +void ksw_watch_fire (void ) +{ +struct ksw_watchpoint *wp; +char *ptr; + + wp = current->ksw_ctx.wp; + +if (!wp) { +pr_info ("nothing to fire\n" ); +return ; + } + + ptr = (char *)wp->attr.bp_addr; +pr_warn ("watch triggered immediately\n" ); + *ptr =0x42 ;// This should trigger immediately for any bp_len +} +EXPORT_SYMBOL_GPL (ksw_watch_fire);
Signature · 1 line
2.43.0
PATCH v5 17/23 mm/ksw: add test module
Introduce a separate test module to validate functionality in controlled scenarios.
The module provides a proc interface (/proc/kstackwatch_test) that allows triggering specific test cases via simple commands:
echo test0 > /proc/kstackwatch_test
Test module is built with optimizations disabled to ensure predictable behavior.
--- mm/Kconfig.debug | 10 ++++ mm/kstackwatch/Makefile | 6 ++ mm/kstackwatch/test.c | 122 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 138 insertions(+) create mode 100644 mm/kstackwatch/test.c
mm/Kconfig.debug +10 -0
@@ -317,3 +317,13 @@ config KSTACK_WATCH A lightweight real-time debugging tool to detect stack corrupting. If unsure, say N. + +config KSTACK_WATCH_TEST + tristate "KStackWatch Test Module" + depends on KSTACK_WATCH + help + This module provides controlled stack corruption scenarios to verify + the functionality of KStackWatch. It is useful for development and + validation of KStackWatch mechanism. + + If unsure, say N.
mm/kstackwatch/Makefile +6 -0
@@ -1,2 +1,8 @@ obj-$(CONFIG_KSTACK_WATCH) += kstackwatch.o kstackwatch-y := kernel.o stack.o watch.o + +obj-$(CONFIG_KSTACK_WATCH_TEST) += kstackwatch_test.o +kstackwatch_test-y := test.o +CFLAGS_test.o := -fno-inline \ + -fno-optimize-sibling-calls \ + -fno-pic -fno-pie -O0 -Og
mm/kstackwatch/test.c new file +122 -0
122 lines not on this page · raw message
Signature · 1 line
2.43.0
Re: [PATCH v5 17/23] mm/ksw: add test module
Quoted 8 lines · Jinchao Wang
Introduce a separate test module to validate functionality in controlled scenarios.
The module provides a proc interface (
/proc/kstackwatch_test) that allows triggering specific test cases via simple commands:echo test0 >
/proc/kstackwatch_test
This should not be in /proc/ - if anything, it should go into debugfs.
Quoted 177 lines
Test module is built with optimizations disabled to ensure predictable behavior.
Signed-off-by Jinchao Wang <[email protected]>--- mm/Kconfig.debug | 10 ++++ mm/kstackwatch/Makefile | 6 ++ mm/kstackwatch/test.c | 122 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 138 insertions(+) create mode 100644 mm/kstackwatch/test.cmm/Kconfig.debug +10
-0@@ -317,3 +317,13 @@ config KSTACK_WATCH A lightweight real-time debugging tool to detect stack corrupting. If unsure, say N. + +config KSTACK_WATCH_TEST + tristate "KStackWatch Test Module" + depends on KSTACK_WATCH + help + This module provides controlled stack corruption scenarios to verify + the functionality of KStackWatch. It is useful for development and + validation of KStackWatch mechanism. + + If unsure, say N.mm/kstackwatch/Makefile +6
-0@@ -1,2 +1,8 @@ obj-$(CONFIG_KSTACK_WATCH) += kstackwatch.o kstackwatch-y := kernel.o stack.o watch.o + +obj-$(CONFIG_KSTACK_WATCH_TEST) += kstackwatch_test.o +kstackwatch_test-y := test.o +CFLAGS_test.o := -fno-inline \ + -fno-optimize-sibling-calls \ + -fno-pic -fno-pie -O0 -Ogmm/kstackwatch/test.c new file +122
-1@@ -0,0 +1,122 @@ +// SPDX-License-Identifier: GPL-2.0 +#define pr_fmt (fmt) KBUILD_MODNAME ": " fmt + +#include <linux/delay.h> +#include <linux/kthread.h> +#include <linux/list.h> +#include <linux/module.h> +#include <linux/prandom.h> +#include <linux/printk.h> +#include <linux/proc_fs.h> +#include <linux/random.h> +#include <linux/spinlock.h> +#include <linux/string.h> +#include <linux/uaccess.h> + +#include "kstackwatch.h" + +static struct proc_dir_entry *test_proc; + +#define BUFFER_SIZE 16 +#define MAX_DEPTH 6 + +struct work_node { +ulong *ptr; +struct completion done; +struct list_head list; +}; + +static DECLARE_COMPLETION (work_res); +static DEFINE_MUTEX (work_mutex); +static LIST_HEAD (work_list); + +static void test_watch_fire (void ) +{ +u64 buffer[BUFFER_SIZE ] = {0 }; + +pr_info ("entry of %s\n" , __func__); +ksw_watch_show (); +ksw_watch_fire (); +pr_info ("buf[0]:%lld\n" , buffer[0 ]); + +barrier_data (buffer); +pr_info ("exit of %s\n" , __func__); +} + + +static ssize_t test_proc_write (struct file *file,const char __user *buffer, +size_t count,loff_t *pos) +{ +char cmd[256 ]; +int test_num; + +if (count >=sizeof (cmd)) +return -EINVAL ; + +if (copy_from_user (cmd, buffer, count)) +return -EFAULT ; + + cmd[count] ='\0' ; +strim (cmd); + +pr_info ("received command: %s\n" , cmd); + +if (sscanf (cmd,"test%d" , &test_num) ==1 ) { +switch (test_num) { +case 0 : +test_watch_fire (); +break ; +default : +pr_err ("Unknown test number %d\n" , test_num); +return -EINVAL ; + } + }else { +pr_err ("invalid command format. Use 'testN'.\n" ); +return -EINVAL ; + } + +return count; +} + +static ssize_t test_proc_read (struct file *file,char __user *buffer, +size_t count,loff_t *pos) +{ +static const char usage[] ="KStackWatch Simplified Test Module\n" +"============ usage ==============\n" +"Usage:\n" +"echo test{i} > /proc/kstackwatch_test\n" +" test0 - test watch fire\n" ; + +return simple_read_from_buffer (buffer, count, pos, usage, +strlen (usage)); +} + +static const struct proc_ops test_proc_ops = { + .proc_read = test_proc_read, + .proc_write = test_proc_write, +}; + +static int __init kstackwatch_test_init (void ) +{ + test_proc =proc_create ("kstackwatch_test" ,0600 ,NULL , &test_proc_ops); +if (!test_proc) { +pr_err ("Failed to create proc entry\n" ); +return -ENOMEM ; + } +pr_info ("module loaded\n" ); +return 0 ; +} + +static void __exit kstackwatch_test_exit(void) +{ +if (test_proc) +remove_proc_entry ("kstackwatch_test" ,NULL ); +pr_info ("module unloaded\n" ); +} + +module_init (kstackwatch_test_init); +module_exit (kstackwatch_test_exit); + +MODULE_AUTHOR ("Jinchao Wang" ); +MODULE_DESCRIPTION ("Simple KStackWatch Test Module" ); +MODULE_LICENSE ("GPL" ); --2.43.0
--
You received this message because you are subscribed to the Google Groups "kasan-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion visit https://groups.google.com/d/msgid/kasan-dev/20250924115931.197077-2-wangjinchao600%40gmail.com.
Re: [PATCH v5 17/23] mm/ksw: add test module
Quoted 11 lines · Marco Elver
Quoted 8 lines · Jinchao Wang
Introduce a separate test module to validate functionality in controlled scenarios.
The module provides a proc interface (
/proc/kstackwatch_test) that allows triggering specific test cases via simple commands:echo test0 >
/proc/kstackwatch_testThis should not be in
/proc/- if anything, it should go into debugfs.
Thanks, will fix in next version.
Quoted 178 lines
Quoted 178 lines
Test module is built with optimizations disabled to ensure predictable behavior.
Signed-off-by Jinchao Wang <[email protected]>--- mm/Kconfig.debug | 10 ++++ mm/kstackwatch/Makefile | 6 ++ mm/kstackwatch/test.c | 122 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 138 insertions(+) create mode 100644 mm/kstackwatch/test.cmm/Kconfig.debug +10
-0@@ -317,3 +317,13 @@ config KSTACK_WATCH A lightweight real-time debugging tool to detect stack corrupting. If unsure, say N. + +config KSTACK_WATCH_TEST + tristate "KStackWatch Test Module" + depends on KSTACK_WATCH + help + This module provides controlled stack corruption scenarios to verify + the functionality of KStackWatch. It is useful for development and + validation of KStackWatch mechanism. + + If unsure, say N.mm/kstackwatch/Makefile +6
-0@@ -1,2 +1,8 @@ obj-$(CONFIG_KSTACK_WATCH) += kstackwatch.o kstackwatch-y := kernel.o stack.o watch.o + +obj-$(CONFIG_KSTACK_WATCH_TEST) += kstackwatch_test.o +kstackwatch_test-y := test.o +CFLAGS_test.o := -fno-inline \ + -fno-optimize-sibling-calls \ + -fno-pic -fno-pie -O0 -Ogmm/kstackwatch/test.c new file +122
-1@@ -0,0 +1,122 @@ +// SPDX-License-Identifier: GPL-2.0 +#define pr_fmt (fmt) KBUILD_MODNAME ": " fmt + +#include <linux/delay.h> +#include <linux/kthread.h> +#include <linux/list.h> +#include <linux/module.h> +#include <linux/prandom.h> +#include <linux/printk.h> +#include <linux/proc_fs.h> +#include <linux/random.h> +#include <linux/spinlock.h> +#include <linux/string.h> +#include <linux/uaccess.h> + +#include "kstackwatch.h" + +static struct proc_dir_entry *test_proc; + +#define BUFFER_SIZE 16 +#define MAX_DEPTH 6 + +struct work_node { +ulong *ptr; +struct completion done; +struct list_head list; +}; + +static DECLARE_COMPLETION (work_res); +static DEFINE_MUTEX (work_mutex); +static LIST_HEAD (work_list); + +static void test_watch_fire (void ) +{ +u64 buffer[BUFFER_SIZE ] = {0 }; + +pr_info ("entry of %s\n" , __func__); +ksw_watch_show (); +ksw_watch_fire (); +pr_info ("buf[0]:%lld\n" , buffer[0 ]); + +barrier_data (buffer); +pr_info ("exit of %s\n" , __func__); +} + + +static ssize_t test_proc_write (struct file *file,const char __user *buffer, +size_t count,loff_t *pos) +{ +char cmd[256 ]; +int test_num; + +if (count >=sizeof (cmd)) +return -EINVAL ; + +if (copy_from_user (cmd, buffer, count)) +return -EFAULT ; + + cmd[count] ='\0' ; +strim (cmd); + +pr_info ("received command: %s\n" , cmd); + +if (sscanf (cmd,"test%d" , &test_num) ==1 ) { +switch (test_num) { +case 0 : +test_watch_fire (); +break ; +default : +pr_err ("Unknown test number %d\n" , test_num); +return -EINVAL ; + } + }else { +pr_err ("invalid command format. Use 'testN'.\n" ); +return -EINVAL ; + } + +return count; +} + +static ssize_t test_proc_read (struct file *file,char __user *buffer, +size_t count,loff_t *pos) +{ +static const char usage[] ="KStackWatch Simplified Test Module\n" +"============ usage ==============\n" +"Usage:\n" +"echo test{i} > /proc/kstackwatch_test\n" +" test0 - test watch fire\n" ; + +return simple_read_from_buffer (buffer, count, pos, usage, +strlen (usage)); +} + +static const struct proc_ops test_proc_ops = { + .proc_read = test_proc_read, + .proc_write = test_proc_write, +}; + +static int __init kstackwatch_test_init (void ) +{ + test_proc =proc_create ("kstackwatch_test" ,0600 ,NULL , &test_proc_ops); +if (!test_proc) { +pr_err ("Failed to create proc entry\n" ); +return -ENOMEM ; + } +pr_info ("module loaded\n" ); +return 0 ; +} + +static void __exit kstackwatch_test_exit(void) +{ +if (test_proc) +remove_proc_entry ("kstackwatch_test" ,NULL ); +pr_info ("module unloaded\n" ); +} + +module_init (kstackwatch_test_init); +module_exit (kstackwatch_test_exit); + +MODULE_AUTHOR ("Jinchao Wang" ); +MODULE_DESCRIPTION ("Simple KStackWatch Test Module" ); +MODULE_LICENSE ("GPL" ); --2.43.0
--
You received this message because you are subscribed to the Google Groups "kasan-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion visit https://groups.google.com/d/msgid/kasan-dev/20250924115931.197077-2-wangjinchao600%40gmail.com.
Signature · 1 line
Jinchao
PATCH v5 18/23 mm/ksw: add stack overflow test
In reply to Jinchao WangExtend the test module with a new test case (test1) that intentionally overflows a local u64 buffer to corrupt the stack canary.
--- mm/kstackwatch/test.c | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-)
mm/kstackwatch/test.c +19 -1
@@ -43,6 +43,20 @@ static void test_watch_fire(void)pr_info ("exit of %s\n" , __func__); } +static void test_canary_overflow (void ) +{ +u64 buffer[BUFFER_SIZE ]; + +pr_info ("entry of %s\n" , __func__); + +/* intentionally overflow */ +for (int i =BUFFER_SIZE ; i <BUFFER_SIZE +10 ; i++) + buffer[i] =0xdeadbeefdeadbeef ; +barrier_data (buffer); + +pr_info ("exit of %s\n" , __func__); +} +static ssize_t test_proc_write (struct file *file,const char __user *buffer,size_t count,loff_t *pos)
@@ -66,6 +80,9 @@ static ssize_t test_proc_write(struct file *file, const char __user *buffer,case 0 :test_watch_fire ();break ; +case 1 : +test_canary_overflow (); +break ;default :pr_err ("Unknown test number %d\n" , test_num);return -EINVAL ;
@@ -85,7 +102,8 @@ static ssize_t test_proc_read(struct file *file, char __user *buffer,"============ usage ==============\n" "Usage:\n" "echo test{i} > /proc/kstackwatch_test\n" -" test0 - test watch fire\n" ; +" test0 - test watch fire\n" +" test1 - test canary overflow\n" ;return simple_read_from_buffer (buffer, count, pos, usage,strlen (usage));
Signature · 1 line
2.43.0
PATCH v5 19/23 mm/ksw: add recursive depth test
In reply to Jinchao WangIntroduce a test that performs stack writes in recursive calls to exercise stack watch at a specific recursion depth.
--- mm/kstackwatch/test.c | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-)
mm/kstackwatch/test.c +19 -1
@@ -57,6 +57,20 @@ static void test_canary_overflow(void)pr_info ("exit of %s\n" , __func__); } +static void test_recursive_depth (int depth) +{ +u64 buffer[BUFFER_SIZE ]; + +pr_info ("entry of %s depth:%d\n" , __func__, depth); + +if (depth <MAX_DEPTH ) +test_recursive_depth (depth +1 ); + + buffer[0 ] = depth; +barrier_data (buffer); + +pr_info ("exit of %s depth:%d\n" , __func__, depth); +}static ssize_t test_proc_write (struct file *file,const char __user *buffer,size_t count,loff_t *pos)
@@ -83,6 +97,9 @@ static ssize_t test_proc_write(struct file *file, const char __user *buffer,case 1 :test_canary_overflow ();break ; +case 2 : +test_recursive_depth (0 ); +break ;default :pr_err ("Unknown test number %d\n" , test_num);return -EINVAL ;
@@ -103,7 +120,8 @@ static ssize_t test_proc_read(struct file *file, char __user *buffer,"Usage:\n" "echo test{i} > /proc/kstackwatch_test\n" " test0 - test watch fire\n" -" test1 - test canary overflow\n" ; +" test1 - test canary overflow\n" +" test2 - test recursive func\n" ;return simple_read_from_buffer (buffer, count, pos, usage,strlen (usage));
Signature · 1 line
2.43.0
PATCH v5 20/23 mm/ksw: add multi-thread corruption test cases
In reply to Jinchao WangThese tests share a common structure and are grouped together.
- buggy():
exposes the stack address to corrupting(); may omit waiting
- corrupting():
reads the exposed pointer and modifies memory;
if buggy() omits waiting, victim()'s buffer is corrupted
- victim():
initializes a local buffer and later verifies it; reports an error if the buffer was unexpectedly modified
buggy() and victim() run in worker() thread, with similar stack frame sizes to simplify testing. By adjusting fence_size in corrupting(), the test can trigger either silent corruption or overflow across threads.
- Test 3: one worker, 20 loops, silent corruption
- Test 4: 20 workers, one loop each, silent corruption
- Test 5: one worker, one loop, overflow corruption
Test 4 also exercises multiple watchpoint instances.
--- mm/kstackwatch/test.c | 178 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 176 insertions(+), 2 deletions(-)
mm/kstackwatch/test.c +176 -2
@@ -17,11 +17,12 @@static struct proc_dir_entry *test_proc; -#define BUFFER_SIZE 16 +#define BUFFER_SIZE 32#define MAX_DEPTH 6struct work_node {ulong *ptr; +u64 start_ns;struct completion done;struct list_head list; };
@@ -30,6 +31,9 @@ static DECLARE_COMPLETION(work_res);static DEFINE_MUTEX (work_mutex);static LIST_HEAD (work_list); +static int global_fence_size; +static int global_loop_count; +static void test_watch_fire (void ) {u64 buffer[BUFFER_SIZE ] = {0 };
@@ -72,6 +76,164 @@ static void test_recursive_depth(int depth)pr_info ("exit of %s depth:%d\n" , __func__, depth); } +static struct work_node *test_mthread_buggy (int thread_id,int seq_id) +{ +ulong buf[BUFFER_SIZE ]; +struct work_node *node; +bool trigger; + + node =kmalloc (sizeof (*node),GFP_KERNEL ); +if (!node) +return NULL ; + +init_completion (&node->done); + node->ptr = buf; + node->start_ns =ktime_get_ns (); +mutex_lock (&work_mutex); +list_add (&node->list, &work_list); +mutex_unlock (&work_mutex); +complete (&work_res); + + trigger = (get_random_u32 () %100 ) <10 ; +if (trigger) +return node;/* let the caller handle cleanup */ + +wait_for_completion (&node->done); +kfree (node); +return NULL ; +} + +#define CORRUPTING_MINIOR_WAIT_NS (100000) +#define VICTIM_MINIOR_WAIT_NS (300000) + +static inline void silent_wait_us (u64 start_ns,u64 min_wait_us) +{ +u64 diff_ns, remain_us; + + diff_ns =ktime_get_ns () - start_ns; +if (diff_ns < min_wait_us *1000ULL ) { + remain_us = min_wait_us - (diff_ns >>10 ); +usleep_range (remain_us, remain_us +200 ); + } +} + +static void test_mthread_victim (int thread_id,int seq_id,u64 start_ns) +{ +ulong buf[BUFFER_SIZE ]; + +for (int j =0 ; j <BUFFER_SIZE ; j++) + buf[j] =0xdeadbeef + seq_id; +if (start_ns) +silent_wait_us (start_ns,VICTIM_MINIOR_WAIT_NS ); + +for (int j =0 ; j <BUFFER_SIZE ; j++) { +if (buf[j] != (0xdeadbeef + seq_id)) { +pr_warn ("victim[%d][%d]: unhappy buf[%d]=0x%lx\n" , + thread_id, seq_id, j, buf[j]); +return ; + } + } + +pr_info ("victim[%d][%d]: happy\n" , thread_id, seq_id); +} + +static int test_mthread_corrupting (void *data) +{ +struct work_node *node; +int fence_size; + +while (!kthread_should_stop ()) { +if (!wait_for_completion_timeout (&work_res,HZ )) +continue ; +while (true) { +mutex_lock (&work_mutex); + node =list_first_entry_or_null (&work_list, + struct work_node, list); +if (node) +list_del (&node->list); +mutex_unlock (&work_mutex); + +if (!node) +break ;/* no more nodes, exit inner loop */ +silent_wait_us (node->start_ns, +CORRUPTING_MINIOR_WAIT_NS ); + + fence_size =READ_ONCE (global_fence_size); +for (int i = fence_size; i <BUFFER_SIZE - fence_size; + i++) + node->ptr[i] =0xabcdabcd ; + +complete (&node->done); + } + } + +return 0 ; +} + +static int test_mthread_worker (void *data) +{ +int thread_id = (long )data; +int loop_count; +struct work_node *node; + + loop_count =READ_ONCE (global_loop_count); + +for (int i =0 ; i < loop_count; i++) { + node =test_mthread_buggy (thread_id, i); + +if (node) +test_mthread_victim (thread_id, i, node->start_ns); +else +test_mthread_victim (thread_id, i,0 ); +if (node) { +wait_for_completion (&node->done); +kfree (node); + } + } +return 0 ; +} + +static void test_mthread_case (int num_workers,int loop_count,int fence_size) +{ +static struct task_struct *corrupting; +static struct task_struct **workers; + +WRITE_ONCE (global_loop_count, loop_count); +WRITE_ONCE (global_fence_size, fence_size); + +init_completion (&work_res); + workers =kmalloc_array (num_workers,sizeof (void *),GFP_KERNEL ); +memset (workers,0 ,sizeof (struct task_struct *) * num_workers); + + corrupting =kthread_run (test_mthread_corrupting,NULL ,"corrupting" ); +if (IS_ERR (corrupting)) { +pr_err ("failed to create corrupting thread\n" ); +return ; + } + +for (ulong i =0 ; i < num_workers; i++) { + workers[i] =kthread_run (test_mthread_worker, (void *)i, +"worker_%ld" , i); +if (IS_ERR (workers[i])) { +pr_err ("failto create worker thread %ld" , i); + workers[i] =NULL ; + } + } + +for (ulong i =0 ; i < num_workers; i++) { +if (workers[i] && workers[i]->__state !=TASK_DEAD ) { +usleep_range (1000 ,2000 ); + i--; + } + } +kfree (workers); + +if (corrupting && !IS_ERR (corrupting)) { +kthread_stop (corrupting); + corrupting =NULL ; + } +} +static ssize_t test_proc_write (struct file *file,const char __user *buffer,size_t count,loff_t *pos) {
@@ -100,6 +262,15 @@ static ssize_t test_proc_write(struct file *file, const char __user *buffer,case 2 :test_recursive_depth (0 );break ; +case 3 : +test_mthread_case (1 ,20 ,BUFFER_SIZE /4 ); +break ; +case 4 : +test_mthread_case (20 ,1 ,BUFFER_SIZE /4 ); +break ; +case 5 : +test_mthread_case (1 ,1 ,-3 ); +break ;default :pr_err ("Unknown test number %d\n" , test_num);return -EINVAL ;
@@ -121,7 +292,10 @@ static ssize_t test_proc_read(struct file *file, char __user *buffer,"echo test{i} > /proc/kstackwatch_test\n" " test0 - test watch fire\n" " test1 - test canary overflow\n" -" test2 - test recursive func\n" ; +" test2 - test recursive func\n" +" test3 - test silent corruption\n" +" test4 - test multiple silent corruption\n" +" test5 - test prologue corruption\n" ;return simple_read_from_buffer (buffer, count, pos, usage,strlen (usage));
Signature · 1 line
2.43.0
PATCH v5 21/23 tools/ksw: add test script
In reply to Jinchao WangProvide a shell script to trigger test cases.
--- tools/kstackwatch/kstackwatch_test.sh | 52 +++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100755 tools/kstackwatch/kstackwatch_test.sh
tools/kstackwatch/kstackwatch_test.sh new file +52 -0
@@ -0,0 +1,52 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0 + +echo "IMPORTANT: Before running, make sure you have updated the config values!" + +usage() { + echo "Usage: $0 [0-5]" + echo " 0 - test watch fire" + echo " 1 - test canary overflow" + echo " 2 - test recursive depth" + echo " 3 - test silent corruption" + echo " 4 - test multi-threaded silent corruption" + echo " 5 - test multi-threaded overflow" +} + +run_test() { + local test_num=$1 + case "$test_num" in + 0) echo fn=test_watch_fire fo=0x29 wl=8 >/proc/kstackwatch + echo test0 > /proc/kstackwatch_test + ;; + 1) echo fn=test_canary_overflow fo=0x14 >/proc/kstackwatch + echo test1 >/proc/kstackwatch_test + ;; + 2) echo fn=test_recursive_depth fo=0x2f dp=3 wl=8 so=0 >/proc/kstackwatch + echo test2 >/proc/kstackwatch_test + ;; + 3) echo fn=test_mthread_victim fo=0x4c so=64 wl=8 >/proc/kstackwatch + echo test3 >/proc/kstackwatch_test + ;; + 4) echo fn=test_mthread_victim fo=0x4c so=64 wl=8 >/proc/kstackwatch + echo test4 >/proc/kstackwatch_test + ;; + 5) echo fn=test_mthread_buggy fo=0x16 so=0x100 wl=8 >/proc/kstackwatch + echo test5 >/proc/kstackwatch_test + ;; + *) usage + exit 1 ;; + esac + # Reset watch after test + echo >/proc/kstackwatch +} + +# Check root and module +[ "$EUID" -ne 0 ] && echo "Run as root" && exit 1 +for f in /proc/kstackwatch /proc/kstackwatch_test; do + [ ! -f "$f" ] && echo "$f not found" && exit 1 +done + +# Run +[ -z "$1" ] && { usage; exit 0; } +run_test "$1"
Signature · 1 line
2.43.0
PATCH v5 22/23 docs: add KStackWatch document
In reply to Jinchao WangAdd documentation for KStackWatch under Documentation/.
It provides an overview, main features, usage details, configuration parameters, and example scenarios with test cases. The document also explains how to locate function offsets and interpret logs.
--- Documentation/dev-tools/index.rst | 1 + Documentation/dev-tools/kstackwatch.rst | 316 ++++++++++++++++++++++++ 2 files changed, 317 insertions(+) create mode 100644 Documentation/dev-tools/kstackwatch.rst
Documentation/dev-tools/index.rst +1 -0
@@ -31,6 +31,7 @@ Documentation/process/debugging/index.rst kcsan kfence kselftest + kstackwatch kunit/index ktap checkuapi
Documentation/dev-tools/kstackwatch.rst new file +316 -0
316 lines not on this page · raw message
Signature · 1 line
2.43.0
PATCH v5 23/23 MAINTAINERS: add entry for KStackWatch
In reply to Jinchao WangAdd a maintainer entry for Kernel Stack Watch.
--- MAINTAINERS | 8 ++++++++ 1 file changed, 8 insertions(+)
MAINTAINERS +8 -0
@@ -13362,6 +13362,14 @@ T: git git://git.kernel.org/pub/scm/linux/kernel/git/shuah/linux-kselftest.git F: Documentation/dev-tools/kselftest* F: tools/testing/selftests/ +KERNEL STACK WATCH +M: Jinchao Wang <[email protected]> +S: Maintained +F: Documentation/dev-tools/kstackwatch.rst +F: include/linux/kstackwatch_types.h +F: mm/kstackwatch/ +F: tools/kstackwatch/ + KERNEL SMB3 SERVER (KSMBD) M: Namjae Jeon <[email protected]> M: Namjae Jeon <[email protected]>
Signature · 1 line
2.43.0