Back Original

A good strlen reads out of bounds

A good strlen reads out of bounds

A simple strlen

This is a strlen that counts bytes from s, one at a time, until hitting a zero byte:

size_t len(char const *s) {
    size_t result = 0;

    while (true) {
        if (!s[result]) {
            return result;
        } else {
            result++;
        }
    }
}
    

I tested this strlen against glibc's on a variety of string lengths, and this strlen (compiled with clang 23) is ~40x slower than glibc's strlen in the worst testcase.

We can do a lot better, if we're willing to go out of bounds. Here's a version that reads 2 bytes at a time:

static inline bool contains_zero_in_first_2(char const *p) {
    // Compiler may optimize this into a single 2-byte read, if it wants
    auto result = false;
    for (size_t i = 0; i < 2; i++) {
        result |= !(p[i]);
    }
    return result;
}

size_t len(char const *const s) {
    size_t result = 0;

    while (true) {
        if (contains_zero_in_first_2(s + result)) {
            return result + (s[result] != 0);
        } else {
            result += 2;
        }
    }
}
    
This strlen is way faster; only ~17x slower than glibc's on the worst test. Unfortunately, when s's length is even, this strlen reads one byte beyond the end of the string. This could be bad: if that one-byte overread crosses a page boundary into a page that doesn't have the read permission (or isn't mapped). We can fix this up by adding a special case: when s is an odd address, process its first byte individually. After that, we can confidently proceed 2 bytes at a time without crossing a page boundary, because the page size is divisible by 2. Here's what that would look like:
size_t len(char const *const s) {
    size_t result = 0;

    if ((uintptr_t)s % 2) {
        // s is odd
        if (*s) {
            result++;
        } else {
            return result;
        }
    }

    while (true) {
        if (contains_zero_in_first_2(s + result)) {
            return result + (s[result] != 0);
        } else {
            result += 2;
        }
    }
}
    
Note that we're still reading the string one byte out of bounds! It's just that we don't care so much about this, because we know that the OOB read won't cause a crash on normal machines (idc about MTE or CHERI).

Scaling to 32 bytes at a time

If we scale this approach up a little bit, it might look like this:

constexpr size_t N = 32;

static inline bool contains_zero_in_first_n(char const *p) {
    // No early return because this can't be vectorized with an early return.
    auto result = false;
    for (typeof_unqual(N) i = 0; i < N; i++) {
        result |= !(p[i]);
    }
    return result;
}

static inline bool is_aligned(void const *p) {
    return !((uintptr_t)p % N);
}

size_t len(char const *s) {
    size_t result = 0;

    // Count bytes from s until s is aligned
    // Needed so that intentionally OOB reads don't cross a page boundary
    while (!is_aligned(s + result)) {
        if (!s[result]) {
            return result;
        }
        result++;
    }

    while (true) {
        if (contains_zero_in_first_n(s + result)) {
            // Hit a zero.
            // Count remaining bytes and return.
            // I'm doing this with a for loop to help the compiler unroll
            for (typeof_unqual(N) i = 0; i < N; i++) {
                if (!s[result + i]) {
                    return result + i;
                }
            }
            unreachable();
        } else {
            // No zero.
            result += N;
        }
    }
}
    
This one's only ~3x slower than glibc on the worst test, and near identical for many other tests. That's a huge improvement!

Isn't this undefined behavior?

Sure is :) Sometimes, maximizing performance requires coloring outside the lines :)

Why can't we beat glibc?

glibc's strlen uses the same tricks as ours, but glibc's is handwritten assembly, and has a few more tricks of its own. Still, it's surprising that we can get this close using only standard C23 (and a touch of UB)!

The code

Here it is. There's a Rust script for benchmarking, and a strcpy in there too. It should go without saying, but I wrote both this post and the code.