Как правильно сравнить две строки в ассемблере nasm с test или cmp (x64) - PullRequest
1 голос
/ 13 апреля 2020

Я пытаюсь выполнить простую проверку пароля в nasm, но моя программа никогда не переходит на correct_func, но пароль правильный. Я что-то не так делаю?

section .data
    msg1: db "Enter your password: ", 0
    len1 equ $-msg1
    correct: db "Correct!", 0x0a
    lenc equ $-correct
    wrong: db "Wrong!", 0x0a
    lenw equ $-wrong
    passwd: db "ASD123"
    input

section .text
global _start

correct_func:
    mov rax, 0x1
    mov rdi, 1
    mov rsi, correct
    mov rdx, lenc
    syscall
    mov rax, 60
    mov rdi, 0
    syscall
    ret

_start:
    mov rax, 0x1
    mov rdi, 1
    mov rsi, msg1
    mov rdx, len1
    syscall
    mov rax, 0x0
    mov rdi, 0
    mov rsi, input
    mov rdx, 6
    syscall
    mov rax, passwd
    mov rbx, input
    cmp rax, rbx
    je correct_func
    mov rax, 0x1
    mov rdi, 1
    mov rsi, wrong
    mov rdx, lenw
    syscall
    mov rax, 60
    mov rdi, 0
    syscall

1 Ответ

3 голосов
/ 13 апреля 2020

Чтобы сравнить две строки, сравните каждый символ одной строки с соответствующим символом другой. Если две строки имеют одинаковую длину и совпадают во всех своих символах, они равны. Я предполагаю, что вы проверили, что оба имеют одинаковую длину.

Вы можете сделать это с явным l oop:

        mov ecx, 0            ; index and loop counter
.loop:  mov al, [passwd+rcx]  ; load a character from passwd
        cmp al, [input+rcx]   ; is it equal to the same character in the input?
        jne .incorrect        ; if not, the password is incorrect
        inc ecx               ; advance index
        cmp ecx, 6            ; reached the end of the string?
        jle .loop             ; loop until we do
                              ; if this line is reached, the password was correct

В качестве альтернативы, вы можете использовать cmpsb инструкция:

        mov rsi, passwd       ; load the address of passwd
        mov rdi, input        ; load the address of input
        mov ecx, 6            ; load the string length
        repe cmpsb            ; compare the strings
        je correct_func       ; jump to correct_func if they are equal
                              ; if this line is reached, the password was wrong

Подробнее см. в справочном руководстве.

...