Linux kernel layer-application layer

Kernel layer calls application layer programs

Reference blog:
linux driver calls (run/execute) applications . You
only need to execute this function at the kernel layer:

extern int call_usermodehelper(char *path, char **argv, char **envp, int wait);

Kernel layer program:

#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/kmod.h>

MODULE_AUTHOR("darui");
MODULE_LICENSE("GPL");

static int __init practiceCall(void)
{
    
    
		int ret = 0;
        char *path = "/home/darui/practice/a";
        char *arv[] = {
    
    path,"",NULL};//无参数,注意要按照这个格式path在 第一个位置,必须NULL结束
        char *env[] = {
    
    "/home/darui","/usr/local/sbin",NULL};//多路径可以用逗号隔开,也可以在一对引号中用分号隔开,必须NULL结束标志

        printk("%s:call_usermodehelper\n",__func__);
        ret = call_usermodehelper(path,arv,env,UMH_WAIT_PROC);
        if(ret < 0)
        {
    
    
        	printk("error");
        	return -1;
        }
        return 0;
}

static void __exit practiceCallExit(void)
{
    
    
        printk("%s:call_usermodehelper\n",__func__);
}

module_init(practiceCall);
module_exit(practiceCallExit);

Note that there is a pitfall, the execution program cannot be a.sh and other programs, it should only be a compiled program, and the execution of the shell script will cause an error (stuck for a long time)

Application layer program source code:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main()
{
    
    
        int fd = -1;

        fd = open("/home/darui/practice/file.txt",O_RDWR|O_CREAT);
        write(fd,":practice\n",10);
        close(fd);
}

gcc -oa ac can be compiled, and the file.txt file will be created

Principle:
call_usermodehelper
——》call_usermodehelper_setup + call_usermodehelper_exec
————》queue_work
——————》__call_usermodehelper
————————》do_execve
——————————
1. In the process stack Push into the application layer program,
2. The iret instruction saves the kernel on-site for stack switching,
3. After the application layer is executed, ret_from_sys_call returns

Patch the pit

Patch the pit

Guess you like

Origin blog.csdn.net/qq_42882717/article/details/114062512