Call a Kernel Module Function from Program at User Space

Calling a user defined function in kernel space from user space application program

Well, what you have there is normally referred to as "syscall". I suggest you read into the kernel developer documentation on how to expose a new syscall. On the userspace side, the libc provides you a function syscall, that you can use to call into kernel space. But normally you write a wrapper around it.

However introducing new syscalls should be avoided. The preferred way to call into kernel space is to use sysfs and expose the user space callable functions as files therein.

How can I Execute/Call a user-space defined function from Linux kernel space module?

You can, but it is a really bad idea. You need to establish a pointer to your user mode function, arrange for the process containing that function to be running (in the kernel) when you invoke it. That is a lot of work, and is fundamentally malware due to the security holes it creates. Additionally, in the mad dash to lock the door to the now empty barn in the wake of spectre et al, new layers of hackery are being deployed in newer CPUs to make this even harder.

A different approach:

In your original query, you are running this driver as a "tee"; that is, you take the input you receive from the device, give a copy to the caller, and call eval_keycode with each input. Eval_keycode doesn't modify the data, and the kernel module discards it afterwards. So Eval_keycode doesn't really need to be a function; or rather, there could be a user function:

void ProcessEvents(int fd) {
struct input_event ev;
while (read(fd, &ev, sizeof ev) == sizeof ev) {
eval_keycode(&ev);
}
}

if you could arrange for all the events to be fed into that fd. With this setup, your problem becomes more plumbing than kernel renovation. The user creates a pipe/socket/fifo/... and passes the write end to your kernel module (yay more ioctl()s). Your kernel module can then carefully use kernel_write() ( or vfs_write if you are stuck in the past ) to make these events available to the user handler. It wants to be careful about where its blocking points are.

You could extend this to work as a transform; that is where your driver transforms the events via a user mode handler; but at that point, you might really consider FUSE a better solution.

How can i call a function that written in kernel module, from the user program?

You can make your driver to react on writes (or if necessary, ioctl) to a /dev/xxx file or a /proc/xxx file. Also, you can create a new syscall, but that's more of a toy as the module would only work on custom built kernels.

Edit: try http://www.faqs.org/docs/kernel/x571.html (on character device drivers.)



Related Topics



Leave a reply



Submit