[英]Compare two strings in FASM
关于FASM,我是新手,而对于ASM来说,我还是一个新手,但是我想比较存储在“变量”中的两个字符串: user_input
和exit_cmd
:
目前,它可以正常组装,但是当我在提示符下输入任何内容时,它就会崩溃。 是的,我的代码很乱,我要完成的任务似乎无法达到我所知道的ASM的水平,但是我已经用其他语言完成过,所以我正在ASM中进行尝试。
您可以看到我使用宏CompareStrings
(来源不明;不是我的)将字符串匹配的EAX
设置为1,但是当我使用CMP
将EAX
与1进行比较,然后将JE
与标签进行比较时,它拒绝工作。 有什么帮助吗?
这是越野车代码:
format PE console
;win32a.inc, win32w.inc, win64a.inc and win64w.inc
include 'win32w.inc'
entry main
; Define macros for things like printing strings ('print') and pausing (well, waiting for the user to press enter ('pause'))
macro print str {
push str
call [printf]
push 0
}
macro pause {
invoke system,'pause>nul'
}
macro getinput prompt {
print prompt
invoke gets,user_input
}
macro CompareStrings str1, str2
{
lea edi, [str2] ; edi -> address of string2
dec edi ; edi = edi - 1
.lab1: ; loop through all chars and compare each of them
inc edi ; ds:di --> next character in string2
lodsb ; al = next char from string1. loadsb increments si automatically
cmp [edi], al ; compare characters
jne .notfound ; jump out of the loop if they're unequal
cmp al, 0 ; chars are equal, but make sure we compared the entire string
jne .lab1 ; if not, continue the loop
mov eax, 1 ; else: strings are equal -> eax = 1
ret ; return; result: strings are equal
.notfound: ; chars are not equal
mov eax, 0 ; unequal -> eax = 0
ret ; return; result: strings are not equal
}
section '.text' code readable executable
main:
print header_msg
jmp input_loop
input_loop:
getinput cmd_prompt
print newline
CompareStrings user_input,cmd_exit
cmp eax, 1
je exit_cmd
jne input_loop
exit_cmd:
print header_msg
ret
section '.data' data readable writable
header_msg db "Basic Programming Language in ASM | Version 0.0.1",13,10,0
cmd_prompt db "> ",0
newline db "",13,10,0
user_input db "",0dh,0ah,0
chrarr db '%s',0dh,0ah,0
cmd_exit db 'exit',0
section '.idata' import data readable
library msvcrt,"msvcrt.dll"
import msvcrt,\
puts,"puts",\
getchar,"getchar",\
exit,"exit",\
printf,"printf",\
scanf,"scanf",\
system,"system",\
gets,"gets"
这个程序有很多问题,它崩溃并不奇怪。
您没有为输入的字符串分配足够的空间。 使用rb
指令分配足够大的空间来处理您的输入:
user_input rb 1024
将其放在数据部分的末尾,以免在结果可执行文件中发生。
我不知道如何使用CPP库,但是可能调用约定不是STDCALL,参数也不完全是这些。 例如gets
可能需要某种CPP自扩展字符串,而不是简单的缓冲区地址。 否则,很容易使缓冲区溢出,并且无法检查此类问题。
因此,最好使用普通的WinAPI-ReadFile和WriteFile来读取和写入控制台。
在上述背景下,这很挑剔,但无论如何:
push str
call [printf]
push 0
此push 0
在这里看起来很奇怪。 应该怎么办?
你的风格。 尝试不使用“ {”和“}”字符来实现此程序。 这将帮助您更好地理解汇编语言。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.