[PATCH] ftrace: fix use-after-free of mod->name in function_stat_show()

From: Xiang Gao

Date: Thu Apr 16 2026 - 04:39:11 EST


From: Xiang Gao <gaoxiang17@xxxxxxxxxx>

function_stat_show() uses guard(rcu)() inside the else block to hold
the RCU read lock while calling __module_text_address() and accessing
mod->name. However, guard(rcu)() ties the RCU read lock lifetime to
the scope of the else block. The original code stores mod->name into
refsymbol and uses it in snprintf() after the else block exits,
at which point the RCU read lock has already been released. If the
module is concurrently unloaded, mod->name is freed, causing a
use-after-free.

Fix by moving the snprintf() call into each branch of the if/else,
so that mod->name is only accessed while the RCU read lock is held.
refsymbol now points to the local str buffer (which already contains
the formatted string) rather than to mod->name, and is only used
afterwards as a non-NULL indicator to skip the kallsyms_lookup()
fallback.

Signed-off-by: Xiang Gao <gaoxiang17@xxxxxxxxxx>
---
kernel/trace/ftrace.c | 10 ++++++----
1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/kernel/trace/ftrace.c b/kernel/trace/ftrace.c
index 413310912609..6217b363203c 100644
--- a/kernel/trace/ftrace.c
+++ b/kernel/trace/ftrace.c
@@ -559,21 +559,23 @@ static int function_stat_show(struct seq_file *m, void *v)
unsigned long offset;

if (core_kernel_text(rec->ip)) {
- refsymbol = "_text";
offset = rec->ip - (unsigned long)_text;
+ snprintf(str, sizeof(str), " %s+%#lx",
+ "_text", offset);
+ refsymbol = str;
} else {
struct module *mod;

guard(rcu)();
mod = __module_text_address(rec->ip);
if (mod) {
- refsymbol = mod->name;
/* Calculate offset from module's text entry address. */
offset = rec->ip - (unsigned long)mod->mem[MOD_TEXT].base;
+ snprintf(str, sizeof(str), " %s+%#lx",
+ mod->name, offset);
+ refsymbol = str;
}
}
- if (refsymbol)
- snprintf(str, sizeof(str), " %s+%#lx", refsymbol, offset);
}
if (!refsymbol)
kallsyms_lookup(rec->ip, NULL, NULL, NULL, str);
--
2.34.1