从 ftrace 处理程序返回到原始函数时恢复任务pt_regs



使用内核模块(LKM(,linux内核ftrace函数允许您设置FTRACE_OPS_FL_SAVE_REGSFTRACE_OPS_FL_IPMODIFY标志,实质上允许您完全重定向任何可以找到符号地址的内核函数,如下所示:

static void notrace my_ftrace_handler(unsigned long ip, unsigned long parent_ip,
        struct ftrace_ops *fops, struct pt_regs *regs) {
    regs->ip = new_addr;
}

其中new_addr是新函数的地址。kpatch工具使用它,尽管永远不会返回到原始函数。

如果在new_addr指向的函数末尾,我尝试这样做:

task_pt_regs(current)->ip = orig_addr + MCOUNT_INSN_SIZE;

某些函数可以毫无问题地运行,但大多数函数会导致调用过程出现段错误。

ftrace函数具有内置代码,可以在返回到原始函数时恢复当前任务的pt_regs,这就是为什么我能够转到自己的函数并毫无问题地使用参数的原因。但是,在代码的此时,不再涉及ftrace。我如何告诉内核不要重置当前寄存器,以便函数可以在新的返回地址使用它们?

发布此内容后,我想也许我可以直接从 ftrace 处理程序中的pt_regs *regs指针读取参数。事实证明,你可以。通过不重定向到另一个函数,您可以保留寄存器和返回地址,同时决定是返回到那里还是从处理程序本身返回其他地方:

int donotexec(void) {
        return -EACCES;
}
static void notrace my_ftrace_handler(unsigned long ip, unsigned long parent_ip,
                    struct ftrace_ops *fops, struct pt_regs *regs) {
    struct linux_binprm *bprm = (struct linux_binprm *)regs->di;
    if (bprm->file)
            if (allowed_to_exec(bprm->file))
                    regs->ip = (unsigned long)donotexec;
}

这个函数钩security_bprm_check,其中allowed_to_exec是另一个检查从regs->di寄存器读取的bprm->file的函数。

这是依赖于 arch 的(参见 arch/x86/include/asm/ptrace.h 中内核的 pt_regs 结构(,并且仅限于 5 个函数参数。

最新更新