简体   繁体   English

执行void(char *)函数作为void(void)

[英]Executing void(char*) function as a void(void)

void print( char * str ){ printf("%s",str); }

void some_function(){
    ... Loads a file into `char * buffer` ...
    ... Stores the function print before `buffer` address ...
    ((void(*)(void))buffer();
}

In the file, there is a "Hello World" in it, and some unreadable characters. 在文件中,有一个“Hello World”,还有一些不可读的字符。 Executing the buffer will print "Hello World". 执行缓冲区将打印“Hello World”。

I know you can execute a pointer like this: 我知道你可以执行这样的指针:

void (*foo)(int) = &bar; // such that void bar(int)
(*foo)(123);

But executing void(int) function as a void(void) function with its function and parameters in memory is new to me. 但是执行void(int)函数作为void(void)函数及其函数和参数在内存中对我来说是新的。

Is there a standard of how a function look like in memory (like a string is terminated by a null character) such that you can execute it in this way? 函数在内存中的外观是否有标准(如字符串由空字符终止),以便您可以以这种方式执行它?

But executing void(int) function as a void(void) function with its function and parameters in memory is new to me. 但是执行void(int)函数作为void(void)函数及其函数和参数在内存中对我来说是新的。

Good. 好。 It's undefined behavior and you should never do it. 这是未定义的行为,你永远不应该这样做。 It might happen to work on some implementation, but there's no guaranteed result. 它可能恰好适用于某些实现,但没有保证结果。

Is there a standard of how a function look like in memory (like a string is terminated by a null character) such that you can execute it in this way? 函数在内存中的外观是否有标准(如字符串由空字符终止),以便您可以以这种方式执行它?

No, there isn't. 不,没有。 More relevantly, there is no standard for how arguments are passed to functions -- it's up to the implementation, and there is no requirement that it be implemented in such a way that functions with different types are compatible. 更相关的是,没有关于如何将参数传递给函数的标准 - 它取决于实现,并且不要求以不同类型的函数兼容的方式实现它。

But in this case, the programmer is taking advantage of knowledge of what a function looks like in memory, and has prepared the file in such a way that it does the right thing when loaded into memory and run in this particular implementation. 但在这种情况下,程序员正在利用内存中函数的知识,并以这样的方式准备文件,使其在加载到内存并在此特定实现中运行时做正确的事情。 This is, after all, what loaders do ... they read programs from files into memory and then execute them. 毕竟,这是加载器所做的......他们将文件中的程序读入内存然后执行它们。 This method is also used by exploits that take advantage of bugs in programs to load nefarious code into the program's memory and get the program to execute it. 利用程序中的错误将恶意代码加载到程序的内存中并使程序执行它的漏洞利用此方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM