簡體   English   中英

如何使用匯編語言從鍵盤讀取輸入字符串

[英]How to read input string from keyboard using assembly language

我正在嘗試編寫一個簡單的程序,該程序從鍵盤獲取字符串,然后將其打印到屏幕上。 到目前為止,我無法讓它發揮作用。

這是代碼:

    .section .rodata
output: .string "you entered %s\n"
input:  .string "%s"

    .text
.globl  main
    .type   main, @function

main:
    pushl   %ebp
    movl    %esp, %ebp

    subl    $100, %esp
    pushl   $input
    call    scanf

    movl    %ebp, %esp
    subl    $100, %esp
    pushl   $output
    call    printf

    xorl    %eax, %eax
    movl    %ebp, %esp
    popl    %ebp
    ret

當我執行它時,輸出是you entered (null)為任何給定輸入you entered (null) 當我將subl $100, %esp命令( call print之前的subl $104, %esp )的偏移量設置為subl $104, %esp我讓you entered %s ,當偏移量設置為 108 時,我讓you entered *gibberish*

我覺得這是一個我需要猜測scanf將字符串保存在堆棧中的位置的游戲(為什么不是它應該在的位置?)。

我正在使用 IA32 指令集。

任何幫助將不勝感激。

程序中基本上存在3個問題:

subl    $100, %esp
pushl   $input
# Error 1:
# As Frank Kotler already wrote at this point
# only $input is stored on the stack; however
# the address of the buffer must also be on
# the stack (see Frank Kotler's comment)
call    scanf

movl    %ebp, %esp
# Error 2:
# Now the buffer is below ESP.
# Because interrupts use the kernel stack they
# will not overwrite the memory below ESP.
# However signals will destroy the memory below
# ESP!!
#
# Instead of the lines:
#   movl    %ebp, %esp
#   subl    $100, %esp
#
# You should use something like this:
#   add $8, %esp
# or:
#   lea -100(%ebp), %esp
#

subl    $100, %esp
# Error 3:
# As for "scanf" the second argument
# is missing on the stack
pushl   $output
call    printf
[org 0x0100]
jmp start
;=======Data===================================
s1: db 'Enter String: $'
s2: db 'Reversed String:$'
linefeed: db 10, '$'
;=======Read string and store into stack=======
start: mov dx, s1
mov ah, 09h
int 21h
mov dx, linefeed
mov ah, 09h
int 21h
mov si,0
mov bx,0
again: mov ah, 01h
int 21h
cmp al,byte 0dh
je endread
Page 8 of 10
mov bl,al
push bx
inc si
cmp si,15
je endread
jmp again
endread: Push si
;=======Read from stack and print to screen=====
mov dx, linefeed
mov ah, 09h
int 21h
mov dx, s2
mov ah, 09h
int 21h
mov dx, linefeed
mov ah, 09h
int 21h
pop si
r1: pop bx
mov dl,bl
mov ah, 02h
int 21h
dec si
cmp si,0
jne r1
mov dx, linefeed
mov ah, 09h
int 21h
mov ax, 0x4c00 ;terminate program
int 21h

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM