The answers to the question How to allocate an executable page in a Linux kernel module? describe how executable memory can be allocated using __vmalloc()
. Is this also possible using kmalloc()
? My goal is having a physically-contiguous executable memory area.
-
1IIRC, `kmalloc` just gives you a pointer into the existing direct-mapped region that maps all physical memory. So the question is whether this existing mapping has exec permission or not. (IDK, could go either way. Yes for performance: don't need separate mappings for code parts. No for security so there isn't a kernel-executable mapping of all memory contents just sitting there waiting to be used as a "gadget" by a ROP attack or even as a Spectre gadget). – Peter Cordes Dec 22 '19 at 22:11
-
1@PeterCordes It does not have exec permissions. I tried it, and dmesg shows "kernel tried to execute NX-protected page - exploit attempt? (uid: 0)" – andreas Dec 23 '19 at 02:29
1 Answers
It does not have exec permissions. I tried it, and dmesg shows "kernel tried to execute NX-protected page - exploit attempt? (uid: 0)"
Then no, I'd assume you can't kmalloc
executable memory. Unless I'm wrong about how it works (returning pointers into an existing mapping that uses 1GB hugepages to cover all of physical RAM) it's just plain incompatible with the purpose / design of kmalloc
.
There might be something other than vmalloc
that you could use, if you really need more than 1 physically-contiguous 4k page of executable memory, but I don't know what it is. (I'm not a kernel dev, I just know a little bit about the big picture, and lots about CPU architecture / x86). Perhaps something like vmalloc
and then changing the page tables?
Other answers welcome.

- 328,167
- 45
- 605
- 847
-
Downvote this all you want; it's still (I think) correct that `kmalloc` itself never remaps page-table entries ([What is the difference between vmalloc and kmalloc?](//stackoverflow.com/q/116343)) and thus can't give you executable pages. If there is some function that makes physical contiguous + executable possible, leaving a comment or writing an answer would be much more useful to future readers than a downvote. – Peter Cordes Jan 03 '20 at 05:30