Hacker News new | ask | show | jobs
by AnimalMuppet 10 days ago
But (almost) every hardware has some integer type that has the same size as what is needed to represent the address space, because (almost) every hardware has some way of manipulating addresses at the assembly level, and (almost) every C implementation has some integer type that generates those assembly instructions.

I say "almost" because I am not absolutely certain that this is true of absolutely every architecture. Feel free to point out one that breaks these rules, if there is one.

2 comments

In principle a pointer can be a tuple of two other things. Think of CHERI, segmented architectures, etc. In practice on current, modern, general purpose, non-embedded platforms' C ABIs pointers are equivalent to unsigned integers of the same size.
Arguably they're more like signed integers in the case of amd64 - due to address canonicalization. Eg, with 4-level paging we have a 48-bit address space, and valid pointers have the signed integer values `-2^48..+2^48-1`.

They can be further complicated by UAI/LAM, which relaxes the canonicalization constraints and allows bits 48..62 (the high bits, excluding the sign bit) to be anything - so we can have pointers that compare unequal but point to the same address - a potential source of exploits (There's already been Spectre-like vulnerabilities shown for LAM). Fortunately nobody really uses LAM - it needs enabling by the kernel to be used in user space to begin with.

You don't need to interpret the high bit as a sign bit. uintptr_t (unsigned) shows we can interpret pointers as unsigned integers when we can interpret them as integers at all.
You can interpret it as uintptr_t - particularly now that the latest C standards require two's complement representation of integers - but pointers on amd64 are more like signed ints.

The sign bit must match the highest bit of the virtual address (47th bit counting from 0 in the case of 4LP, or the 56th bit for 5LP). (And without LAM/UAI, all the bits in between must match too.)

Eg, with 4LP, if you cast a pointer to `uintptr_t`, shift it left 16 bits, then shift right 16 bits - then an address in the higher half (usually in the Kernel) would be non-canonical. Do the same for `intptr_t` it will be canonical because the shift right is an arithmetic shift.

On other architectures this isn't the case. I know AARCH64 for example does not use canonicalization. If you were doing the same shift left/right by 16 as above on AARCH64, you'd want a uintptr_t.

Segmented 8086 is always the fun one.
I still have occasional nightmares about that. Once I got a 32-bit C/C++ compiler for DOS, I never looked back.