The argument that this is valid defined C is not entirely correct. You can not subtract one pointer form another that doesn't come from the same allocation, that is explicitly UB. But the user here subtracts one integer from the other and that is valid. However C only guarantees you can you can convert a integer to a valid pointer, if that integer has been converted from a pointer, and not been modified in any way. If the integer has been modified its implementation defined what happens. Its no longer valid standard C.
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.
If you convert a pointer to `intptr_t`/`uintptr_t` and back again to a pointer, the standard only guarantees that it compares equal to the original - but it makes no guarantee that you can dereference that pointer.
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.
This is in theory true, but almost all the machines for which pointers were not integers have died out. There were a lot of them during the 16 to 32 bit transition, the Intel 286 being the best known. There were tagged machines, such as Burroughs mainframes and Symbolics LISP machines, but those are mostly forgotten.
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.
>This is in theory true, but almost all the machines for which pointers were not integers have died out.
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.
The standard copies the same language used for defining void pointer conversions, that you can convert any object pointer to a void pointer and back again and the result will compare equal. So your interpretation would also necessarily imply the standard doesn't guarantee you can dereference such a pointer. In legal textual analysis that would count as an absurdity, meaning it's obviously not a reasonable interpretation.
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.
> So your interpretation would also necessarily imply the standard doesn't guarantee you can dereference such a pointer.
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 pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
and
> 7.22.1.4 Integer types capable of holding object pointers
> The following type designates a signed integer type, other than a bit-precise integer type, with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer:
> intptr_t
intptr_t is not like other integer types. It has special properties and guarantees that other integer types might not, even when they're the same width.
And I think your interpretation about dereferencing may be ruled out by 6.5.10p7:
> Two pointers compare equal if and only if both are null pointers, both are pointers to the same object....
That is, if they compare equal and one is a valid object pointer then the other is a valid object pointer, regardless of whether it was round-tripped through intptr_t/uintptr_t.
I hear this claim sometimes, but I think this is a far-fetched interpretation that you can only compare the pointers after backconversion but not use them.
A segmented architecture that can not support this should not support intptr_t. It is optional for this reason.
The C standard does not make any guarantees that you can dereference it.
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).
> 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.
That isn't to say we can't do the cast - compilers specify the behavior, and most modern architectures have a linear virtual address space where the round trip is valid - though it may not always be - for example, with the fs/gs segment registers - a cast of pointer to integer isn't just a simple conversion of type - it must also fetch the value from the FS register and offset the pointer by this to produce an integer containing the absolute address. This is entirely implementation defined.
Producing the absolute virtual address of a `thread_local` is potential UB though - if you attempt to dereference it in a different thread.
Another example would be casting a qualified pointer (const, restrict, volatile) to an integer, then back to a pointer with a different qualifier or no qualifier - then dereferencing such pointer would of course be UB as per the standard - the cast to `intptr_t` loses information about its qualification - but the pointers would still compare equal - as the standard guarantees that a pointer cast to a qualified pointer compares equal.
There are stricter requirements for casting a void pointer to (u)intptr_t and back. Again, a segmented architecture should not provide (u)intptr_t. But if an implementation has it, in my opinion, this is expected to work.
The only stricter requirement in the standard is that they compare equal after the round trip.
The intended purpose of these types is to allow the round trip, yes, and the requirement they compare equal is part of that. The standard doesn't put stricter requirements. I don't think that is an oversight, but a deliberate omission to allow for flexibility in implementation.
It's up to the compiler to specify that it's safe to dereference the pointer after the round trip - the standard does not want to put such constraints on implementors.
This is where I disagree. In the context when this was written, I think it was clear that two pointers that compare equally were meant to be interchangeable.
It would've been trivial for the committee to add such clause in the spec - why only the requirement that they compare equal and not that they dereference the same object?
The standard leaves a lot of things implementation defined deliberately to allow for flexibility in both processor design and compiler implementation.
I don't think for example, a segmented architecture shouldn't provide an `intptr_t` - it's still useful to be able to cast a pointer to integer and back even in the case of segmentation - but is obviously more prone to error if we dereference it in a different segment (which would be UB).
I completely agree that it is the intended case that a pointer that has had this round trip is intended to be dereferenced - but I disagree that the requirement to do so is an oversight and not a deliberate omission.
There are potential cases where you would want to dereference the pointer but to a different object (which is UB by the standard, but could be well defined for a specific compiler/arch). Consider for example, if you have a bunch of threads which all have the same structure in their thread local storage - it can be useful to be able to specify an offset that is going fetch a value specific value from the TLS - but obviously a different one in each thread - ie, we want the pointer to be an offset, and not an absolute address.
It is not trivial for anything to be done in a committee. If we wrote this text today, we would clearly specify this differently, but in the 90s there was not much reason to assume that this will be misunderstood. Note also that the far / near pointer model used by segmented architectures was never part of ISO C.
The committee wanted to have TS 6010 which would clarify that this work, but at the request of compiler vendors it is not (yet) part of the IS. But the reasons are unrelated to pointer round trips.
It would have been trivial, given foresight of such an argument. "They didn't specifically reject my interpretation of this document when they wrote the document" isn't a good argument for your interpretation, especially when it's a particularly counterintuitive one.
The standard is quite specific about what occurs when casting between integers and pointers.
> 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.
Why would these passages be written with such specificity, only to be overridden by unwritten passages w.r.t intptr_t?
When intptr_t was added, for C99, segmented memory was not uncommon, and there was more variation in processor architecture. The reason this is IDB or UB is because there were architectures where the implementation of such conversions is not straightforward.
Today we've largely converged on a common model of a single virtual address space with paging - if it were written today, it probably would have included such clauses, or made more assumptions about conversion between int/pointer rather than explicitly stating that nearly all behavior in this regard is IDB or UB, because the architectures these clauses were written to address - where implementation is non-obvious - are pretty much obsolete.
Anything besides this is subjective "interpretation" of the spec. There's nothing about `intptr_t` having different properties - the intptr_t is sufficiently wide to hold a pointer converted to integer - it solves only the last issue that "the result is not required to fit in the range of values of any integer type" - and hence why `intptr_t` is optional. It says nowhere that its purpose is to ensure that an intptr_t converted back to can be dereferenced without IDB. It's a pointer converted from an integer which is still subject to the constraints specified for int->pointer and pointer->int conversion.
Again, I don't challenge the idea that `void*->intptr_t->void*` is intended to result in a usable pointer - but I reject the idea that it was some kind of oversight to not explicitly state it in the spec - when the spec explicitly states the opposite - that it's IDB. It's implementation-defined because it was intended to be used in such way where pointers are effectively integers, but they did not want to place constraints on compilers which targetted the other architectures where making this guarantee would've been unpractical.
There are also Harvard architecture machines like microcontrollers where a function pointer points to ROM and a data pointer points to RAM.
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.)
> However C only guarantees you can you can convert a integer to a valid pointer, if that integer has been converted from a pointer, and not been modified in any way. If the integer has been modified its implementation defined what happens. Its no longer valid standard C.
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.
I'm not a C expert, however I do follow Rust's discussions about pointer provenance. It might be unspecified but people do rely on this (e.g. pointer tagging is the same under your explanation), and even CHERI uses hacks to not break them, at least whenever possible. Furthermore the standard says in a footnote:
> 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.
> However C only guarantees you can you can convert a integer to a valid pointer, if that integer has been converted from a pointer, and not been modified in any way.
How does that work when I want to set an address high?
You cant in standard C, but many implementations do let you manipulate pointers in all kinds ow ways, but then your code depends on an extension of the language and is not portable. C is designed so that you can write both portable and non portable code. I would argue you shouldn't because often these extensions are very poorly documented and are based mostly on "it seems to work". Try when possible to stay within the standard.
Quite some time after this blog was written Aria blogged about the "strict provenance experiment" for Rust, and today Aria's API (more or less) is sanctioned and Rust is defined to deliver the behaviour Aria described in the Tower of Weakenings.
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.
> However in C, which most of the examples are written in, the status is a bit less clear.
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.
Hey, that's me. TS 6010 is not currently supported by GCC and Clang. But also for Rust this does not work due to the same compiler issues. (as you point out)
Do note though that strict provenance in Rust does work (at least we're not aware of any miscompilation AFAIK), and pre-strict-provenance semantics, or exposed provenance semantics, are warned against in the docs and clarify that they do not have accepted formal semantics. So the situation is a bit better than C.
It's true that Rust gives confidence to do (some) crazy pointer tricks which would work in the "pointers are just integers" world, yet not pay the performance price such tricks would cost if we really did "pointers are just integers"
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.
> 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.
If I'm getting what you mean correctly, that's not true. Integers do not have provenance and if `a - b == 0` then `a == b` when a, b are integers. The problem is only when LLVM concludes from this that `a as *const _ == b as *const _`, and that doesn't exist for strict provenance.
> If I'm getting what you mean correctly, that's not true
Well, what I'm doing here is describing the real situation with LLVM. If by "that's not true" you mean "that would be a bug in LLVM" then, uh, yeah, we know that it's a bug in LLVM. The LLVM maintainers know it's a bug in LLVM, have for many years.
> Integers do not have provenance
No, integers shouldn't have provenance. Due to this compiler bug unfortunately we can give integers provenance and blow up the world. Remembering the difference between what is and what should be is important, most especially in Criminal Justice.
So as to not rag specifically on LLVM, here's a ticket with Martin in the comments where somebody blew up GNU's C compiler on essentially the same trick question:
> If by "that's not true" you mean "that would be a bug in LLVM" then, uh, yeah, we know that it's a bug in LLVM.
No that's not what I meant. Of course there is a bug in LLVM, but I said there will be no miscompilations and meant that - because with strict provenance, we don't use the problematic constructs (that LLVM miscompiles).
> No, integers shouldn't have provenance. Due to this compiler bug unfortunately we can give integers provenance and blow up the world.
Nope that's incorrect. In LLVM (and all other compilers I know) integers do not have provenance, and there aren't any optimizations that think they do. The bug (as understood by experts) is in pointer handling and not integers, specifically that ptr2int is not treated as having side-effects and that int2pt is considered to give the same pointers for the same integers.
When you follow this link they'll have arbitrary values so I can't predict what those values will be but I can tell you that they'll be identical because the optimising compiler put both those unused temporary locals in the same spot on the stack.
One and three are booleans which ask whether the pointers to those temporaries are the same, LLVM says they are not even though Rust's policy is that they are. That's not great, but we could choose to imagine that's a Rust bug, except...
Two is another boolean asking whether the integers c and d are the same. LLVM says that those aren't the same either. It has given provenance to integers, that's the bug.
Perhaps. In C one should avoid any non-local use of one-after pointers and any integer-to-pointers casts. Then I think one is also safe from miscompilation. Alternatively, one can use a compiler that is not broken.
You definitely can be safe in C as well - the difference I noted is that in Rust the safe pattern is officially blessed and the unsafe pattern is officially unblessed.
That is fair, but we are a bit in a different situation. There are many C compilers, and we can not unbless language constructs every time one of them has implementation bugs. Perhaps would could this in this case, but compared to other issues compilers have, it is also a relatively minor issue in terms of practical impact on C code.
Also to be fair, it has to be said that officially blessed safe Rust code is not really what is competing with C.
No, not really. There are couple of smaller compiler projects such as tcc, slimcc, cparser, kefir, etc. that I kind of hope will mature a bit more, but I haven't really used them.
Sometimes I am wondering whether I should continue to develop my own compiler with an eye towards correctness, but I do not have enough time at the moment. And fixing bugs in GCC seems more useful.
Article says pointers and its are both just bitvectors, but doesn't explain what a bitvector is.
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" ?
>ultimately it's the same pattern of ones and zeroes
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).
Yeah, “bitvector” implies individually addressable bits, which is something you most certainly cannot do with pointers. I think the term they were looking for was “bag of bits”, i.e. opaque. But even that only applies to void pointers, anything with a defined size has arithmetic semantics too.
> Except in practice, a bitvector is just an int where you're using the binary digits to store stuff?
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.
There was an old VAX or something that had a C standard library where function pointers in both C and Fortran were multiple machine words. C was 4 words and Fortran was 6 with everything but the first two being reserved for later. The idea was to provide additional argument and return type information in tag bits in the additional machine words.
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".
That is indeed the semantics most people want, but justifying why is not trivial, and it's also not trivial to formally specifying everything with this view.
The easiest way to justify it is to think about pointers that are literally not integers: CHERI capabilities. It's not the original motivation for provenance but it's kind of an explicit encoding of it so it's a nice way to understand it IMO.
That's not a justification for why we want that when compiling to other platforms though. CHERI indeed chooses to have provenance for pointers and not integers, but it's not the only possible choice (even though it is the best choice, but we want to justify it here).
I tried, but frankly, typing "pointer provenance" into Google gets you a much better explanation than my attempt. Google's AI analysis might be questionable, but it's less questionable than my first attempt.
To oversimplify, provenance is the metadata a compiler keeps about a pointer during the compilation process.
For example, Arm Memory Tagging Extension uses the top byte of a 64-bit address to store a tag that the CPU verifies against the allocation tag on pointer dereference. If the tags don't match, an exception occurs. MTE makes exploiting memory vulnerabilities more difficult by preventing the attacker from generating valid pointers to hijack program control flow with. To bypass MTE, the attack would need to combine the exploit with an info leak or arbitrary memory read to set the correct tag for a new pointer.
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.
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.
That certainly would be very nice. It’s also extremely difficult to do reliably. One certainly could make the argument that it should be done in easy cases like this example. But I suspect that the cases where it’s easy to consistently fault and the cases where it’s a useful diagnostic in real programs don’t have much overlap.
C abstract machine is from 1989 and also wants to be compatible with machines like a VAX or microcontrollers with Harvard architecture from back then.
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.
There are other systems languages, some which older than C, without such problems, because contrary to C, they decided from the start that some operations are unsafe, like conversion between plain integers and raw pointers, thus these kind of issues don't arise like they do in C and C++.
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.
Itanic failed because the Sufficiently Smart Compiler that could pack its instruction set decently well never materialized. Funky pointer representation is something compilers could handle from long experience at it, EPIC still is not, and today’s processor pipelines seem to show that it it isn’t even necessary.
Itanium failed because AMD exists, without the rights to produce AMD64, Intel would be able to push Itanium no matter what, it was already the future of Windows 64 bit version, before AMD64 became public.
In mutable aliasing world (aka C and C++ like languages), there is officially speaking, only one global memory with one very fast read and write port.
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.
> What's the difference between an integer and a pointer?
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.
> First, does this C program execute undefined behavior? It does not! Computing out-of-bounds pointers is UB but we are free to do whatever we like with integer-typed values that were derived from pointers. Second, does the C standard mandate the behavior that we saw here? It does not!
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.
There is a vast difference between IDB and UB. IDB is perfectly fine to rely on for your compiler, but it means your program may not be portable to other compilers.
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).
> When casting from pointer to integer and back again, the resulting pointer must reference the same object as the original pointer, otherwise the behavior is undefined.
So I'm right. This is implementation-defined, and the way the implementation has defined it is to make it fully UB (except for round trips).
Whenever something is undefined behaviour or not is a matter of the standard and what the implementation may or may not have defined for that is immaterial to that. As far as the standard is considered, when they encounter UB, you no longer have a valid C program. However the compiler can still choose to do something with it, which in this particular case manifests as GCC has documented it, but some other compiler can do something else for it.
Good point, I misremembered that. I have read the standard, but it seems that they changed some of the language around between C17 and C23. In C17 (6.3.2.3 Pointers), we have:
> 5 An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.68)
> 6 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 need not be in the range of values of any integer type.
And in C23 (6.3.2.3):
> 5 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.58)
> 6 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.
It's interesting that they dropped the "trap representation" language from C23. Of course, being an "indeterminate representation" probably does the same thing given that "trap representation" isn't a thing in C23 at all.
But yeah, I was wrong about the pointer roundtrip.
I don't think GCC is doing something special, rather that -O3 might be optimizing out the subtraction. Try with -O0, I suspect you will get the same result as clang.
That depends entirely on how you define “the semantics.” Any optimizing compiler has to draw a line between what the program is meant to do and how the emitted code actually makes it happen. The proper location of that line is not obvious. Can it turn x++,x++ into x+=2? That’s normally fine, potentially disastrous if x is a memory mapped register on an external device.
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.
It’s clear by the language spec. It’s not clear based on how people want it to work or think it should work. And the inevitable stream of comments complaining about C compiler optimizers every time this gets discussed tells us that people are not willing to just consider where the language spec draws the line.
Because doing so doesn’t change the semantics of the program as defined by the language.
If you open the possibility of other notions of “the semantics” besides what the language spec lays out, then changing those semantics is an inherent part of an optimizer.
What people (IMO fairly reasonably) want is a different C language spec with less undefined behavior and compilers that follow that spec. But people don’t think about it clearly and skip major parts of that picture when complaining about it.
Many people program for their hardware (what else can be actually tested) or maybe qemu or virtualbox or vmware or a specific external microcontroller.
Very few people want to program for the C abstract machine. The C abstract machine doesn’t even really have dlopen(3). It also has to be compatible with Harvard architecture, von Neumann architecture, two's complement signed machine word integers, one's complement signed machine word integers, and sign-magnitude signed machine word integers.
I’m not talking about whether a language has defined semantics. C’s semantics are plenty well defined, much better than the current crop of more modern languages that are mostly defined by their single implementation.
I’m talking about the question of what should be covered by the official semantics. That’s inherently subjective and a matter of opinion.
Gcc’s optimizer does not accept changing language-level semantics based on which optimizations are performed. That the above comment thinks it does means that the commenter has a different notion of what should count as “the semantics” from what the language spec says. Which is a perfectly legitimate opinion, but if you take that position then you have to accept that other people will have other ideas of what should count, and therefore any optimizer might change “the semantics” of code according to at least some of those ideas.
They are definitely not integers on the Symbolics Lisp machine. The C standard allows for atypical representations. [u]intptr_t is optional for this reason.
Sure, but if you're not an embedded programmer, if you're not working with odd architectures, then the difference between pointers and unsigned integers of the same size in C on common current platforms' C ABIs, is minimal. Of course there are footguns here: you can't conjure up and dereference a pointer from an integer that isn't itself obtained from casting from a valid pointer.
C doesn't provide any guarantee that a pointer can be stored in an integer.
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.
> 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.
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.
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.
The argument that this is valid defined C is not entirely correct. You can not subtract one pointer form another that doesn't come from the same allocation, that is explicitly UB. But the user here subtracts one integer from the other and that is valid. However C only guarantees you can you can convert a integer to a valid pointer, if that integer has been converted from a pointer, and not been modified in any way. If the integer has been modified its implementation defined what happens. Its no longer valid standard C.
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.)
If you convert a pointer to `intptr_t`/`uintptr_t` and back again to a pointer, the standard only guarantees that it compares equal to the original - but it makes no guarantee that you can dereference that pointer.
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.
This is in theory true, but almost all the machines for which pointers were not integers have died out. There were a lot of them during the 16 to 32 bit transition, the Intel 286 being the best known. There were tagged machines, such as Burroughs mainframes and Symbolics LISP machines, but those are mostly forgotten.
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.
>This is in theory true, but almost all the machines for which pointers were not integers have died out.
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.
The standard copies the same language used for defining void pointer conversions, that you can convert any object pointer to a void pointer and back again and the result will compare equal. So your interpretation would also necessarily imply the standard doesn't guarantee you can dereference such a pointer. In legal textual analysis that would count as an absurdity, meaning it's obviously not a reasonable interpretation.
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.
> So your interpretation would also necessarily imply the standard doesn't guarantee you can dereference such a pointer.
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.
From C23 (N3220), compare
> 6.3.2.3 Pointers
> A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
and
> 7.22.1.4 Integer types capable of holding object pointers
> The following type designates a signed integer type, other than a bit-precise integer type, with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer:
> intptr_t
intptr_t is not like other integer types. It has special properties and guarantees that other integer types might not, even when they're the same width.
And I think your interpretation about dereferencing may be ruled out by 6.5.10p7:
> Two pointers compare equal if and only if both are null pointers, both are pointers to the same object....
That is, if they compare equal and one is a valid object pointer then the other is a valid object pointer, regardless of whether it was round-tripped through intptr_t/uintptr_t.
I hear this claim sometimes, but I think this is a far-fetched interpretation that you can only compare the pointers after backconversion but not use them.
A segmented architecture that can not support this should not support intptr_t. It is optional for this reason.
The C standard does not make any guarantees that you can dereference it.
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).
The standard is English text which may not alway be perfectly precise, but the wording there clearly was meant to allow this.
I think it's quite clear.
> 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.
That isn't to say we can't do the cast - compilers specify the behavior, and most modern architectures have a linear virtual address space where the round trip is valid - though it may not always be - for example, with the fs/gs segment registers - a cast of pointer to integer isn't just a simple conversion of type - it must also fetch the value from the FS register and offset the pointer by this to produce an integer containing the absolute address. This is entirely implementation defined.
Producing the absolute virtual address of a `thread_local` is potential UB though - if you attempt to dereference it in a different thread.
Another example would be casting a qualified pointer (const, restrict, volatile) to an integer, then back to a pointer with a different qualifier or no qualifier - then dereferencing such pointer would of course be UB as per the standard - the cast to `intptr_t` loses information about its qualification - but the pointers would still compare equal - as the standard guarantees that a pointer cast to a qualified pointer compares equal.
There are stricter requirements for casting a void pointer to (u)intptr_t and back. Again, a segmented architecture should not provide (u)intptr_t. But if an implementation has it, in my opinion, this is expected to work.
The only stricter requirement in the standard is that they compare equal after the round trip.
The intended purpose of these types is to allow the round trip, yes, and the requirement they compare equal is part of that. The standard doesn't put stricter requirements. I don't think that is an oversight, but a deliberate omission to allow for flexibility in implementation.
It's up to the compiler to specify that it's safe to dereference the pointer after the round trip - the standard does not want to put such constraints on implementors.
This is where I disagree. In the context when this was written, I think it was clear that two pointers that compare equally were meant to be interchangeable.
It would've been trivial for the committee to add such clause in the spec - why only the requirement that they compare equal and not that they dereference the same object?
The standard leaves a lot of things implementation defined deliberately to allow for flexibility in both processor design and compiler implementation.
I don't think for example, a segmented architecture shouldn't provide an `intptr_t` - it's still useful to be able to cast a pointer to integer and back even in the case of segmentation - but is obviously more prone to error if we dereference it in a different segment (which would be UB).
I completely agree that it is the intended case that a pointer that has had this round trip is intended to be dereferenced - but I disagree that the requirement to do so is an oversight and not a deliberate omission.
There are potential cases where you would want to dereference the pointer but to a different object (which is UB by the standard, but could be well defined for a specific compiler/arch). Consider for example, if you have a bunch of threads which all have the same structure in their thread local storage - it can be useful to be able to specify an offset that is going fetch a value specific value from the TLS - but obviously a different one in each thread - ie, we want the pointer to be an offset, and not an absolute address.
It is not trivial for anything to be done in a committee. If we wrote this text today, we would clearly specify this differently, but in the 90s there was not much reason to assume that this will be misunderstood. Note also that the far / near pointer model used by segmented architectures was never part of ISO C.
The committee wanted to have TS 6010 which would clarify that this work, but at the request of compiler vendors it is not (yet) part of the IS. But the reasons are unrelated to pointer round trips.
It would have been trivial, given foresight of such an argument. "They didn't specifically reject my interpretation of this document when they wrote the document" isn't a good argument for your interpretation, especially when it's a particularly counterintuitive one.
The standard is quite specific about what occurs when casting between integers and pointers.
> 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.
Why would these passages be written with such specificity, only to be overridden by unwritten passages w.r.t intptr_t?
When intptr_t was added, for C99, segmented memory was not uncommon, and there was more variation in processor architecture. The reason this is IDB or UB is because there were architectures where the implementation of such conversions is not straightforward.
Today we've largely converged on a common model of a single virtual address space with paging - if it were written today, it probably would have included such clauses, or made more assumptions about conversion between int/pointer rather than explicitly stating that nearly all behavior in this regard is IDB or UB, because the architectures these clauses were written to address - where implementation is non-obvious - are pretty much obsolete.
Anything besides this is subjective "interpretation" of the spec. There's nothing about `intptr_t` having different properties - the intptr_t is sufficiently wide to hold a pointer converted to integer - it solves only the last issue that "the result is not required to fit in the range of values of any integer type" - and hence why `intptr_t` is optional. It says nowhere that its purpose is to ensure that an intptr_t converted back to can be dereferenced without IDB. It's a pointer converted from an integer which is still subject to the constraints specified for int->pointer and pointer->int conversion.
Again, I don't challenge the idea that `void*->intptr_t->void*` is intended to result in a usable pointer - but I reject the idea that it was some kind of oversight to not explicitly state it in the spec - when the spec explicitly states the opposite - that it's IDB. It's implementation-defined because it was intended to be used in such way where pointers are effectively integers, but they did not want to place constraints on compilers which targetted the other architectures where making this guarantee would've been unpractical.
FTR C++ makes the guarantee. I'm not familiar enough with C standard wording to comment on that.
There are also Harvard architecture machines like microcontrollers where a function pointer points to ROM and a data pointer points to RAM.
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.)
> However C only guarantees you can you can convert a integer to a valid pointer, if that integer has been converted from a pointer, and not been modified in any way. If the integer has been modified its implementation defined what happens. Its no longer valid standard C.
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.
I'm not a C expert, however I do follow Rust's discussions about pointer provenance. It might be unspecified but people do rely on this (e.g. pointer tagging is the same under your explanation), and even CHERI uses hacks to not break them, at least whenever possible. Furthermore the standard says in a footnote:
> 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.
> However C only guarantees you can you can convert a integer to a valid pointer, if that integer has been converted from a pointer, and not been modified in any way.
How does that work when I want to set an address high?
You cant in standard C, but many implementations do let you manipulate pointers in all kinds ow ways, but then your code depends on an extension of the language and is not portable. C is designed so that you can write both portable and non portable code. I would argue you shouldn't because often these extensions are very poorly documented and are based mostly on "it seems to work". Try when possible to stay within the standard.
Quite some time after this blog was written Aria blogged about the "strict provenance experiment" for Rust, and today Aria's API (more or less) is sanctioned and Rust is defined to deliver the behaviour Aria described in the Tower of Weakenings.
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.
> However in C, which most of the examples are written in, the status is a bit less clear.
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.
Hey, that's me. TS 6010 is not currently supported by GCC and Clang. But also for Rust this does not work due to the same compiler issues. (as you point out)
Do note though that strict provenance in Rust does work (at least we're not aware of any miscompilation AFAIK), and pre-strict-provenance semantics, or exposed provenance semantics, are warned against in the docs and clarify that they do not have accepted formal semantics. So the situation is a bit better than C.
It's true that Rust gives confidence to do (some) crazy pointer tricks which would work in the "pointers are just integers" world, yet not pay the performance price such tricks would cost if we really did "pointers are just integers"
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.
> 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.
If I'm getting what you mean correctly, that's not true. Integers do not have provenance and if `a - b == 0` then `a == b` when a, b are integers. The problem is only when LLVM concludes from this that `a as *const _ == b as *const _`, and that doesn't exist for strict provenance.
> If I'm getting what you mean correctly, that's not true
Well, what I'm doing here is describing the real situation with LLVM. If by "that's not true" you mean "that would be a bug in LLVM" then, uh, yeah, we know that it's a bug in LLVM. The LLVM maintainers know it's a bug in LLVM, have for many years.
> Integers do not have provenance
No, integers shouldn't have provenance. Due to this compiler bug unfortunately we can give integers provenance and blow up the world. Remembering the difference between what is and what should be is important, most especially in Criminal Justice.
So as to not rag specifically on LLVM, here's a ticket with Martin in the comments where somebody blew up GNU's C compiler on essentially the same trick question:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=119472
> If by "that's not true" you mean "that would be a bug in LLVM" then, uh, yeah, we know that it's a bug in LLVM.
No that's not what I meant. Of course there is a bug in LLVM, but I said there will be no miscompilations and meant that - because with strict provenance, we don't use the problematic constructs (that LLVM miscompiles).
> No, integers shouldn't have provenance. Due to this compiler bug unfortunately we can give integers provenance and blow up the world.
Nope that's incorrect. In LLVM (and all other compilers I know) integers do not have provenance, and there aren't any optimizations that think they do. The bug (as understood by experts) is in pointer handling and not integers, specifically that ptr2int is not treated as having side-effects and that int2pt is considered to give the same pointers for the same integers.
> Nope that's incorrect.
https://rust.godbolt.org/z/nxnazs7Y6
c and d are both integers. Do you agree?
When you follow this link they'll have arbitrary values so I can't predict what those values will be but I can tell you that they'll be identical because the optimising compiler put both those unused temporary locals in the same spot on the stack.
One and three are booleans which ask whether the pointers to those temporaries are the same, LLVM says they are not even though Rust's policy is that they are. That's not great, but we could choose to imagine that's a Rust bug, except...
Two is another boolean asking whether the integers c and d are the same. LLVM says that those aren't the same either. It has given provenance to integers, that's the bug.
Oh, it seems you're right. I wasn't aware of this. Interesting.
Perhaps. In C one should avoid any non-local use of one-after pointers and any integer-to-pointers casts. Then I think one is also safe from miscompilation. Alternatively, one can use a compiler that is not broken.
You definitely can be safe in C as well - the difference I noted is that in Rust the safe pattern is officially blessed and the unsafe pattern is officially unblessed.
That is fair, but we are a bit in a different situation. There are many C compilers, and we can not unbless language constructs every time one of them has implementation bugs. Perhaps would could this in this case, but compared to other issues compilers have, it is also a relatively minor issue in terms of practical impact on C code.
Also to be fair, it has to be said that officially blessed safe Rust code is not really what is competing with C.
Do you have a particular suggestion of a "not broken" C compiler? Genuinely interested.
No, not really. There are couple of smaller compiler projects such as tcc, slimcc, cparser, kefir, etc. that I kind of hope will mature a bit more, but I haven't really used them.
Sometimes I am wondering whether I should continue to develop my own compiler with an eye towards correctness, but I do not have enough time at the moment. And fixing bugs in GCC seems more useful.
Article says pointers and its are both just bitvectors, but doesn't explain what a bitvector is.
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" ?
>ultimately it's the same pattern of ones and zeroes
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).
Yeah, “bitvector” implies individually addressable bits, which is something you most certainly cannot do with pointers. I think the term they were looking for was “bag of bits”, i.e. opaque. But even that only applies to void pointers, anything with a defined size has arithmetic semantics too.
It got me wondering so I checked. According to Wikipedia [1], it's a contiguous sequence of bits.
I guess the point here is CPUs operate on groups of bits that are very localized spatially (physically).
[1] https://en.wikipedia.org/wiki/Bit
> Except in practice, a bitvector is just an int where you're using the binary digits to store stuff?
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.
Assembly programmer here.
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.
Assembly indeed has a very easy exit in such issues (and in UB in general).
There was an old VAX or something that had a C standard library where function pointers in both C and Fortran were multiple machine words. C was 4 words and Fortran was 6 with everything but the first two being reserved for later. The idea was to provide additional argument and return type information in tag bits in the additional machine words.
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.
Pointers have provenance, integers don't.
That is indeed the semantics most people want, but justifying why is not trivial, and it's also not trivial to formally specifying everything with this view.
The easiest way to justify it is to think about pointers that are literally not integers: CHERI capabilities. It's not the original motivation for provenance but it's kind of an explicit encoding of it so it's a nice way to understand it IMO.
That's not a justification for why we want that when compiling to other platforms though. CHERI indeed chooses to have provenance for pointers and not integers, but it's not the only possible choice (even though it is the best choice, but we want to justify it here).
When you want to support something like Harvard architecture with functions in ROM and data in RAM.
Go on.
I tried, but frankly, typing "pointer provenance" into Google gets you a much better explanation than my attempt. Google's AI analysis might be questionable, but it's less questionable than my first attempt.
To oversimplify, provenance is the metadata a compiler keeps about a pointer during the compilation process.
For example, Arm Memory Tagging Extension uses the top byte of a 64-bit address to store a tag that the CPU verifies against the allocation tag on pointer dereference. If the tags don't match, an exception occurs. MTE makes exploiting memory vulnerabilities more difficult by preventing the attacker from generating valid pointers to hijack program control flow with. To bypass MTE, the attack would need to combine the exploit with an info leak or arbitrary memory read to set the correct tag for a new pointer.
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....
Isn't the proper sane default behavior to fault if x is accessed after realloc?
To do that you need to track more information than the integer-like value of pointer x.
In this case there’s a good chance that x and y have the same value, for example.
So that is more costly in storage and speed.
I think that depends on compiler flags, at least with gcc.
That certainly would be very nice. It’s also extremely difficult to do reliably. One certainly could make the argument that it should be done in easy cases like this example. But I suspect that the cases where it’s easy to consistently fault and the cases where it’s a useful diagnostic in real programs don’t have much overlap.
[flagged]
Recommended further reading in this blog series by Ralf Jung: https://www.ralfj.de/blog/2020/12/14/provenance.html
2018, and some of the comments are already outdated, SPARK 2014 is out there with ownership model.
C abstract machine is from 1989 and also wants to be compatible with machines like a VAX or microcontrollers with Harvard architecture from back then.
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.
There are other systems languages, some which older than C, without such problems, because contrary to C, they decided from the start that some operations are unsafe, like conversion between plain integers and raw pointers, thus these kind of issues don't arise like they do in C and C++.
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.
Itanic failed because the Sufficiently Smart Compiler that could pack its instruction set decently well never materialized. Funky pointer representation is something compilers could handle from long experience at it, EPIC still is not, and today’s processor pipelines seem to show that it it isn’t even necessary.
Itanium failed because AMD exists, without the rights to produce AMD64, Intel would be able to push Itanium no matter what, it was already the future of Windows 64 bit version, before AMD64 became public.
In mutable aliasing world (aka C and C++ like languages), there is officially speaking, only one global memory with one very fast read and write port.
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.
Context.
One is a mathematical construct, the other is a dog?
> What's the difference between an integer and a pointer?
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
> Conceptually they seem pretty clear
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.
well, their names, for starters...
range of values
> First, does this C program execute undefined behavior? It does not! Computing out-of-bounds pointers is UB but we are free to do whatever we like with integer-typed values that were derived from pointers. Second, does the C standard mandate the behavior that we saw here? It does not!
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.
There is a vast difference between IDB and UB. IDB is perfectly fine to rely on for your compiler, but it means your program may not be portable to other compilers.
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).
How does gcc document integer to pointer conversion?
The rules and process are defined here:
https://gcc.gnu.org/onlinedocs/gcc/Arrays-and-pointers-imple...
> When casting from pointer to integer and back again, the resulting pointer must reference the same object as the original pointer, otherwise the behavior is undefined.
So I'm right. This is implementation-defined, and the way the implementation has defined it is to make it fully UB (except for round trips).
Whenever something is undefined behaviour or not is a matter of the standard and what the implementation may or may not have defined for that is immaterial to that. As far as the standard is considered, when they encounter UB, you no longer have a valid C program. However the compiler can still choose to do something with it, which in this particular case manifests as GCC has documented it, but some other compiler can do something else for it.
You have it backwards, the language document says it's IDB and the ID has chosen to make it UB.
Good point, I misremembered that. I have read the standard, but it seems that they changed some of the language around between C17 and C23. In C17 (6.3.2.3 Pointers), we have:
> 5 An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.68)
> 6 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 need not be in the range of values of any integer type.
And in C23 (6.3.2.3):
> 5 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.58)
> 6 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.
It's interesting that they dropped the "trap representation" language from C23. Of course, being an "indeterminate representation" probably does the same thing given that "trap representation" isn't a thing in C23 at all.
But yeah, I was wrong about the pointer roundtrip.
[dead]
No, these are different things.
I don't think GCC is doing something special, rather that -O3 might be optimizing out the subtraction. Try with -O0, I suspect you will get the same result as clang.
The GCC compiler changes the order of the operations such that the assignment happens after the print for x.
call __printf_chk@PLT mov ecx, DWORD PTR 0[rbp] mov rdx, rbp mov edi, 2 mov DWORD PTR -96[rbx], 7
The "special" thing of note is that GCC considers it acceptable to change the semantics of this program depending on the optimization level.
That depends entirely on how you define “the semantics.” Any optimizing compiler has to draw a line between what the program is meant to do and how the emitted code actually makes it happen. The proper location of that line is not obvious. Can it turn x++,x++ into x+=2? That’s normally fine, potentially disastrous if x is a memory mapped register on an external device.
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.
> Can it turn x++,x++ into x+=2
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
It’s clear by the language spec. It’s not clear based on how people want it to work or think it should work. And the inevitable stream of comments complaining about C compiler optimizers every time this gets discussed tells us that people are not willing to just consider where the language spec draws the line.
More like code that falls through might be reordered in the binary and the C abstract machine has no concept of that.
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.
Because doing so doesn’t change the semantics of the program as defined by the language.
If you open the possibility of other notions of “the semantics” besides what the language spec lays out, then changing those semantics is an inherent part of an optimizer.
What people (IMO fairly reasonably) want is a different C language spec with less undefined behavior and compilers that follow that spec. But people don’t think about it clearly and skip major parts of that picture when complaining about it.
We seem to agree.
Many people program for their hardware (what else can be actually tested) or maybe qemu or virtualbox or vmware or a specific external microcontroller.
Very few people want to program for the C abstract machine. The C abstract machine doesn’t even really have dlopen(3). It also has to be compatible with Harvard architecture, von Neumann architecture, two's complement signed machine word integers, one's complement signed machine word integers, and sign-magnitude signed machine word integers.
> The proper location of that line is not obvious.
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.
I’m not talking about whether a language has defined semantics. C’s semantics are plenty well defined, much better than the current crop of more modern languages that are mostly defined by their single implementation.
I’m talking about the question of what should be covered by the official semantics. That’s inherently subjective and a matter of opinion.
Gcc’s optimizer does not accept changing language-level semantics based on which optimizations are performed. That the above comment thinks it does means that the commenter has a different notion of what should count as “the semantics” from what the language spec says. Which is a perfectly legitimate opinion, but if you take that position then you have to accept that other people will have other ideas of what should count, and therefore any optimizer might change “the semantics” of code according to at least some of those ideas.
This is interesting
There is no difference.
Yes, I'm a C programmer, how did you know?
It doesn't sound like you are or you would know C doesn't define either precisely enough to make that statement true.
On the contrary, the vast majority of C programmers don't know C well enough to understand the difference between integers and pointers.
Using a tool doesn't mean understanding that tool, just means you know how to follow some repetitive processes over and over again.
They are definitely not integers on the Symbolics Lisp machine. The C standard allows for atypical representations. [u]intptr_t is optional for this reason.
Sure, but if you're not an embedded programmer, if you're not working with odd architectures, then the difference between pointers and unsigned integers of the same size in C on common current platforms' C ABIs, is minimal. Of course there are footguns here: you can't conjure up and dereference a pointer from an integer that isn't itself obtained from casting from a valid pointer.
C doesn't provide any guarantee that a pointer can be stored in an integer.
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.
> 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.
WG14 (the standards committee for the C programming language) does not agree with you.
https://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_260.htm
There is a counter example in the OP.
There's the voice of a C programmer who hasn't used hardware with a different word size to address space...
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.
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.
I agree, I have passed void* to the JVM by casting to int more often than I can count
You should read TFA.