What's the protection flags of memory allocated by malloc?

断了今生、忘了曾经 提交于 2019-12-01 04:40:51

malloc is not the right tool for allocating memory for code. You should use mmap, and depending on the paranoid security policies on your system, you might need to use mprotect too for changing the permissions.

Among the reasons malloc is not the right tool:

  • Permissions are set only with page granularity, but memory obtained by malloc is unlikely to be page-aligned, and thus you'll end up setting permissions on adjacent memory too, possibly breaking things.
  • If you don't restore the old permissions before calling free, you might break malloc's internals.
ninjalj

malloc() will normally return memory with read and write permissions. Some architectures (e.g: older x86) may not allow disabling execute permission in a straightforward way, but that's just a defficiency of the platform.

If you want to execute code from memory you allocated, you'll have to give execute permissions explicitly, and possibly you'll have to remove write permissions, since having both write and execute permissions on the same memory is considered potentially dangerous on some systems (commonly referred as W^X).

There have been several other threads on executing code from memory allocated by the programmer:

Allocate executable ram in c on linux
Is it possible to execute code from the stack in standard C?

You may need to call mprotect to set the PROT_EXEC flag yourself, after the memory has been allocated.

$ man mprotect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!