4

I recently thought about precompilable scripting language, which would be translated to machine code during program loading.

Lets say that I can generate this binary function myself. Now I need to somehow execute it. The general scheme would look like that:

char* binary = compile("script.sc");
pushArgsToStack(1,7);
memexec(binary);
int ret = getEax();

Is there any chance to get it working?

Also, would calling jmp to c++ funcion address work like planned? I mean, after pushing args, returnAddr and so on, I want to somehow call that function from my compiled script.

Thanks for any answers

noisy cat
  • 2,865
  • 5
  • 33
  • 51
  • 1
    http://stackoverflow.com/questions/2019923/executing-machine-code-in-memory – Iłya Bursov May 29 '14 at 06:44
  • 1
    Feasible with additional permissions on a specifically allocated memory block using VirtualAllocEx(): http://stackoverflow.com/q/4911993/1175253 – Sam May 29 '14 at 06:45
  • @KittyPL: Have you considered using other programming languages for this? Even if it can be done (with significant effort) in C++, there are already a number of ready-to-use dynamic scripting languages out there. – Christian Hackl May 29 '14 at 09:12
  • I don't know if you want to write your own language, but - as Christian Hackl noticed - there are already such solutions. From my perspective LuaJit seems what you are looking for. – Red XIII May 29 '14 at 09:43

1 Answers1

3

This certainly can be done.

The biggest part will be the compile function, which unless your ".sc" language is VERY trivial will require quite a bit of work. You may want to have a look at for example llvm, which allows you to generate code from an intermediate virtual machine instruction set. It adds a lot of code, but makes your life a bit easier when it comes to generating (reasonably good) instructions.

You can't really push arguments in a function - the pushing will be removed when you return. You would have to generate the push instructions as part of the "compile" process.

And you should be able to to do:

int ret = memexec(binary);

You probably want to write memexec in assembler, and perhaps have it take multiple arguments (but you'd still have the problem if what type those arguments are, so some sort of list of arguments with type information is probably really what is required - or always pass arguments as strings, or some such)

Assuming you have an operating system made in the last 15-20 years, you will also need to allocate memory with "execute rights", which requires something other than malloc. Deopending on OS, the calls you need will vary.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227