在C中伪造匿名函数

编程入门 行业动态 更新时间:2024-10-27 12:31:45
本文介绍了在C中伪造匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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中伪造匿名函数

本文发布于:2023-10-24 09:20:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523560.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!