Short of converting void* (or sufficiently large ints) to T* because of legacy API, I'm not sure reinterpret_cast has any portable use. But I'm sure you can NOT type pun with it if that would break the aliasing rules.
int* x = static_cast<int*>(malloc(sizeof(int))); #ifdef __cplusplus
#define strip_qual(TYPE, EXPR) (const_cast<TYPE>(EXPR))
#define convert(TYPE, EXPR) (static_cast<TYPE>(EXPR))
#define coerce(TYPE, EXPR) (reinterpret_cast<TYPE>(EXPR))
#else
#define strip_qual(TYPE, EXPR) ((TYPE) (EXPR))
#define convert(TYPE, EXPR) ((TYPE) (EXPR))
#define coerce(TYPE, EXPR) ((TYPE) (EXPR))
#endif
Very cool; you just use these macros for all your casts, and when building using a C++ compiler, you get additional diagnostics, like that you're accidentally stripping away a const-qualifier.https://docs.microsoft.com/en-us/cpp/mfc/reference/mfc-macro...
*(int *)foo = 0x12345678
is valid C++ and equivalent to using reinterpret_cast. Here, this is the same thing (in C++) as *reinterpret_cast<int *>(foo) = 0x12345678
It is not well-defined behavior.C++ has just divided the behavior of the (TYPE) cast notation in terms of more specific kinds of casts which are mutually exclusive. If a qualifier is being removed, you must use const_cast, which will not change type. The C-style-cast notation automatically chooses the right combination of C++-style casts to do the job. So for instance a C style cast from "const char " to "void ":
void foo(const void *arg)
{
static_cast<char *>(const_cast<void *>(arg));
}
The same thing can be achieved with just: void foo(const void *arg)
{
(char *) arg;
}
So the "bad" thing about the C-style cast notation then is that no matter how you change how the inputs are declared elsewhere, it will just "do what you ask", in the spirit of the C language. Whereas the C++ style casts will diagnose if the input types change so that they are not applicable.E.g. reinterpret_cast is not so powerful that it will strip away qualifiers:
void foo(const void *arg)
{
reinterpret_cast<char *>(arg); // error: stripped qualifier
}But this isn't just a person trying to properly understand the kernel code. It's someone who's trying to merge a change that's motivated by following a standard. If you're making a change to code based on a standard then yeah, you should know the intricacies of how the compiler implements that standard. Because, as Linus keeps coming back to, that's reality, that's what's actually going to impact users and other devs: the intricacies.
This change strictly makes the Linux kernel more in line with the C Standard, so it may compile better in CLang.
There's literally nothing wrong here. The code is more correct and more conformant with the C-Standard. So why is Linus against it?
Hint: he really isn't. Linus accepted the code anyway.
I dunno, the more and more I look into this, the more I feel like its just another example of Linus unnecessarily flaming someone on the developer communication channels.
This is from the overall discussion going on in this thread. Others have shown how union-aliasing fails to work in CLang throughout this thread:
https://news.ycombinator.com/item?id=17242457
By removing the non-standard GCC-specific union{} methodology from the code, the contributor necessarily improved portability to CLang. That's just the facts.
I think it's reasonable (and even important) for Linus to emphasize that the kernel is coded in GNU C, not strictly standards-compliant C.
That was super important as the compiler was first starting out, because (A) Apple's existing code was built with GCC, so it relied on GCC flags & extensions, and (B) for it to be a viable open source compiler, it needed to build large existing codebases which were already using GCC.
However, that doesn't mean that Clang will always continue to support every thing GCC does. Whether they by design or by accident, incompatibilities will arise. Of course, projects as tightly coupled to GCC as the Linux kernel might not care.
All type punning is in the hands of the implementation. The language definition provides the syntax for it, which has the virtuel that all code which attempts to do type punning expresses it in the same manner. However, the language leaves it up to implementations to define whether type punning works, and with what caveats and restrictions.
There is some hand-waving in the definition of memcpy so that copying compatible objects is well-defined.
Yes, you can. The behavior is implementation-defined but not undefined. (Well, it can trigger undefined behavior if the value corresponds to a signaling NaN, or if the implementation uses a nonstandard, non-IEEE format for doubles that has other "trap representations". But it's not otherwise undefined.)
The basis for this is that the aliasing rule has an explicit exception for reading or writing to objects using char pointers, i.e. byte-by-byte, regardless of the object's type. This exception is in both the C standard:
https://port70.net/~nsz/c/c11/n1570.html#6.5p7
and the C++ standard:
http://eel.is/c++draft/expr.prop#basic.lval-11.8
The memcpy function is defined as copying characters, so the exception applies to it too.
Both standards also explicitly define that objects (at least of POD types) have byte representations and those representations are implementation-defined (as opposed to triggering undefined behavior if you depend on them). For C:
> Except for bit-fields, objects are composed of contiguous sequences of one or more bytes, the number, order, and encoding of which are either explicitly specified or implementation-defined.
https://port70.net/~nsz/c/c11/n1570.html#6.2.6.1
C++:
If you memcpy a uint64_t to a double, the implementation is not required to notice that the double variable's value has changed; a subsequent access to that variable can continue to refer to a register. It's not a matter of what bit pattern was stored there.
> 3.1 > 1 access >〈execution-time action〉 to read or modify the value of an object
Thus, the requirement is symmetrical. The compiler must consider any char write as potentially aliasing a subsequent read (or write) of any type, unless it can prove non-aliasing without depending on type. And similarly, it must consider a write of any type as potentially aliasing a subsequent char read/write.
There are a lot of sharp edges to C/++ and the community really is hurting for a good static analyzer that can at least save you from most of them.
[1] almost always, because while a simple unaligned mov is safe, if the compiler unrolls and vectorises your loop, it is free to then use aligned sse read instructions, assuming that your int ptr is aligned, because pointers must be aligned according to their type. Then your program crashes, but only in optimised builds.
If you need type-punning, use a union. Done and done.
You're just making an appeal to authority here and deciding that The C++ Standards Committee (who give us one official way to do this) is a better authority than The GCC Authors (who give us another).
And that's shortsighted and silly, because GCC (being working software) is if anything a more reliable and more accessible authority than any spec-writer will ever be. That's exactly the point Linus was making, albeit with more profanity.
Well, until you decide to use CLang, ICC, or Visual Studio or something out there. The reason why people follow the standards is because they want their code to correctly work on more than just one compiler.
Fundamentally you're still missing the point. Standards are important. Features are more important. The best standards are ones driven by features and not paper. GCC has been a far better, more innovative, and more practical driver of "standards" than any committee.
Lets break it down.
In C, type-punning is NOT part of the language. Its technically "undefined behavior". There's an expectation that when you do:
A little-endian machine will pass this assert. But this isn't guaranteed by the C standard! This is "undefined behavior". The C-standard allows a C compiler to assume that foo[0] and foo[1] are still == to 1 and 2 respectively. Which would cause the assert to fail. In GCC -O2 or -O3, this may happen, depending on how registers get mapped to the variables. (The canonical memory location changes, but should registers be updated when optimizations are enabled??)When an optimizer can assume, and when it can't assume, "aliasing" is very much an undefined behavior within the C language.
-------------
In effect, Linus knows GCC inside and out. GCC guarantees that unions will ALWAYS work for this aliasing problem. But this requires knowledge above and beyond the C Standard.
Linus may be "hating" and "criticizing" the standard in this case. And I guess there's certainly a gap. But the general expectation that everyone knows the intricacies of GCC to properly understand the kernel code is misplaced IMO, and goes back to "Angry Linus yells at random dev unnecessarily" territory for me.
And instead of simply explaining this VERY simple fact (although super-obscure) that GCC makes unions safe against aliasing issues at the compiler level... Linus yells at the dev. Not fair IMO.