In C. I need a way to execute computer instructions DIRECTLY while a program is running. The only way I know how to make computer instructions in binary is through a hex editor, then you run the file as an application. How would I write the binary using a program and then execute it from their without having to create a new process for execution. It seems like their should be a simple way to do this but no matter where I look I can't find it.
The only other way I can think of doing this is through inline assembly, but in my current project that would be a drawback, executing directly with binary is the best way to go. (would this possibly require a driver on windows? how to do on linux? in other words a cross-platform method would be nice)
Thank you.
What you want to do is a bit problematic and is liable to make a lot of people ask "Why are you doing that?"
Assuming you have an operating system WITHOUT memory protection (which is very rare), you can just point a function to array of bytes and call the function. Here's the gist of it:
unsigned char* code_to_execute = "\xB8\x13\x00\xCD\x10";
void (*runCode)();
runCode = code_to_execute;
runCode();
But, there are SO MANY THINGS to worry about when doing something like this. You need to know how your C compiler is setting up function call frames and respect that in your "binary code". It's impossible to create cross-platform code in this manner. Even making it run in multiple C compilers on a single platform would be tricky. And then there's memory protection. Most modern operating systems simply won't let you arbitrarily execute data as code. You need to explicitly mark the memory as executable and many operating systems won't let you do that without special permission. There is no cross-platform way to do this either.
Again, I want to stress that this is really not a good idea. You would be better off using inline assembly language. Or better yet, don't use assembly language at all. Maybe you could explain a little more about your project and why it's important to write "binary code" directly in your C program. It would help us craft an answer or recommendation that could help you considerably.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With