How can I run some machine code from within my C program?
Lets say I have the instruction ‘B2’, how can I execute this? (note that the instructions will change at run time)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
void (*foo)(void) = mmap(...),foo();) , or use inline assembly to “jmp” to the code.Note that on newer systems you will need to make sure you have requested memory which does NOT have the NX (no execute) bit set. If NX is set, jumping to your code will produce a processor exception and your process will be killed.
On Linux this is an mmap flag, on Windows there are other means to request DEP-unprotected memory.
Your code should also not rely on fixed addresses, that is it should be position independent. You cannot guarantee the same load address.
If your code needs to call into your program, it is best to provide it a table via the function call where it can resolve function addresses of your executable or C library, or attempt to use the system linker (you might have some luck using
ld.sofunctionality on Linux, but this is of course non-portable).