Is it possible to generate an array of bytes and then have Windows execute it like a normal code? Say we have some assembly code:
inc ecx
which is part of a program. After we compile with Nasm we get an EXE in which the above line is converted into something like this:
00000035 41
Would it be possible to create an array of bytes, fill it with the above bytes and execute- so the incrementation actually takes place?
I have made my super-simple interpreted language but since it is interpreted it's pretty slow. I don't want to write a real compiler for it but I would like to make it faster- compile and run on the fly.
Absolutely. Processors and operating systems that support data-execution prevention may balk, but that's easy to circumvent. Simply call VirtualProtect
to mark the block of memory as executable. It might be best to use VirtualAlloc
to allocate the memory you plan on executing. That way, you have an entire page of memory dedicated exclusively to executable code. If you call VirtualProtect
to make some arbitrary memory you allocated with GetMem
executable, it will actually mark the entire page that way, so you might accidentally mark some data as executable. If that data gets compromised, it might get executed. That's exactly what DEP is meant to protect against, so it's better to keep data and executable code in separately protected regions.
Keep in mind that the task of converting textual code into machine code is compiling, so if you don't want to write a real compiler, you might not want to generate machine code after all.
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