strlen() implementation in NASM
08 Jan 2013Introduction
Seeing so many “Hello, world” concepts for getting up an running in Assembly has annoyed me a little bit. I see people using the $ - msg
macro to calculate the length of their string at assemble time. In today’s post, I’ll show you how to measure the length of your string at runtime so you’ll be able to provide the write syscall’s third parameter a little more flexibly.
The logic
The logic behind this procedure is dead-simple. Test the current byte for being null, if it is get out now if its not keep counting! Here’s how the code looks.
This is just straight-forward memory testing, no great advancements in computer science here! The function expects that the string that requires testing will be in the rdi
register. To actually use this function in your application though, you’ll need to transport the result (which sits in rax by the time the function has completed execution) into the register that write
expects its length parameter. Here’s how you use your new strlen function (in the Debian scenario).
So you can see that this is quite straight forward. We setup rdx before we setup the rest of the registers. We could have done this the other way around - to be on the safe side, I’ve done it this way as you never know what registers get mowed over in people’s functions. I tried to help this also in the _strlen
implementation by saving the only work register that I use rcx
. Anyway, that’s how you measure your string.
A more optimal way?
After completing this article, I’d thought about the “brute-forcish” way that I’d crunched out the numbers to derive a string’s length and thought to myself, what if I could just scan the string of bytes - find the null character and subtract this found index from the original starting point. Mathematically I would have calculated the distance in bytes between the start of the string and the NULL
character, ergo the string length. So, I’ve written a new string length implementation that does just this and here it is.
It may look longer than the first implementation however this second implementation uses SCASB which will be heaps more optimal than my hand-rolled loop.
Enjoy.