<?xml version="1.0"?>
<paste-with-annotations>
  <paste>
    <number>
      <integer>44085</integer>
    </number>
    <user>
      <string>bsmntbombdood</string>
    </user>
    <title>
      <string>hacky closures in C</string>
    </title>
    <contents>
      <string>#include &lt;string.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;sys/mman.h&gt;

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(&quot;size: %d\n&quot;, 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(&quot;result of 2+3: %d\n&quot;, test(3));
  return 0;
}
</string>
    </contents>
    <universal-time>
      <integer>3392768280</integer>
    </universal-time>
    <channel>
      <string>#lispcafe</string>
    </channel>
    <colorization-mode>
      <string>C</string>
    </colorization-mode>
    <maybe-spam>
      <null/>
    </maybe-spam>
    <is-unicode>
      <null/>
    </is-unicode>
  </paste>
</paste-with-annotations>