Create function in memory

*爱你&永不变心* 提交于 2019-12-06 09:50:35

A few points:

  • your asm_commands[] should probably be unsigned char (or uint8_t) - as is, you'll be copying 3 NUL/0 characters as well as the 0x90

  • some Operating Systems will just not let you execute instructions in memory you've allocated with malloc() - they'll SIGSEGV or similar instead - that's intended to prevent certain types of stack overflow and other hackery

  • I suggest you write an actual function void f() { } and see what opcodes are generated for it, using g++ -S or whatever your compiler offers, as you might need to do something more than just 0xC3 to return properly (e.g. pop certain registers)

    • if "cloning" instructions from an actual C++ function to get you started on a tweaked asm function, be wary of position dependent code too... you can't just copy data and code addresses within the function as they won't be inside the malloced region. Position Independent Code (PIC) uses relative addressing opcodes to avoid this... that's what you'll need to write.

You can do what you describe. However, memory allocated with malloc() might not have the permission for code execution - depending on your platform.

The way to allocate executable memory differs from OS to OS. On Linux, check mmap. On Windows, see VirtualAlloc.

Function calling is more complex than that.

You must at least modify the base pointer. I suggest you look at the dissassembly of a function call and try to mimic it

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