DEV Community

Gealber Morales
Gealber Morales

Posted on • Updated on • Originally published at gealber.com

Challenge RE #21

Challenge #21 description it's quite simple

This is easy. What does the following code do?

We can assume this will be easy.

Analysis

Here's the assembly code we need to analyze

f1:
        push    r12
        push    rbp
        mov     rbp, rdi
        push    rbx
        mov     rbx, rsi

        ;; strlen(rdi);
        call    strlen

        ;; strlen(rbx);
        mov     rdi, rbx
        mov     r12, rax
        call    strlen

        ;; size_1 -= size_2;
        sub     r12, rax

        mov     rsi, rbx
        lea     rdi, [rbp+0+r12]
        call    strcmp

        pop     rbx
        test    eax, eax
        pop     rbp
        sete    al
        pop     r12
        ret
Enter fullscreen mode Exit fullscreen mode

)
We have two calls to strlen and one to strcmp. With this in mind we can assume we receive two strings as arguments of our function.

Right after the calls to strlen we have the following instruction

sub r12, rax
Enter fullscreen mode Exit fullscreen mode

In r12 we stored the result of our first call to strlen, so with this instruction we are computing the difference in length of these two strings.
The following three instructions perform a comparison in size of strings rbx and [rbp+0+r12].

mov     rsi, rbx
lea     rdi, [rbp+0+r12]
call    strcmp
Enter fullscreen mode Exit fullscreen mode

In r12 we have the result of the difference, so if for str1 we have str1_size, and for str2 we have str2_size, then in r12 we have str1_size - str2_size. Hence these three instructions can be expressed in this way

size_t s1 = strlen(str1);
size_t s2 = strlen(str2);

strcmp((str1+(s1-s2)), str2);
Enter fullscreen mode Exit fullscreen mode

Our last step it's quite simple also, in case our comparison with strcmp was 0 we return 1, otherwise we return 0.

Formal description

The function takes two strings as arguments and return 1 if one string it's the suffix of the other, and 0 otherwise.

Conclusion

Coming from the frustration with challenge #19, making this one was quite easy.

Top comments (0)