Strlen in assembly

I made my own strlen implementation in the assembly but did not return the correct value. It returns the length of the string + 4. Therefore. I don’t understand why .. And I hope one of you ...

Build Source:

section .text [GLOBAL stringlen:] ; C function stringlen: push ebp mov ebp, esp ; setup the stack frame mov ecx, [ebp+8] xor eax, eax ; loop counter startLoop: xor edx, edx mov edx, [ecx+eax] inc eax cmp edx, 0x0 ; null byte jne startLoop end: pop ebp ret 

And the main procedure:

 #include <stdio.h> extern int stringlen(char *); int main(void) { printf("%d", stringlen("h")); return 0; } 

thanks

+4
source share
6 answers

You do not get access to bytes (characters), but double words. Thus, your code does not look for a single trailing zero, it looks for 4 consecutive zeros. Note that it will not always return the correct +4 value, it depends on what the memory contains after your line.

To fix, you should use byte calls, for example, changing edx to dl .

+2
source

Thank you for your responses. In this case, working code for those who have the same problem as me.

 section .text [GLOBAL stringlen:] stringlen: push ebp mov ebp, esp mov edx, [ebp+8] ; the string xor eax, eax ; loop counter jmp if then: inc eax if: mov cl, [edx+eax] cmp cl, 0x0 jne then end: pop ebp ret 
+2
source

Not sure about four, but it seems obvious that it always returns the correct length + 1, since eax always increases, even if the first byte read from the string is zero.

+1
source

Change the line

 mov edx, [ecx+eax] 

to

 mov dl, byte [ecx+eax] 

and

  cmp edx, 0x0 ; null byte 

to

  cmp dl, 0x0 ; null byte 

Because you only have to compare bytes at a time. Below is the code. Your source code received an error message. For "h", it will return two h + null characters.

 section .text [GLOBAL stringlen:] ; C function stringlen: push ebp mov ebp, esp ; setup the stack frame mov ecx, [ebp+8] xor eax, eax ; loop counter startLoop: xor dx, dx mov dl, byte [ecx+eax] inc eax cmp dl, 0x0 ; null byte jne startLoop end: pop ebp ret 
+1
source

The easiest way is here (only ASCII null terminated string):

REPE SCAS m8

http://pdos.csail.mit.edu/6.828/2006/readings/i386/REP.htm

0
source

I think your inc should be after jne. I am not familiar with this assembly, so I really don't know.

-1
source

Source: https://habr.com/ru/post/1340310/


All Articles