Vit*_*meo 4 linux x86 assembly nasm
我正在 GNU/Linux 上学习 x86 汇编,并且正在尝试编写一个程序,从 stdin 读取用户输入并将其打印在 stdout 上。
以下代码确实有效,但如果用户输入的字符串的大小小于 100 个字节,它会打印额外的字符。
section .data
str: db 100 ; Allocate buffer of 100 bytes
section .bss
section .text
global _start
_start:
mov eax, 3 ; Read user input into str
mov ebx, 0 ; |
mov ecx, str ; | <- destination
mov edx, 100 ; | <- length
int 80h ; \
mov eax, 4 ; Print 100 bytes starting from str
mov ebx, 1 ; |
mov ecx, str ; | <- source
mov edx, 100 ; | <- length
int 80h ; \
mov eax, 1 ; Return
mov ebx, 0 ; | <- return code
int 80h ; \
Run Code Online (Sandbox Code Playgroud)
如何可靠地计算用户输入的字符串的长度?
如何避免打印多余的字符?
str: db 100是错的。您分配了值为 100 的1 个str: times 100 db 0字节。正确的做法是:分配值为 0 的 100 个字节。
你有两个问题:
1) 要获取输入的字节数,您可以计算 中读取函数 (int 80h / fn 3) 的返回值EAX。
2)如果您输入的字符多于“允许”,则其余字符将存储在您必须清空的输入缓冲区中。执行此操作的一种可能方法如下例所示:
global _start
section .data
str: times 100 db 0 ; Allocate buffer of 100 bytes
lf: db 10 ; LF for full str-buffer
section .bss
e1_len resd 1
dummy resd 1
section .text
_start:
mov eax, 3 ; Read user input into str
mov ebx, 0 ; |
mov ecx, str ; | <- destination
mov edx, 100 ; | <- length
int 80h ; \
mov [e1_len],eax ; Store number of inputted bytes
cmp eax, edx ; all bytes read?
jb .2 ; yes: ok
mov bl,[ecx+eax-1] ; BL = last byte in buffer
cmp bl,10 ; LF in buffer?
je .2 ; yes: ok
inc DWORD [e1_len] ; no: length++ (include 'lf')
.1: ; Loop
mov eax,3 ; SYS_READ
mov ebx, 0 ; EBX=0: STDIN
mov ecx, dummy ; pointer to a temporary buffer
mov edx, 1 ; read one byte
int 0x80 ; syscall
test eax, eax ; EOF?
jz .2 ; yes: ok
mov al,[dummy] ; AL = character
cmp al, 10 ; character = LF ?
jne .1 ; no -> next character
.2: ; end of loop
mov eax, 4 ; Print 100 bytes starting from str
mov ebx, 1 ; |
mov ecx, str ; | <- source
mov edx, [e1_len] ; | <- length
int 80h ; \
mov eax, 1 ; Return
mov ebx, 0 ; | <- return code
int 80h ; \
Run Code Online (Sandbox Code Playgroud)