| Paste number 44085: | hacky closures in C |
| Pasted by: | bsmntbombdood |
| 1 year, 3 months ago | |
| #lispcafe | Context in IRC logs | |
| Paste contents: |
| #include <string.h> #include <stdlib.h> #include <stdio.h> #include <sys/mman.h> void begin_adder_closure() {} /* to get the length of base_adder */ int base_adder(int x) { int closure = 0xDEADBEEF; return closure + x; } void end_adder_closure() {} void *make_adder(int num) { int size; char *newfunc; char *curr; size = end_adder_closure - begin_adder_closure; /* printf("size: %d\n", size); */ newfunc = malloc(size); mprotect(newfunc, size, PROT_WRITE | PROT_READ | PROT_EXEC); memcpy(newfunc, base_adder, size); /* implant our value into the function. there's probably some way to calculate the offset we want, but I don't know it */ curr = newfunc; while(*((int*)curr) != 0xDEADBEEF) { curr++; } *((int*)curr) = num; return newfunc; } int main() { int (*test)(int); test = make_adder(2); printf("result of 2+3: %d\n", test(3)); return 0; } |
This paste has no annotations.