Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I compile the code on the fly in Delphi and execute it?

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.

like image 845
Tom Avatar asked May 01 '13 12:05

Tom


1 Answers

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.

like image 189
Rob Kennedy Avatar answered Nov 15 '22 05:11

Rob Kennedy