汇编,寄存和返回值-m32 / linux

时间:2013-05-04 16:23:51

标签: assembly x86

我试图在汇编中制作一些简单的代码,这样我就可以更容易理解了。首先,我想创建一个带参数的函数。

我想在参数中添加一个值,例如字母' A'(ascii中的值为65)。     我希望函数返回A,但由于eax保存4个字节,而且这个字母只需要一个字节,我试图使用EAX寄存器的AL部分。

这里的问题是当我使用它时这个功能不起作用。我得到四个奇怪的字符作为返回值。谁知道为什么?

这就是我的代码的样子:

        .globl  letterprinter
# Name:             letterprinter
# Synopsis:         prints the character 'A' (or at least, it is supposed to)
# C-signature:      int letterprinter(unsigned char *res);
# Registers:        %EDX: for the argument that is supposed to get the value
#                   %EAX: for the return value(s)
#



letterprinter:                      # letterprinter

    pushl       %ebp                # start of
    movl        %esp, %ebp          # function

    movl        8(%ebp), %edx       # first argument

    movl        $65, %dl            # the value 'A' in lowest part of edx, dl

    movb        (%dl), %al          # moves it to the return register eax
    jmp     exit                    # ending function

exit:

    popl        %ebp                # popping - standard end of a function
                                    # 0-byte ? should there be one?
    ret                             # return

1 个答案:

答案 0 :(得分:0)

                    .globl  char

# Name:         char
# Synopsis:         A simplified sprintf
# C-signature:      int sprinter(unsigned char *res, unsigned char);
# Registers:        %EDX: first argument
#               %EBX: second argument
#



char:                   # char

    pushl       %ebp            # start of
    movl        %esp, %ebp      # function

    movl        8(%ebp), %edx           # first argument
    movl        12(%ebp), %eax          # second argument


add_res:
    movb        %al, (%edx)     # eax low gets the val at edx
    movb        $65, (%edx)     # puts A to the string
    jmp     exit            # jump to exit  

exit:

    popl        %ebp            # popping standard end of function
    movb        $0,1(%edx)      # adds the zero-byte at end                     
    ret                 # return