How to write to stdout using assembly?

I'm having trouble trying to write the text "hello!". in "stdout". I wrote this code using the standard FreeBSD system call invocation convention (FreeBSD Developers' Handbook: 11.3.1) and my beginner build skills.

Here is the code (in & t format):

.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 FreeBSD 9 x86.

+5
source share
1 answer

One easy way to find out is to get the C compiler to create an assembler template for you. Let's start with the equivalent in C:

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

Then we create for us the assembly code for the assembly:

cc -S hello.c

The resulting assembly code should be ready for assembly (and link to the C library).

    .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

(), .size , .

0

All Articles