String Length Function in NASM

In certain situations when I want to print some string to stdout we need the length for the write syscall in linux. So we can’t always depend on the $-string macro, which is valid for a defined string.

We use the REPNE (REPeat while Not Equal) instruction which will loop as long as CX != 0. Along with REPNE we use SCASB (scan byte string). It compares the content of the accumulator (AL, AX, or EAX) against the current value pointed at by ES:[EDI]. In the end we calculate the difference between offsets of the scanned string (EDI) and the original string (EBX) to find the length.

_strlen:
push ebx
push ecx
mov ebx, edi
xor al, al
mov ecx, 0xffffffff
repne scasb ; REPeat while Not Equal [edi] != al
sub edi, ebx ; length = offset of (edi - ebx)
mov eax, edi
pop ebx
pop ecx
ret


References:
REPNE
SCASB

Advertisements

2 thoughts on “String Length Function in NASM

    • Thanks 🙂 That is the normal way in assembly and it contains a null byte, but I have tried to save lines plus no null bytes 😉
      \x53\x51\x89\xfb\x30\xc0\xb9\xff\xff\xff\xff\xf2\xae\x29\xdf\x89\xf8\x5b\x59\xc3

      Furthermore you can make it short to 16 bytes if you remove my registers saving it’s state.
      push,pop ebx
      push,pop ecx
      \x89\xfb\x30\xc0\xb9\xff\xff\xff\xff\xf2\xae\x29\xdf\x89\xf8\xc3

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s