gpt4 book ai didi

c - 如何确定函数的长度?

转载 作者:太空狗 更新时间:2023-10-29 15:36:45 30 4
gpt4 key购买 nike

考虑以下采用函数 f() 的代码,将函数本身完整复制到缓冲区,修改其代码并运行更改后的函数。在实践中,返回数字 22 的原始函数被克隆和修改为返回数字 42。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define ENOUGH 1000
#define MAGICNUMBER 22
#define OTHERMAGICNUMBER 42

int f(void)
{
return MAGICNUMBER;
}

int main(void)
{
int i,k;
char buffer[ENOUGH];
/* Pointer to original function f */
int (*srcfptr)(void) = f;
/* Pointer to hold the manipulated function */
int (*dstfptr)(void) = (void*)buffer;
char* byte;
memcpy(dstfptr, srcfptr, ENOUGH);
/* Replace magic number inside the function with another */
for (i=0; i < ENOUGH; i++) {
byte = ((char*)dstfptr)+i;
if (*byte == MAGICNUMBER) {
*byte = OTHERMAGICNUMBER;
}
}

k = dstfptr();
/* Prints the other magic number */
printf("Hello %d!\n", k);
return 0;
}

代码现在仅依赖于猜测该函数将适合 1000 字节的缓冲区。它还通过向缓冲区复制太多内容来违反规则,因为函数 f() 很可能比 1000 字节短很多。

这给我们带来了问题:是否有一种方法可以计算出 C 中任何给定函数的大小?一些方法包括查看中间链接器输出,并根据函数中的指令进行猜测,但这还不够。有什么方法可以确定吗?


请注意:它可以在我的系统上编译和运行,但并不完全符合标准,因为函数指针和 void* 之间的转换是不允许的:

$ gcc -Wall -ansi -pedantic fptr.c -o fptr
fptr.c: In function 'main':
fptr.c:21: warning: ISO C forbids initialization between function pointer and 'void *'
fptr.c:23: warning: ISO C forbids passing argument 1 of 'memcpy' between function pointer and 'void *'
/usr/include/string.h:44: note: expected 'void * __restrict__' but argument is of type 'int (*)(void)'
fptr.c:23: warning: ISO C forbids passing argument 2 of 'memcpy' between function pointer and 'void *'
/usr/include/string.h:44: note: expected 'const void * __restrict__' but argument is of type 'int (*)(void)'
fptr.c:26: warning: ISO C forbids conversion of function pointer to object pointer type
$ ./fptr
Hello 42!
$

请注意:在某些系统上,从可写内存执行是不可能的,此代码将崩溃。它已经在运行于 x86_64 架构的 Linux 上使用 gcc 4.4.4 进行了测试。

最佳答案

您不能在 C 中执行此操作。即使您知道长度,函数的地址也很重要,因为函数调用和对特定类型数据的访问将使用程序计数器相对 寻址。因此,位于不同地址的函数副本将不会执行与原始函数相同的操作。当然还有很多其他问题。

关于c - 如何确定函数的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8269832/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com