issue in rewriting strlen from C to Assembly

2k Views Asked by At

please could you help me? I have to rewrite strlen function from C to Assembly language. Iput string is ended with "0h". Output length is without char "0". Input is alway ended with "0h" I have something like that but it doesnt work:

[segment .data use32] 

; ******************************************************************

str:          resb 50
str1:         resb 50
str2:         resb 50
aTmpWord:     dw 0   
aTmpDWord:    dd 0  
strlen:
push EBP
mov EBP, ESP
mov AL, 0h
mov EDI, dword [EBP + 8]
mov EBX, 0

vypocet_str:
cld
repne scasb
je koniec_str
inc EBX
mov EDI, [EDI + EBX]
jmp vypocet_str

koniec_str:
mov EAX, EBX
mov ESP, EBP 
pop EBP
ret
;************
prologue
push dword [str]
call strlen
call WriteNewLine
call WriteInt32
epilogue
1

There are 1 best solutions below

0
On BEST ANSWER

There are several mistakes in your code

1) strlen is officially declared as size_t strlen(const char *s);. Argument is a pointer to a string. With push dword [str] you don't pass a pointer, but the first 4 bytes of the string. Change it to push str. NASM (unlike MASM) calculates then the address of str.

2) The cdecl calling conventions determines that arguments are passed on the stack and the caller must clear the stack. You correctly pushed the argument but don't clear the stack. Add a add esp, 4 after call strlen.

3) repne needs an initialization of ECX. This is the maximal count of the repetitions.

4) repne is the instruction for a loop. You don't need an extra loop (jmp vypocet_str). It repeats the following instruction while ECX>0 and the instruction don't tell an "equal" (zero flag set). So ECX can be used to determine the counts of the repne-run - with a little adjust.

TL;DR: here is your homework in a beautiful form:

%include 'rw32.inc'     ; http://www.fit.vutbr.cz/~iklubal/IAS/

[segment .data use32]

    str: db "hello world", 0

[segment .code use32]

    strlen:
        push ebp
        mov ebp, esp
        mov al, 0
        mov edi, dword [EBP + 8]
        mov ecx, -1
        repne scasb
        neg ecx
        sub ecx, 2
        mov eax, ecx
        mov esp, ebp
        pop ebp
        ret

    prologue
    push str
    call strlen
    add esp, 4
    call WriteNewLine
    call WriteInt32
    epilogue