问题描述
我正在GNU/Linux上学习x86程序集,并且试图编写一个程序来从stdin读取用户输入并将其输出到stdout上.
I'm learning x86 assembly on GNU/Linux, and I'm trying to write a program that reads user input from stdin and prints it on stdout.
以下代码确实有效,但是如果用户输入的字符串的大小小于100个字节,它将打印额外的字符.
The following code does work, but it prints extra characters if the size of the user-entered string is less than 100 bytes.
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 ; \
如何可靠地计算用户输入的字符串的长度?
How can I reliably calculate the length of the user-entered string?
如何避免打印多余的字符?
How can I avoid printing extra characters?
推荐答案
str: db 100
是错误的.您分配了一个字节,其值为100.正确的方法是:str: times 100 db 0
分配100个字节,其值为0.
str: db 100
is wrong. You allocated one byte with the value 100. Correct is: str: times 100 db 0
to allocate 100 bytes with the value 0.
您有两个问题:
1)要获取输入的字节数,可以评估EAX
中读取功能的返回值(int 80h/fn 3).
1) To get the number of inputted bytes you can evaluate the return value of the read-function (int 80h / fn 3) in EAX
.
2)如果输入的字符多于允许的"字符,其余字符将存储在输入缓冲区中,必须将其清空.下面的示例是实现此目的的一种可能方法:
2) If you input more characters than "allowed" the rest is stored in the input buffer which you have to empty. A possible method to do this is in the following example:
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 ; \
这篇关于使用x86程序集(GNU/Linux)读取和打印用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!