在NASM中传播String的长度

时间:2015-12-01 17:52:46

标签: string assembly nasm

我试图检查程序参数中给出的sting的长度,作为更大程序的一部分。我需要将字符串长度的值放在一个名为n的变量中,我在BSS中保留了未初始化的值。我尝试了几种不同的方法,包括我现在正在尝试的方法,这是另一个答案。然而,当我尝试打印或使用这个小算法的结果时,它总是返回7.我相信我得到了我想要的地址而不是结果,但我不知道要改变什么。继承我的代码:

%include "asm_io.inc"
SECTION .data
    fmt1: db "%d",10,0
    argErrMsg: db "Needs 2 args",10,0
    argOkMsg : db "Arguments ok",10,0
    doneMsg: db "Program finished, now exiting",10,0
    strErrMsg: db "String must be between 1 and 20 charaters",10,0
    strOkMsg: db "String length ok",10,0
SECTION .bss
    X: resd 20
    i: resd 1
    n: resd 1
    k: resd 1
SECTION .text
    global asm_main
    extern printf
    extern strlen

asm_main:

    enter 0,0
    pusha

    CHECK_ARGS:
        cmp dword [ebp+8],2
        jne ERROR_ARGS
        je OK_ARGS

    ERROR_ARGS:
        push dword argErrMsg
        call printf
        add esp,8
        jmp EXIT
    OK_ARGS:
        push dword argOkMsg
        call printf
        add esp,8
        jmp CHECK_STRING
    CHECK_STRING:
        mov eax, dword[ebp+16]
        push eax        ;This is the code I tried using from another answer 
        mov ecx,0
        dec eax
        count:
            inc ecx
            inc eax
            cmp byte[eax],0
            jnz count
        dec ecx
        ret
        pop eax
        mov [n],ecx    ;Tried prining it here to see the result
        push dword [n]
        push dword fmt1
        call printf
        add esp,8
        cmp byte [n],1
        jl ERROR_STRING
        cmp byte [n],20
        jg ERROR_STRING

        jmp OK_STRING    ;The program always gets to here since [n] = 7?  
    ERROR_STRING:
        push dword strErrMsg
        call printf
        add esp,8
        jmp EXIT
    OK_STRING:
        push dword strOkMsg
        call printf
        add esp,8
        jmp EXIT
    EXIT:
        push dword doneMsg
        call printf
        popa
        leave
        ret

1 个答案:

答案 0 :(得分:2)

获得argv [1]的长度:

        mov     edi,[ebp+12]    ;edi = argv = &argv[0]
        mov     edi,[edi+4]     ;edi = argv[1]
        mov     ecx,0ffffh      ;scan for 0
        xor     eax,eax
        repne   scasb
        sub     ecx,0ffffh      ;ecx = -(length + 1)
        not     ecx             ;ecx = length

main应该在eax中返回0:

        popa
        xor     eax,eax
        leave
        ret