0

I know that you can't use malloc inside a kernel module because all functions used in the kernel must be defined in the kernel, but how exactly does the kernel achieve this lock-down?

Zuriar
  • 11,096
  • 20
  • 57
  • 92

2 Answers2

2

It's not so much that it's locked down. It's just that your kernel module has no idea where malloc() is. The malloc() function is part of the C standard library, which is loaded alongside programs in userspace. When a userland program is executed, the linker will load the shared libraries needed by the program and figure out where the needed functions are. SO it will load libc at an address, and malloc() will be at some offset of that. So when your program goes to call malloc() it actually calls into libc.

Your kernel module isn't linked against libc or any other userspace components. It's linked against the kernel, which doesn't include malloc. Your kernel driver can't depend on the address of anything in userspace, because it may have to run in the context of any userspace program or even in no context, like in an interrupt. So the code for malloc() may not even be in memory anywhere when your module runs. Now if you knew that you were running in the context of a process that had libc loaded, and knew the address that malloc() was located at, you could potentially call that address by storing it in a function pointer. Bad things would probably happen though, possibly including a kernel panic. You don't want to cross userspace and kernelspace boundaries except through sane, well defined interfaces.

itsokimbatman
  • 69
  • 1
  • 3
  • For one, a userspace malloc() may not be able to allocate pages with the correct ownership and permissions for kernel needs. For another, a userspace malloc() really can't do *anything* without calling back into the kernel, unless it gives you memory previously obtained by such a mechanism. There are, of course, a variety of memory allocation functions *within* the kernel which play a similar role for the needs of kernel code, as malloc() does for user code. – Chris Stratton Oct 19 '14 at 22:22
  • 1
    Just to add to the above, malloc() is a memory manager implemented by glibc which inturn call brk() syscall. malloc() ---> [glibc.so] ---> sbrk()/brk() ---> sys_brk(). Note: for memory allocation in the kernel space use kmalloc(), vmalloc() which are similar to malloc. – askb Oct 20 '14 at 02:46
-2

When you write a module for the kernel you just don't have this functions in your header files. And you don't have it in the files you are linking with.

Also the malloc's implementation is a procedure calling system calls. System calls moves you to hypervisor and calls the kernel's code. There is no point doing it while in hypervisor mode.

You can see it here in more details.

Community
  • 1
  • 1
  • Whether `malloc()` uses system calls is a implementation detail. Also, I don't think you're using the term *hypervisor* correctly here. – tangrs Oct 20 '14 at 07:29