在x86 asm中输出变量值 [英] Outputting variable values in x86 asm
问题描述
我正在用汇编语言编写程序,但该程序无法正常工作,因此我想在x86函数中输出变量,以确保值符合我的期望.有没有简单的方法可以做到这一点,或者它很复杂?
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?
如果使它更简单,则可以从C函数使用汇编函数,并使用gcc进行编译.
If it makes it simpler, the assembly functions are being used from C functions and are being compiled with gcc.
推荐答案
您的问题似乎与如何在x86汇编器中打印出变量值"类似. x86本身不知道如何执行此操作,因为它完全取决于您所使用的输出设备(以及该输出设备由OS提供的接口的详细信息).
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).
一种实现方法是使用操作系统syscall,就像您在另一个答案中提到的那样.如果您使用的是x86 Linux,则可以使用sys_write
sys调用将字符串写入标准输出,如下所示(GNU汇编器语法):
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
但是,如果要打印数字值,那么最灵活的方法是使用C标准库中的printf()
函数(您提到要从C调用汇编程序常规程序,因此您可能是无论如何都链接到标准库).这是一个例子:
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
需要注意的两件事:
- 您需要保存和恢复寄存器,因为调用会破坏寄存器.和
- 调用函数时,参数以从右到左的顺序推送.
这篇关于在x86 asm中输出变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!