NASM-如何从终端解决输入读取问题


section .data
yourinputis db "your input is =",0
len equ $ - yourinputis
section .bss
msginput    resb    10
section .text
global _start

_start:
mov eax,3 ;read syscall
mov ebx,2
mov ecx,msginput
mov edx,9 ; I don't know that is correct?
int 80h
mov eax,4 ;write syscall
mov ebx,1
mov ecx,yourinputis
mov edx,len
int 80h
mov eax,4 ;write syscall
mov ebx,1
mov ecx,msginput
mov edx,10
int 80h

exit:
mov eax,1 ;exit syscall
xor ebx,ebx
int 80h

这个代码运行得很好。但它是如此可怕的bug(对我来说:((。如果我输入的输入长于10->

$./mycode
012345678rm mycode
your input is 012345678$rm mycode
$

这种情况正在发生。当然;分枝杆菌";目前不存在。

我该怎么办?

编辑:输入的输入正确打印在屏幕上。但如果你输入一个长输入,它会在第9个字符之后移动到shell并运行它

在该示例中;rm-mycode";在";012345678";正在shell中运行。

如果输入的字符超过9个,它们将留在终端驱动程序的输入缓冲区中。当程序退出时,shell从终端读取并尝试将该行的其余部分作为命令执行。

为了防止这种情况,您的程序应该保持循环读取,直到它得到一个换行符。

您可以逐个读取字符,直到到达0x0a。类似于:

_read:
mov esi, msginput
_loop:
mov eax,3 ;read syscall
mov ebx,0
mov ecx, esi
mov edx,1 ; I don't know that is correct?
int 80h
cmp byte[esi], 0x0a
je end
inc esi
jmp _loop
end:
ret

您将不得不增加msginputtho的大小。

重要提示:请注意,这不是有效的方法(请参阅评论(,这里只是作为上面答案的一个例子。

最新更新