汇编:从标准input读取整数,增加它并打印到标准输出

我为IA32编写了下面的程序集脚本。 它应该从标准input读取一个数字,增加它并打印到标准输出,但它不像预期的那样,它不会打印任何东西(也许从标准input读取不会终止或打印什么是错误的?)

.section .text .globl _start _start: movl $3, %eax # use syscall 3 (read) to read from stdin movl $0, %ebx # reads from stdin (FD 0) movl %edi, %ecx # store input in register %edi movl $4, %edx # read one byte int $0x80 # invoke system call to read from stdin incl %edi # increment the value we got from stdin movl $4, %eax # use syscall 4 (write) to print to screen movl $1, %ebx # print to stdout (FD 1) movl %edi, %ecx # pointer to text to write out movl $4, %edx # length of text to write out (1 byte) int $0x80 # invoke system call to write to stdout movl $1, %eax # use syscall 1 (exit) to exit movl $0, %ebx # error code = 0 int $0x80 # invoke system call 

你看到错误吗? 对于任何帮助我提前感谢你,

一切顺利,西蒙

 movl %edi, %ecx # store input in register %edi movl $4, %edx # read one byte 

这一部分都是错误的。 您不能将读取的结果存储在寄存器中。 实际上做的是将结果存储在%edi所包含的地址中,因为您没有设置它,所以可能是您没有任何业务存储的地方。 你首先需要腾出空间存储字符串。 你也读了四个字节,而不是一个。

我会用这样的东西取代

 subl $4, %esp movl %esp, %ecx movl $4, %edx 

这将为堆栈中的4个字节腾出空间,然后使用堆栈的顶部作为地址来存储字符串。 您还必须修改写入系统调用的参数才能使用此地址。

另一个你必须要处理的问题是,stdin和stdout通常处理文本,所以你正在阅读的内容可能是一个字符串,而不是一个数字,要用它作为一个数字,你必须将其转换然后在写出之前将其转换回来。