User:Renamed user awfwvowjvwrvnwio/How to implement closures in assembly

This is a tutorial in how to implement closures in x86 assembly. We will assume a Win32 or WOW64 architecture and the NASM assembler.

This can be easily adapted to other operating systems by changing allocation methods and can easily be translated to other x86 assemblers.

See the header /metafuncs.h for an implementation in C++ of the combinators.

Method
This works by having a function that fills in a function skeleton with the argument(s) it received.

For instance, the skeleton for the K combinator is:

Note it assembles into: B8 CC CC CC CC C2 04 00 and the 4 bytes to replace are at 1 byte from the start.

Then we make the K function, that works as follows:

We allocate a block in a executable heap (created by calling the function HeapCreate in KERNEL32.DLL or RtlCreateHeap in ntdll.dll) that is 8 bytes long.

The code is below:

Partial functions
We then perform partial function evaluation using the same skeleton technique.

"AllocateCodeBlock" is a function allocating a readable, writable, executable memory block that takes two arguments and is STDCALL as are many of the functions in the library. It takes two arguments: a starting address (0 if allow system to decide, in here it is the case) and a memory size (in this case 4096 bytes, the minimum size). Simply, it allocates a readable, writable and executable memory block and fills it with a 24-byte skeleton with two 4-byte blank spots, one 7 bytes after the start and the other 12 bytes after.

Those are for the first argument of the function given and the function itself, respectively. This is a partial function evaluator because it takes a two-argument function f as its first argument and the first argument of that function x and produces a partially evaluated function g which takes an argument y and returns f(x, y). This calling operation is STDCALL, again.

I'll soon perform a full currying operation using another skeleton operation.