Advertisement
hxrussia

Generating functions in plain C

Nov 3rd, 2014
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.63 KB | None | 0 0
  1. /*
  2.  * Compile this with:
  3.  *     $ gcc example.c -o example -z execstack
  4.  * */
  5.  
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8.  
  9. typedef int (*FunctionThatReturnsInt)();
  10.  
  11. FunctionThatReturnsInt GenerateAFunctionThatReturnsX(int x) {
  12.     void *buf = malloc(6);
  13.    
  14.     // mov eax, x
  15.     *(unsigned char *) buf = 0xb8;
  16.     *(int *) (buf + 1) = x;
  17.    
  18.     // ret
  19.     *(unsigned char *) (buf + 5) = 0xc3;
  20.    
  21.     return (FunctionThatReturnsInt) buf;
  22. }
  23.  
  24. int main() {
  25.     int i;
  26.     for (i = 0; i < 10; i++) {
  27.         FunctionThatReturnsInt f = GenerateAFunctionThatReturnsX(i);
  28.         printf("%d\n", f());
  29.     }
  30.     return 0;
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement