Fake anonymous functions in C

后端 未结 3 1022
孤独总比滥情好
孤独总比滥情好 2021-02-05 15:23

In this SO thread, Brian Postow suggested a solution involving fake anonymous functions:

make a comp(L) function that returns the version of comp for arra

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-05 16:24

    See the answer I just posted to that question. You can use the callback(3) library to generate new functions at runtime. It's not standards compliant, since it involves lots of ugly platform-specific hacks, but it does work on a large number of systems.

    The library takes care of allocating memory, making sure that memory is executable, and flushing the instruction cache if necessary, in order to ensure that code which is dynamically generated (i.e. the closure) is executable. It essentially generates stubs of code that might look like this on x86:

      pop %ecx
      push $THUNK
      push %ecx
      jmp $function
    THUNK:
      .long $parameter
    

    And then returns the address of the first instruction. What this stub does is stores the the return address into ECX (a scratch register in the x86 calling convention), pushes an extra parameter onto the stack (a pointer to a thunk), and then re-pushes the return address. Then, it jumps to the actual function. This results in the function getting fooled into thinking it has an extra parameter, which is the hidden context of the closure.

    It's actually more complicated than that (the actual function called at the end of the stub is __vacall_r, not the function itself, and __vacall_r() handles more implementation details), but that's the basic principle.

提交回复
热议问题