简体   繁体   English

如何使用汇编写入stdout?

[英]How write to stdout using assembly?

I'm having troubles trying to write the text "hi!" 我在尝试写文字“嗨!”时遇到了麻烦。 in the 'stdout'. 在'stdout'。 I wrote this code using the default calling convention of system calls for Freebsd (FreeBSD Developers' Handbook: 11.3.1) and my newbie assembly skills. 我使用Freebsd的系统调用的默认调用约定(FreeBSD Developers'Handbook:11.3.1)和我的新手组装技巧编写了这段代码。

Here is the code(at&t format): 这是代码(at&t格式):

.data
        str:
        .ascii "hi!"

.text

.globl main

main:
        pushl $0x3      # size
        pushl $str      # *buf
        pushl $0x1      # fd
        movl $0x4,%eax  # write
        int $0x80

        movl $0x1,%eax
        movl $0x0,%ebx
        int $0x80

The system is a FreeBSD 9 x86. 该系统是FreeBSD 9 x86。

One of the simples ways to learn this is to have the C compiler produce an assembler template for you. 学习此方法的一种简单方法是让C编译器为您生成汇编程序模板。 We start off with the equivalent in C: 我们从C中的等价物开始:

main()
{
        write(1, "hi!\n", 4);
        return 0;
}

Then we have the compiler create assembly code for us: 然后我们让编译器为我们创建汇编代码:

cc -S hello.c

The resulting assembly code should be ready to assemble (and link with the C library). 生成的汇编代码应该可以组装(并与C库链接)。

    .file   "hello.c"
    .section    .rodata
.LC0:
    .string "hi!\n"
    .text
    .p2align 4,,15
.globl main
    .type   main, @function
main:
.LFB2:
    pushq   %rbp
.LCFI0:
    movq    %rsp, %rbp
.LCFI1:
    movl    $4, %edx
    movl    $.LC0, %esi
    movl    $1, %edi
    movl    $0, %eax
    call    write
    movl    $0, %eax
    leave
    ret
.LFE2:
    .size   main, .-main
    .section    .eh_frame,"a",@progbits
.Lframe1:
    .long   .LECIE1-.LSCIE1
.LSCIE1:
    .long   0x0
    .byte   0x1
    .string "zR"
    .uleb128 0x1
    .sleb128 -8
    .byte   0x10
    .uleb128 0x1
    .byte   0x3
    .byte   0xc
    .uleb128 0x7
    .uleb128 0x8
    .byte   0x90
    .uleb128 0x1
    .align 8
.LECIE1:
.LSFDE1:
    .long   .LEFDE1-.LASFDE1
.LASFDE1:
    .long   .LASFDE1-.Lframe1
    .long   .LFB2
    .long   .LFE2-.LFB2
    .uleb128 0x0
    .byte   0x4
    .long   .LCFI0-.LFB2
    .byte   0xe
    .uleb128 0x10
    .byte   0x86
    .uleb128 0x2
    .byte   0x4
    .long   .LCFI1-.LCFI0
    .byte   0xd
    .uleb128 0x6
    .align 8
.LEFDE1:
    .ident  "GCC: (GNU) 4.2.1 20070831 patched [FreeBSD]"
    .section    .note.GNU-stack,"",@progbits

It's not immediately clear (to me) how much of the trailing stuff beyond the .size directive you really need, but this should have you on your way. 对我来说,除了你真正需要的.size指令之外还有多少尾随的东西并不是很清楚,但这应该让你顺利。

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

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