Self modifying code always segmentation faults on Linux

大憨熊 提交于 2019-11-27 07:54:36

You should to change memory access permissions in runtime.

#include <sys/mman.h>

void *addr  = get_address_of_instruction_pointer();
int  length = 4096;   /* size of a page */

if (mprotect(addr, length, PROT_READ | PROT_WRITE | PROT_EXEC) == 0) {
    /* current code page is now writable and code from it is allowed for execution */
}

Modern CPUs have a feature called DEP which prevents execution of code on the stack. Previously, this was possible; now, it is not. The binary is loaded into read-only memory by default.

With that out of the way, you can use the mprotect system call to mark your binary's location in memory as executable - SO LONG AS YOUR CODE IS NOT DEP-PROTECTED. So don't try to put code and the stack and then jump into it.

You can also disable write-protection for the entire program by passing the switch -N to the linker. If you are invoking the linker from gcc, pass Wl,-N. If you invoke ld directly, pass -N.

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