Is there a way to check how "far away" a pointer is from a page boundary?

Yes. Memory addresses are direct-mapped to virtual-memory pages, i.e. by looking at the memory address and masking out the least-significant bits. The least-significant bits are the offset with the page, and tell you how close you are to the page boundary. Since memory can only be marked unreadable by the VM system at the page level, in my understanding it is always safe (can’t segfault) to read memory within the same page as your data (if you are okay with reading garbage).

Assuming that the pages are a power-of-two size that is at least 4096 (4k, 0x1000 in hex) bytes, which I think is true on all x86_64 systems at least, you can therefore check whether the data of a string s is less than 8 bytes from a page boundary by (UInt(pointer(s)) & 0xfff) > 0xff8. I’m not sure about the page sizes on x86, ARM, etc.

This is very finicky low-level stuff, though, with problematic portability. I would be really sure that you have exhausted all other methods of optimization, and that this kind performance hack is really necessary, before considering it.

3 Likes