在C中伪造匿名函数 [英] Fake anonymous functions in C

查看:63
本文介绍了在C中伪造匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此SO 线程中,建议一种涉及假冒匿名函数的解决方案:

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

创建一个comp(L)函数,该函数返回长度为L的数组的comp版本...这样,L成为参数,而不是全局变量

make a comp(L) function that returns the version of comp for arrays of length L... that way L becomes a parameter, not a global

如何实现这样的功能?

推荐答案

请参见我刚刚发布的答案.您可以使用 callback(3) 库来生成新功能在运行时.它不符合标准,因为它涉及许多丑陋的特定于平台的黑客,但它确实可以在大量系统上工作.

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.

该库负责分配内存,确保内存是可执行的,并在必要时刷新指令高速缓存,以确保动态生成的代码(即闭包)是可执行的.本质上,它会生成在x86上看起来像这样的代码存根:

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

然后返回第一条指令的地址.该存根的作用是将返回地址存储到ECX(x86调用约定中的暂存寄存器)中,将一个额外的参数压入堆栈(指向thunk的指针),然后重新推送返回地址.然后,它跳转到实际功能.这导致该函数误以为该函数具有一个额外的参数,该参数是闭包的隐藏上下文.

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.

实际上要比这复杂得多(在存根末尾调用的实际函数是__vacall_r,而不是函数本身,并且__vacall_r()处理更多的实现细节),但这是基本原理.

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.

这篇关于在C中伪造匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆