I have a pointer to a function (which i get from a vtable) and I want to edit the function by changing the assembler code (changing a few bytes) at runtime. I tried using memset and also tried assigning the new value directly (something like mPtr[0] = X, mPtr[1] = Y etc.) but I keep getting segmentation fault. How can I change the code?
(I'm using C++)
开发者_StackOverflow中文版OS is windows.
In generally: if memory is allocated with API call VirtualAlloc than you can change the memory attributes with API call VirtualProtect. Check first memory attributes with API call VirtualQuery
Depending on Operating System and/or architecture you may or may not write to executable pages.
Check documentation about marking pages as executable or read-only in the Intel (IA-32e) manuals. The code may be located in a read only section, therefore, you may not write to it.
You may mark the code not to reside in read only pages, but it's compiler specific (JIT compilers do this).
Under MSVC, you can use the #pragma section to create a read-write section and use #pragma alloc_text to put functions in it.
In general, you are trying to write to the code segment, something new operating systems will prevent you to do. This is the way some viruses worked.
There are APIs to remove that protection, but they are operating system dependent.
Memory sections where your code reside are usually marked as readonly. That's why you get segmentation failure. You can try to remove this flag from section by either special keys for compiler (not sure about that) or by modifying binary file (again, not 100% that it is possible)
精彩评论