Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understand cmpb and loops in assembly language

Tags:

assembly

I have a function string_length that has the following assembly code

0x08048e90 <+0>:     push   %ebp
0x08048e91 <+1>:     mov    %esp,%ebp
0x08048e93 <+3>:     mov    0x8(%ebp),%edx     // assign whatever I declared into edx
0x08048e96 <+6>:     mov    $0x0,%eax          // assign eax = 0
0x08048e9b <+11>:    cmpb   $0x0,(%edx)        // compare edx to byte of 0 (null..?)
0x08048e9e <+14>:    je     0x8048ea9 <string_length+25>   // if equal, jump to +25
0x08048ea0 <+16>:    add    $0x1,%eax          // else, add 1 to eax
0x08048ea3 <+19>:    cmpb   $0x0,(%edx,%eax,1) // compare byte 1*eax+edx with 0, 
0x08048ea7 <+23>:    jne    0x8048ea0 <string_length+16>   // if not equal, back to +16
0x08048ea9 <+25>:    pop    %ebp               // pop ebp
0x08048eaa <+26>:    ret

Since the function name is string_length, I am assuming it will return how many characters is in the string.

what I am confused about is the

cmpb   $0x0,(%edx)

is this comparing whatever is pointed to edx to the byte of 0, and 0 in ASCII is null..?

and

cmpb   $0x0,(%edx,%eax,1)

is comparing, in bytes, 1*eax+edx. If edx is a string, does that mean edx will first be converted its ascii value and then perform the calculation?

like image 414
user3277633 Avatar asked Apr 02 '14 03:04

user3277633


2 Answers

This:

cmpb   $0x0,(%edx)

takes a byte that EDX points to (i. e. contains the address of) and compares it to zero. This:

cmpb   $0x0,(%edx,%eax,1)

takes a byte that EDX+EAX points to and compares it to zero. EDX serves as the string base pointer, EAX is the index. Scale is 1 because we're working with bytes. Think of the whole loop this way: for(eax=0; edx[eax] != 0; eax++).

like image 191
Seva Alekseyev Avatar answered Oct 11 '22 13:10

Seva Alekseyev


The equivalent C code would be something like this:

int string_length(const char *edx)
{
    int eax = 0;
    while (edx[eax] != NULL) eax++;
    return eax;
}
like image 34
Amro Avatar answered Oct 11 '22 12:10

Amro