开发者

Calling manually loaded code (AT&T + C) (g++)

开发者 https://www.devze.com 2023-01-15 08:55 出处:网络
I\'m implementing a program which loads pure code from a file and calls the first instruction. No matter what I do, I get a Segmentation fault when my call instruction is executed. What do I do wrong?

I'm implementing a program which loads pure code from a file and calls the first instruction. No matter what I do, I get a Segmentation fault when my call instruction is executed. What do I do wrong?

cha开发者_运维知识库r code[65536];
...
__asm__("movl code, %eax");
__asm__("call *%eax");


is the "pure code" compatible to your program? What OS? "normally" the "pure code" is relocated annd will be "moved" to the corresponding address in memory by the "linkage-loader" that does the apropriate adjustments.


For generated code to execute - it must be in an executable section.

On x86-64, try this instead

char* code = mmap(0, 1024 * 1024, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_32BIT | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

on a 32-bit system, the map_32bit is not relevant (it is used on x86-64 to make sure code can go into the first 2GB, and use relative addressing)


OS is Linux Ubuntu.

I know that it's normally done that way. The code is compatible, it's from my own compiler which generates a file with just program code and the first instruction in the file is the first instruction of the main method.

(I'm a student and I have to do it manually so I learn something! ;-) =


Check your stack values with a debugger when returning from the imported code and double check it contains a valid return address. How does your imported code get called? Do you push any values before calling the imported code and does the imported code adjust the stack at the end?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号