Linux 上的 C 内联汇编,将字符串从堆栈写入标准输出

标签 c linux string assembly inline-assembly

如何从堆栈中将字符串(例如“Hello”)写入标准输出?没有数据段,也就是说。

void main() {
    __asm__(
                "movl  $0x4, %eax   \n\t"
                "movl  $0x1, %ebx   \n\t"
            //   put "Hello" on the stack and load its address into %ecx
                "movl  $0x5, %edx   \n\t"
                "int   $0x80        \n\t"

                "movl  $0x1, %eax   \n\t"
                "movl  $0x0, %ebx   \n\t"
                "int   $0x80        \n\t"
             );
}

提前致谢

最佳答案

答案一:

int main()
{
    const char* string = "hello";  // string is not in a data segment, it's in the text segment
    fputs(string, stdout);
    return 0;
}

答案2:

int main()
{
    char[6] string = "hello";  // Space for string allocated on stack
    fputs(string, stdout);
    return 0;
}

对于 gcc,第二个答案似乎生成以下内容:

main:      
    leal    4(%esp), %ecx
    andl    $-16, %esp
    pushl   -4(%ecx)
    pushl   %ebp
    movl    %esp, %ebp
    pushl   %ecx
    subl    $36, %esp
    movl    $1819043176, -10(%ebp) ;<< hell
    movw    $111, -6(%ebp)         ;<< o\0
    movl    stdout, %eax
    movl    %eax, 4(%esp)
    leal    -10(%ebp), %eax
    movl    %eax, (%esp)
    call    fputs
    movl    $0, %eax
    addl    $36, %esp
    popl    %ecx
    popl    %ebp
    leal    -4(%ecx), %esp

这显然只使用堆栈。

关于Linux 上的 C 内联汇编,将字符串从堆栈写入标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3263555/

相关文章:

PHP上传问题

c# - 检查字符串是否仅包含有效的 ISO 8859-1 字符

c++ - 如何直接从 char* 数组创建 std::string 而无需复制?

c - 当我从 C 中的数组中获取十六进制值时,如何保持十六进制格式?

c - BlueZ 中的 mainloop_add_fd()

linux - Bash 脚本中有奇怪的特殊字符

`read()` 后面可以直接跟 `write()` 吗? `write()` 后面可以直接跟 `read()` 吗?

c++ - 'dxerr9.h' : No such file or directory

c - valgrind错误条件跳转

java - 检查字符串是否是有效的 JSON 字符串?