Question

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.

Was it helpful?

Solution

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top