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.

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.


Need Your Help

how-to install pecl or pecl extention on Mac 10.6.7?

php osx macports pecl

I install php5.3.6 with fpm + nginx + mysql by macports. But I can't find pecl or pecl_http in it.

SQL Server SSIS and Oracle Data Pump

sql-server oracle ssis sql-server-2008-r2 datapump

I'm a beginner, and trying to improve my knowledge on DB side.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.