简体   繁体   English

汇编x86-调用C函数

[英]Assembly x86 - Calling C functions

I was wondering if it is possible to call printf for example without declaring the format array in the data segment. 我想知道是否可以在不声明数据段中的格式数组的情况下调用printf。 This question is regarding x86. 这个问题是关于x86的。

#include <stdio.h>

int main()
{
    __asm
    {
        push 1 ; number to print
        push 3710092110 ; format in ascii for %d\n
        call printf
        add esp, 8
    }

    return 0;
}

Ok so we need to push the address of the format instead of the format itself so something like this should be close enough right? 好的,我们需要推送格式的地址,而不是格式本身,因此类似这样的内容应该足够接近吧?

#include <stdio.h>

int main()
{
    __asm
    {
        push 3710092110 ; 3710092110 = format in ascii for %d\n
        push 1; argument to print
        lea edx, dword ptr[esp + 4]; get address of the format on stack
        push edx ; push the address of the format
        call printf
        add esp, 12
    }

    return 0;
}

Do you guys happen to have the time to demonstrate a working example? 你们碰巧有时间演示一个有效的例子吗? Can't find anything on the internet about it. 在互联网上找不到任何有关它的信息。

The format string is passed by pushing its address on the stack. 通过将其地址压入堆栈来传递格式字符串。 So you could put the string wherever you like, but still need to pass its address. 因此,您可以将字符串放在任意位置,但仍需要传递其地址。

Your second code snippet comes close but it still needs to use a different value for the contents of the format string %d\\n . 您的第二个代码段接近,但仍需要对格式字符串%d \\ n的内容使用其他值。

The characters involved translate to % =37, d =100, \\n =10 in decimal. 涉及的字符转换为 = 37, d = 100, \\ n = 10(十进制)。
But it is far easier to work with hexadecimal: % =25h, d =64h, \\n =0Ah Due to little endeanness we have to put the first character in the lowest byte of the dword to push on the stack. 但是使用十六进制要容易得多: = 25h, d = 64h, \\ n = 0Ah由于缺乏端正性,我们必须将第一个字符放在dword的最低字节中以压入堆栈。 We leave the highest byte zero to have the necesary null termination. 我们将最高字节保留为零以具有必要的null终止。

%d\n  -->  000A6425h

Your code: 您的代码:

#include <stdio.h>

int main()
{
    __asm
    {
        push 000A6425h ;= format in ascii for %d\n
        push 1; argument to print
        lea edx, dword ptr[esp + 4]; get address of the format on stack
        push edx ; push the address of the format
        call printf
        add esp, 12
    }

    return 0;
}

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

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