/** * Lambda Functions in C Experiment * Hakson "Kerafyrm" Teh */ #include #include #include /** * Definition of function #1: */ int add( int x, int y ) { return x + y; } void dummyfunc1() {} // We need to end with a dummy function so we can easily compute the size of // the function by calculating the differences in addresses. /** * Definition of function #2: */ int sumsquares( int x, int y ) { // Just for fun, we make this function bigger: int part1 = x * x; int part2 = y * y; return part1 + part2; } void dummyfunc2() {} int subtract( int x, int y ) { return x - y; } /** * ENTRY POINT */ int main( int argc, char *argv[] ) { int a, b, c; // Stack buffer to hold the code: char lambda[5000]; /** * Print statistics :) */ printf( " Addr of add func(): %lx\n", (unsigned long)add ); printf( " Addr of dummyfunc1(): %lx\n", (unsigned long)dummyfunc1 ); printf( " Addr of submquares func(): %lx\n", (unsigned long)sumsquares ); printf( " Addr of dummyfunc1(): %lx\n", (unsigned long)dummyfunc2 ); printf( " Addr of main(): %lx\n", (unsigned long)main ); unsigned long function_add_size = (long)dummyfunc1 - (long)add; unsigned long function_sumsquares_size = (long)dummyfunc2 - (long)sumsquares; printf( " add() function size: %lu\n", function_add_size ); printf( " sumsquares() function size: %lu\n", function_sumsquares_size ); a = b = 0; printf( "Before calls to lambda function:\n"); printf( " a = %d\n", a ); printf( " b = %d\n", b ); // Load the first "lambda function" and call it: memcpy( &lambda, (char*)add, function_add_size ); a = ((int (*)(int, int)) lambda)(4, 5); // Load the second "lambda function" and call it: memcpy( &lambda, (char*)sumsquares, function_sumsquares_size ); b = ((int (*)(int, int)) lambda)(4, 5); // Load the machine code for a function that takes two ints, subtracts them // and returns the result as an int: strcpy( lambda, "\x55\x89\xe5\x8b\x55\x0c\x8b\x45\x08\x29\xd0\x5d\xc3" ); c = ((int (*)(int, int)) lambda)(10, 2); printf( "After calls to lambda function:\n"); printf( " a = %d\n", a ); printf( " b = %d\n", b ); printf( " c = %d\n", c ); return EXIT_SUCCESS; }