1 // SPDX-License-Identifier: GPL-2.0-only
3 * Here's a sample kernel module showing the use of fprobe to dump a
4 * stack trace and selected registers when kernel_clone() is called.
6 * For more information on theory of operation of kprobes, see
7 * Documentation/trace/kprobes.rst
9 * You will see the trace data in /var/log/messages and on the console
10 * whenever kernel_clone() is invoked to create a new process.
13 #define pr_fmt(fmt) "%s: " fmt, __func__
15 #include <linux/kernel.h>
16 #include <linux/module.h>
17 #include <linux/fprobe.h>
18 #include <linux/sched/debug.h>
19 #include <linux/slab.h>
21 #define BACKTRACE_DEPTH 16
22 #define MAX_SYMBOL_LEN 4096
23 struct fprobe sample_probe;
25 static char symbol[MAX_SYMBOL_LEN] = "kernel_clone";
26 module_param_string(symbol, symbol, sizeof(symbol), 0644);
27 static char nosymbol[MAX_SYMBOL_LEN] = "";
28 module_param_string(nosymbol, nosymbol, sizeof(nosymbol), 0644);
29 static bool stackdump = true;
30 module_param(stackdump, bool, 0644);
32 static void show_backtrace(void)
34 unsigned long stacks[BACKTRACE_DEPTH];
37 len = stack_trace_save(stacks, BACKTRACE_DEPTH, 2);
38 stack_trace_print(stacks, len, 24);
41 static void sample_entry_handler(struct fprobe *fp, unsigned long ip, struct pt_regs *regs)
43 pr_info("Enter <%pS> ip = 0x%p\n", (void *)ip, (void *)ip);
48 static void sample_exit_handler(struct fprobe *fp, unsigned long ip, struct pt_regs *regs)
50 unsigned long rip = instruction_pointer(regs);
52 pr_info("Return from <%pS> ip = 0x%p to rip = 0x%p (%pS)\n",
53 (void *)ip, (void *)ip, (void *)rip, (void *)rip);
58 static int __init fprobe_init(void)
60 char *p, *symbuf = NULL;
64 sample_probe.entry_handler = sample_entry_handler;
65 sample_probe.exit_handler = sample_exit_handler;
67 if (strchr(symbol, '*')) {
68 /* filter based fprobe */
69 ret = register_fprobe(&sample_probe, symbol,
70 nosymbol[0] == '\0' ? NULL : nosymbol);
72 } else if (!strchr(symbol, ',')) {
74 ret = register_fprobe_syms(&sample_probe, (const char **)&symbuf, 1);
78 /* Comma separated symbols */
79 symbuf = kstrdup(symbol, GFP_KERNEL);
84 while ((p = strchr(++p, ',')) != NULL)
87 pr_info("%d symbols found\n", count);
89 syms = kcalloc(count, sizeof(char *), GFP_KERNEL);
96 for (i = 0; i < count; i++)
97 syms[i] = strsep(&p, ",");
99 ret = register_fprobe_syms(&sample_probe, syms, count);
104 pr_err("register_fprobe failed, returned %d\n", ret);
106 pr_info("Planted fprobe at %s\n", symbol);
111 static void __exit fprobe_exit(void)
113 unregister_fprobe(&sample_probe);
115 pr_info("fprobe at %s unregistered\n", symbol);
118 module_init(fprobe_init)
119 module_exit(fprobe_exit)
120 MODULE_LICENSE("GPL");