我有问题。我尝试在汇编中构建一个循环(nasm,linux)。循环应该“计算”数字 0 - 10,但它不起作用,我不知道为什么。这是一个代码:
section .text
global _start
_start:
xor esi,esi
_ccout:
cmp esi,10
jnl _end
inc esi
mov eax,4
mov ebx,1
mov ecx,esi
mov edx,2
int 80h
jmp _ccout
_end:
mov eax,1
int 80h
section .data
最佳答案
嗯,循环正在工作,但您没有正确使用系统调用。这里涉及到一些神奇的数字,所以让我们首先解决它:
- 4 是
write
的系统调用号 - 1 是标准输出的文件描述符
到目前为止,一切都很好。 write
需要一个文件描述符、缓冲区的地址以及该缓冲区的长度或应该写入文件描述符的缓冲区的部分。所以,它看起来应该类似于
mov eax,4 ; write syscall
mov ebx,1 ; stdout
mov ecx,somewhere_in_memory ; buffer
mov edx,1 ; one byte at a time
将其与您的代码进行比较:
mov eax,4
mov ebx,1
mov ecx,esi ; <-- particularly here
mov edx,2
int 80h
您在那里所做的(除了传递错误的长度之外)是将 esi
的内容传递给 write
作为内存地址,从中读取应该写入标准输出的内容。纯属偶然,这不会崩溃,但内存中的该位置没有有用的数据。
为了解决这个问题,您需要在内存中找到一个位置来放置它。此外,由于 write
适用于字符,而不是数字,因此您必须通过添加“0”(ASCII 中的 48)来自行格式化。总而言之,它可能看起来像这样:
section .data
text db 0 ; text is a byte in memory
section .text
global _start
_start:
xor esi,esi
_ccout:
cmp esi,10
jnl _end
inc esi
lea eax,['0'+esi] ; print '0' + esi. lea == load effective address
mov [text],al ; is useful here even though we're not really working on addresses
mov eax,4 ; write
mov ebx,1 ; to fd 1 (stdout)
mov ecx,text ; from address text
mov edx,1 ; 1 byte
int 80h
jmp _ccout
_end:
mov [text],byte 10 ; 10 == newline
mov eax,4 ; write that
mov ebx,1 ; like before.
mov ecx,text
mov edx,1
int 80h
mov eax,1
mov ebx,0
int 80h
输出123456789:
可能不完全是您想要的,但您应该能够从这里获取它。为读者做练习等等。
关于linux - 汇编中的循环不起作用,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27204776/