110 points · by germanrabbit · 3d ago · 114 comments
C supports pointers that can have memory banks, or pointers that are consist of a hash and and an offset. Real world hardware architectures like CHERI does this and standard C supports this. In hardware like that, this would break, even if the subtraction is done on integers, and don't violate the no subtraction of pointer of different allocation rule. So no, Pointers are really not integers, even if they may look like integers on your machine.
E (Member of the wg14 memory model study group.)
For example, if you had a system with segmented memory, you could cast a pointer used in one segment to `intptr_t`, change the segment register, then attempt to cast back to a pointer and dereference it, which of course is UB.
Pointers are not merely bit vectors. Their representation depends on architecture, and there's no guarantee that they even have an integer representation (intptr_t/uintptr_t are optional) - and even if they do have an integer representation, there's no guarantee that this is a complete enough representation to use the pointer - eg, with the segmentation example above - the `intptr_t` does not contain the segment information.
The examples work as one would expect because they're being run on a system with a single linear virtual address space, where pointers can be represented by an integer. The compiler for such platforms may specify what behavior is to occur in these cases - but the C standard does not.
Where this is likely to bite today is on machines where some memory is shared between processors, and some isn't. That's non-uniform memory access.
That takes us back to banked memory. We see this most commonly when GPU memory is exposed to the CPU, but there are Intel processors which support multiprocessor mixed shared and non-shared access. Linux apparently supports this. Pointer arithmetic between pointers from different banks is not meaningful.
The general safe rule is that, at some level, something allocates memory, and it returns something for which arithmetic is valid only on a part. There may be suballocators, as with Vulkan. Vulkan has an allocator for big blocks, and applications then need an allocator which subdivides those big blocks.
This leads to slices. If a slice is safe, a subslice is also safe. If all operations are on slices, you're good. That's the Rust philosophy.
Historically, slices came very late. If someone had thought of slices in the 1970s, they probably would have been in C, which would have eliminated most of the need for pointer arithmetic. Slices are just bounded pointer arithmetic, really. That C lacks slices is the underlying cause of many headaches.
Yes and this went all the way to the point where even foreign device memory is now mapped into that address space. The address space is linear but its backing memory is not.
Linear address spaces are perfectly logical on the machine level because it is just an arrangement of bits which is easy for silicon to process.
The actual problem that we are hitting is that this linear address space is carved up into (possibly nested) bounded regions and you are not allowed to go outside the region for a given pointer. This is what CHERI, etc do, they add the region information back on the machine level which clears up the confusion.
Should the language be made more explicit? Maybe, but any such change opens the door to errors. For example, modified language may need to explicitly account for object lifetimes. Pandering to every imaginative interpretation is a losing game; it's a balancing act, and there are many other higher priority tasks to attend to.
It's not the same argument because the type in this case is still a pointer (which is not strictly an integer).
The standard is quite clear about conversion between pointers and integers.
> An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, may not be correctly aligned, may not point to an entity of the referenced type, and can produce an indeterminate representation when stored into an object.
> Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result is not required to be in the range of values of any integer type.
The purpose of `intptr_t` is to solve that last issue: it's an integer type sufficiently wide to hold a pointer, so that the result is in the range of values held by the intptr_t - and thus the round trip compares equal to the original pointer - but there's nothing else specified in the spec about intptr_t solving the other issues outlined in these clauses.
A segmented architecture that can not support this should not support intptr_t. It is optional for this reason.
And x86-64 is arguably still "segmented" in that you can use the FS and GC segment registers (they're typically used for TLS). Eg, if you cast a `thread_local` pointer to `intptr_t` - the standard makes no requirement that it point to the absolute virtual address (though this is the common implementation choice by GCC etc).
Feels a little like Harvard architecture says there is not global axiom of choice and von Neuman architecture and single tape Turing machines explicitly count everything in the same memory (except for the logic in the Turing machine control head.)
The C standard doesn't even guarantee that. It only guarantees the conversion from 0 to a null pointer. Any other integer-to-pointer conversion is implementation defined.
What implementations _want_ to define is a different question though.
> The mapping functions for converting a pointer to an integer or an integer to a pointer are intended to be consistent with the addressing structure of the execution environment.
So even if it's not mandatory, it is expected to work.
How does that work when I want to set an address high?
Here's the Rust documentation: https://doc.rust-lang.org/std/ptr/index.html#strict-provenan...
So in Rust much of this is spelled out today, although of course the LLVM backend still miscompiles some programs (in Rust or indeed in C or C++) because it can be tricked into giving integers provenance even though that's clearly not what anybody wanted. Oops.
However in C, which most of the examples are written in, the status is a bit less clear. Martin Uecker (who can often be found here in HN's comments) and colleagues wrote a document for ISO but that document is not (yet?) part of the ISO C standard itself. Of course in practice compilers like LLVM, GCC and MSVC need to do what the document says instead of making it up as they go, or else this matters very little.
One thing which cannot be in doubt in any of these close-to-the-metal languages today, almost certainly including obscure ones you've maybe taken a shine to like Odin or Hare, is that provenance is a thing, if you're sure you don't have pointer provenance in your languages but you do have actual pointers, check with a stop watch. If your programs in that language are very slow you might be right.
Because that's why this became a thing. Without provenance, pointers strangle many "obvious" optimisations. Add provenance and now these optimisations are available and your programs go much faster. It's a bargain - albeit one you probably never signed up for as a programmer.
I believe it's a bit of an exaggeration. Formally specifying int2ptr and ptr2int casts in a way that permits both all code found in the wild (or at least a large majority of it) and all optimizations compilers want to perform (ditto), is more than just a bit difficult.
My favourite example is ColdString, a value the same size as a thin pointer and which could be pointing at some text on the heap - but for smaller texts it is actually inline UTF-8 encoded text, the author originally wrote this to rely on the scary Exposure rules and I asked them if it couldn't be Strict instead and instead of "If you're so smart why don't you do it then?" they just fixed it. Nice. Huge fan of ColdString.
However, there are extant examples where you can just trick LLVM into asserting that two integers a,b are different and then showing that a - b == 0 which proves it was lying, those are by definition miscompilations and they don't rely on Exposure, they're just getting the LLVM optimiser to apply a pointer provenance optimisation to a thing it was just told is not a pointer.
It seems to be a vector of bits? Except in practice, a bitvector is just an int where you're using the binary digits to store stuff? And you gotta use these awkward bitwise operators to actually use it? (Popular in 90s video games, to save RAM!)
Or was it another way of saying "ultimately it's the same pattern of ones and zeroes so you can do whatever you want with it as long as you know what you're doing" ?
Exactly. Much equivocation happens when talking about concepts and representation of those concepts. Numbers, bitvectors, pointers, ones-and-zeros, colors, characters, indices, enum values, and whatever all share the same representation. The author thought "bitvector" best represented the commonality (though it doesn't).
I guess the point here is CPUs operate on groups of bits that are very localized spatially (physically).
I think he's trying to say it's just the opposite: an int is really "just" a bitvector, when it comes down to it, and you just happen to be using a constrained set of operations to emulate the behavior we expect of integers.
Depending upon the architecture, not all values can be memory addresses (aka pointers) due to alignment constraints. Then other way around is possible as long as memory addresses have at least l the same number of bits as integers.
Finally, as long as you don't dereference an integer used (casted) as a pointer, there is no difference. Like equality comparison.
To oversimplify, provenance is the metadata a compiler keeps about a pointer during the compilation process.
On a MTE enabled system, adding an offset to a pointer cast to integer will result in an exception with high probability since the new pointer will be using the tag for the old address.
https://docs.kernel.org/arch/arm64/memory-tagging-extension....
int *x = malloc(4);
*x = 42;
int *y = realloc(x, 4);
*y = 43;
printf(“%p %d %p %d\n”, x, *x, y, *y);
This may well print the same address for x and y while printing different values for x and y. Despite having the same bitwise value, x was invalidated by the call to realloc and it became illegal to access x. Thus the compiler is free to assume that x still holds the value previously assigned to it (or make demons fly out of your nose when you try to read from it), because a pointer isn’t just a memory address, it has meaning tied to where you got it and what you did with it.So, mathematically, pointers still are integers, because "everything" can be encoded as a natural number. Handles like in Windows or UEFI, hardware descriptors like internal to netmap and io_uring for NIC physical memory mapped control registers, 32-bit integer page numbers within sqlite databases, or memory addresses in x86_64 registers. Tagged numbers for counting stuff. Just look at off_t in Linux. Or unix filesescriptor fd numbers into a tiny per-process table of each Linux process. Some with hardware support, some without.
And then stuff like ptrdiff_t in the C abstract machine.
All the same idea. And it "only works", because they are "just numbers".
And then come the implementation details.
x86_64 is useful and widespread maybe because it is so easy to use like pointers are just integers and because the IBM PC was cheap back in the day and still is affordable today. And backwards compatibility just like Java.
Itanium was not backwards compatible and died almost immediately.
For better or for worse, C tries to run on all kinds of hardware that is obscure today. Like one's complement or sign-magnitude integers. This is why no C or C++ library will ever have decent bounds checked arrays.
And back in 1989 it was decided that coming from a PDP-11 and faced with this "anything goes". Until compiler writers used UB to intentionally break SSL, everything looked fine. We are still learning from this.
One problem with overflow safer languages on LLVM is that LLVM IR was originally designed for C++ and some NULL pointer UB weirdness or signed overflow weirdness specific to C was baked into LLVM's IR at the lowest level.
As long as we do this it will be horrible. No escape hatch to sane behaviour. Except for people to skip all the UB by writing assembly for random proprietary microcontrollers.
Under that model, VLIW is basically impossible. You need something that prevents mutable aliasing, because if you don't have mutable aliasing you can use software managed caches (including local register copies) and your software model has effectively as many write ports as there are pointers.
It's not a compiler problem, it's a language problem. You can't keep pretending that a inherently parallel machine can be programmed by an inherently sequential programming language.
It jumps to the eyes that such conversion is being attempted instead of having a easy to ignore type cast, where the optimiser takes all sorts of liberties.
This drove many people mad in college when learning C
And to be fair, sometimes tests seemed like they were trying to deliberately make us suffer
Conceptually they seem pretty clear (value vs link/reference). I think most of the confusion arrises when implementing, C can be hard to read and cryptic to follow when running. A debugger is almost always needed for anything but the most basic projects
I wonder if the hello world for C should actually include debugging instructions
Well because they teach them wrong. Stepping through some examples with a debugger that shows all the values live should clear it up. And yes, use x86 as the teaching platform and ignore everything else, whoever is interested in some funky architectures will find the answers themselves after the class.
> sometimes tests seemed like they were trying to deliberately make us suffer
Half of it is because some teachers are pricks, but the other half is, that tests are meant to challenge someone's thinking. Being able to understand crap like int** x = &(*y) is absolutely useless in practice, but proves the knowledge that isn't just monkey memorizing.
Behaviour that is not defined is undefined behaviour. Integer to pointer conversion is IDB, which is the same as UB except that a conforming compiler documents what could happen. I believe it's typically documented as unpredictable, so the same as plain UB.
UB means your program is not a C program and has no semantics whatsoever past the point it reaches the UB. The compiler is thus free to assume that the point that the UB would happen can't be reached and optimize in accordance to that assumption - which many modern compilers do, with often unexpected consequences (such as the infamous case of removing an integer overflow check in Linux because an_int+1>an_int is guaranteed to be true in the C abstract model).
https://gcc.gnu.org/onlinedocs/gcc/Arrays-and-pointers-imple...
call __printf_chk@PLT mov ecx, DWORD PTR 0[rbp] mov rdx, rbp mov edi, 2 mov DWORD PTR -96[rbx], 7
C and C++ happen to have a particularly restrictive view on what “the semantics” of a program really are, such that there are a lot of things you can write in syntactically-legal C that officially erase the semantic meaning of the code. Within that definition of the program’s semantics, gcc’s optimizer is not supposed to change them, and any such change would be a bug. You’re taking a more expansive view of program semantics than the actual language specifies. If you do that, then any optimizing compiler is going to consider it to be acceptable to violate your special bespoke definition of them.
For this particular example the line should be clear. If the variable is volatile, memory access can't be removed or reordered. If it's not volatile, everything is fair game.
Mandatory Godbolt link: https://godbolt.org/z/fjKs4hbjo
Or strange issues with optimizing infinite loops and the Halting problem preventing a full automated solution.
The C compilers like GCC just hide stuff away and break things silently.
If that's true, you have a bad language.
What is known to be the case with C, but this is not a desirable nor a necessary state of affairs. A language can and should have defined semantics.
Yes, I'm a C programmer, how did you know?
Using a tool doesn't mean understanding that tool, just means you know how to follow some repetitive processes over and over again.
The language only guarantees that an integer is at least 16 bits. There is no guarantee that a compiler that supports a > 16 bit address space will chose to make integers large enough to hold a pointer, and for example gcc still uses 32-bit integers for 64-bit processors.
I'm not sure if C even requires a pointer to be just a linear address, as opposed to something structured.
It doesn't. The standard does not require any particular representation for pointers. It does specify that addition and subtraction on them is possible - but does not specify how this occurs - only that for example, if you have an array `int x[]`, then `x + 1` should point to the second item (index 1) in the array.
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.