Outputting variable values in x86 asm

…衆ロ難τιáo~ 提交于 2019-11-28 09:40:40

问题


I am writing a program in assembly and it isn't working, so I'd like to output variables in x86 functions to ensure that the values are what I expect them to be. Is there a simple way to do this, or is it very complex?

If it makes it simpler, the assembly functions are being used from C functions and are being compiled with gcc.


回答1:


It appears that your question is along the lines of "How can I print out variable values in x86 assembler". The x86 itself doesn't know how to do that, because it depends entirely on what output device you're using (and the specifics of the OS-provided interface to that output device).

One way of doing it is to use operating system syscalls, as you mentioned yourself in another answer. If you're on x86 Linux, then you can use the sys_write sys call to write a string to standard output, like this (GNU assembler syntax):

STR:
    .string "message from assembler\n"

.globl asmfunc
    .type asmfunc, @function

asmfunc:
    movl $4, %eax   # sys_write
    movl $1, %ebx   # stdout
    leal STR, %ecx  #
    movl $23, %edx  # length
    int $0x80       # syscall

    ret

However, if you want to print numeric values, then the most flexible method will be to use the printf() function from the C standard library (you mention that you're calling your assembler rountines from C, so you are probably linking to the standard library anyway). This is an example:

int_format:
    .string "%d\n"

.globl asmfunc2
    .type asmfunc2, @function

asmfunc2:
    movl $123456, %eax

    # print content of %eax as decimal integer
    pusha           # save all registers
    pushl %eax
    pushl $int_format
    call printf
    add $8, %esp    # remove arguments from stack
    popa            # restore saved registers

    ret

Two things to note:

  • You need to save and restore registers, because they get clobbered by the call; and
  • When you call a function, the arguments are pushed in right-to-left order.


来源:https://stackoverflow.com/questions/2504974/outputting-variable-values-in-x86-asm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!