143 points · by ingve · 9y ago · 113 comments
> Summary: This UB is probably not a problem in practice (even if it is moderately displeasing to some of us).
Since LLVM is mostly based around C/C++ semantics this actually turned out to be a problem for rust, because rust can encode diverging functions in its type system and assume certain code sections to be unreachable. If the compiler then optimizes out code and the unreachable (thus not-compiled) section is reached things explode.
If the compiler is able to do that analysis, why not flag the endless spin loop as a compilation error?
> Be knowledgeable about what’s actually in the C and C++ standards since these are what compiler writers are going by. Avoid repeating tired maxims like “C is a portable assembly language” and “trust the programmer.”
> Unfortunately, C and C++ are mostly taught the old way, as if programming in them isn’t like walking in a minefield. Nor have the books about C and C++ caught up with the current reality. These things must change.
The C standard even suggests, when defining undefined behaviour, that one of the possible options is "behaving during translation or program execution in a documented manner characteristic of the environment". If signed int arithmetic on the hardware wraps around upon overflow, then take that into account when optimising and don't assume it can't overflow. This is how C programmers want the language to work; compiler writers and standards be damned.
I've written plenty of Asm and also looked at as much if not more compiler output; and while the latter sometimes pleasingly surprises me, it's usually pretty evident that it was not generated by an intelligent entity. (And countless times, I've obtained size and/or speed savings by replacing the latter with what I would otherwise write.) My general impression is that there aren't enough highly-skilled Asm programmers working on compiler development --- there are many reasons I can think of for that, but one of the things I've always wished to exist is a simple, straightforward C compiler with "understandable" output and optimisation that creates results closer to what a human Asm programmer might write; with the associated optimisation advantages and predictability. This means not assuming anything just because the standard says so, but taking a more holistic (for lack of a better word) approach to compilation and optimisation.
A long-time favourite post on this: http://blog.metaobject.com/2014/04/cc-osmartass.html
Don't speak for all of us.
Some of us may take the language for what it is, instead of assuming it to be a "high level portable assembler" which it is not, but which a particular implementation of it may be, thanks to the standard leaving much up to the implementation.
It is this same leeway that (thankfully) allows smart optimizing compilers that can generate performant code for programs that are not omgwtf-optimized at the source level.
And it is this same leeway that allows very simplistic, naive implementations that do not go out of their way to perform crazy analysis to try and warn you about some corner case of undesirable behavior your code might hit.
You're right that it is the compilers can and need to change to accommodate different types of users. But I don't think every compiler should just go back to being a 1991 compiler; not every compiler needs to accommodate every user.
• Existing code is important, existing implementations are not.
• Avoid “quiet changes.”
• Trust the programmer.
• Keep the language small and simple.
• Make it fast, even if it is not guaranteed to be portable.
In pre-ANSI C, and C89 C interpreted in line with the Rationale, if you wrote ‘+’, the expectation was that you'd get the target machine's ‘add’ instruction, no more and no less. It might overflow, it might not; it might crash or hang your machine on overflow or trap values — but that is all your problem, not the language's or compiler's. The ANSI invention of ‘undefined behaviour’ can be considered a good-faith attempt to codify things like this, but botching it was one of the two great failures of C89.
I worked on a commercial compiler at the time, and I'm confident no one thought of C89 as a license to screw the customer.
"12. Trust the programmer, as a goal, is outdated in respect to the security and safety programming communities. While it should not be totally disregarded as a facet of the spirit of C, the C11 version of the C Standard should take into account that programmers need the ability to check their work."
I disagree. Undefined behavior is very important for optimization. See John Regehr's blog post on the topic [1], or any of DannyBee's numerous posts here explaining why GCC and Clang can and must exploit UB, etc. etc.
Dereferencing null or dangling pointers
Reading uninitialized memory
Breaking the pointer aliasing rules
Producing invalid primitive values:
dangling/null references
a bool that isn't 0 or 1
an undefined enum discriminant
a char outside the ranges [0x0, 0xD7FF] and [0xE000, 0x10FFFF]
a non-utf8 str
Unwinding into another language
Causing a data race
Note that all of these are inside of unsafe blocks. Besides unsafe blocks, Rust has no undefined behavior, and the compiler will prevent you from doing any of these things.It's true that unsafe is needed to get these problems, but they can also occur outside of unsafe blocks. See an example here: https://gankro.github.io/blah/only-in-rust/#unbound-lifetime...
Your own code need not use "unsafe" at all, but the program may still crash in your code if you called some function that internally does unsafe things to mess up your memory.
EDIT: I should say that the linked code does not crash, it only reads uninitialized memory. It seems to me like the same hole could be used to make things crash, but I don't have a ready-made example.
> unsafe does more than pollute a whole function: it pollutes a whole module. Generally, the only bullet-proof way to limit the scope of unsafe code is at the module boundary with privacy.
Correct me if I'm wrong but I don't think such a strong universal statement can be true (even outside unsafe blocks) because LLVM has corner cases of "undefined behavior". (And since Rust is relies on LLVM, ...)
Maybe it's more accurate to say that Rust minimizes undefined behavior as a design goal, or it doesn't have intentional undefined behavior.
And I am only mentioning the most known ones during the 10 years before C was born until early 80's.
Sure some of them also had safety issues like use-after-free, but not in the same amount as C.
Regarding those things that actually matter for programmer, following would be well-behaved in Rust (including unsafe blocks): conversion between types, integer arithmetic, pointer arithmetic (there are generally two variants of operations, one that essentially treats pointers as unsigned integers, and another one that behaves like in C with more opportunities for optimization). On the other side of the coin, in Rust mutable references cannot be aliased.
unspecified != undefined behavior
See this Stack overflow answer for an explanation: https://stackoverflow.com/questions/2397984/undefined-unspec...
Ie function arguments are still evaluated in some (possibly changing) order. C++ undefined behavior allows to eg format your hard disk or launch the nukes.
Afaik, kcc is also really good at finding undefined behavior. Regehr even wrote about it in the past (https://blog.regehr.org/archives/523).
Another reason to mention TIS-interpreter specially is that Pascal Cuoq (the co-author of this blog post) is one of its developers, and his livelihood depends on it being used.
The semantics of the language itself is more or less complete. On top of that, a sizable portion of the standard library is given semantics directly (e.g, malloc, setjmp, stdargs, I/O including input/output to FILEs, much of printf, etc. are all formalized in the semantics). There's even basic C11 thread support. All of this runs and can be reasoned about formally. I tried to give direct semantics to the things that couldn't be (easily) written in C, because much of the standard library CAN be written in C and so it isn't so critical that it's formalized.
To round out the library you can provide provide C implementations of any missing library functions at compile time (we provide some by default), and it will KCC those just like any other code. The resulting system is pretty good at catching undefined behavior, but it is super slow.
I'm not involved with the commercial version, but they offer a trade off: don't do any semantic checking inside standard library calls in exchange for faster execution times. My understanding is that instead of chugging through the semantics of printf for every bottle of beer on the wall, they just call out to a native of printf. This makes things a lot faster, but it's possible you won't catch as many problems. In general, the commercial version is trying to make using the semantics practical instead of "academically slow", which was all I managed :)
Any questions welcome.
That's different from "This is UB, and now I do ...".
In C `x + 1` is an undefined behavior if `x` is signed and overflows. Optimizer takes advantage of that for loop optimizations.
Rather they are written under the assumption that there are no UB in the program, and the chips fall where they may as these assumptions are used and propagated.
Absolutely not. Many instances of UB depend on runtime values. (E.g. overflows, out-of-bounds shifts, etc. etc.)
If people prefer "performance trumps correctness" and "winning compiler benchmarks is what counts" then they should happily keep getting exploited.
for many cases it is in fact equivalent to the halting problem. What you can do is check at runtime, which has performance implications (from trivial to expensive depending on the check).
And yes, if you want to allow manual allocation of objects and setting pointers to arbitrary objects, then your two choices are: 1) garbage collection 2) undefined behavior (use-after-free, double-free, dangling pointers, etc.)
int res(int a, int b) { return a + b; }
since it can be UB, for instance if a + b > INT_MAX.
Smart people with a ton of experience in C have already examined the possibility of defining a C dialect with much less undefined behavior in it. In fact, I believe it's been seriously tried more than once by independent groups. And the result has been the same each time; initial excitement and optimism gives way to total failure. It's simply way too deeply ingrained in the definition of C, backed by all the code in the world written in C. If you want less undefined behavior, your only choice is to leave C.
The reason that that doesn't happen, here as elsewhere, is that there are a number of specific compiler optimizations that rely on it being undefined. See GCC's -fwrapv flag.
It might be possible to do the same thing if you didn't check any code generated from macros.
Mostly new compilers now a days do handle such behavior with a compiler error or warning. So if you try to do an out of bound shift a new compiler might throw a warning, but according to the C standard it does not have to. In fact instead of throwing a warning it can wipe your complete hardware and that too is allowed according to the C standard...
In contrast there is implementation defined behavior, and unspecified behavior. Where the compiler developers have to document and take care of certain things.
I wrote a detailed article about the subtle difference you can check that out....
https://medium.com/@faizan10114/understanding-c-terminologie...
Right, for doing so needs to determine that this is happening, which neither GCC and Clang can do for fairly trivial cases like
for (i = 0; i < 100; i ++) {
... x << i ...
}UB is the result of C compiler vendors not wanting to give up on their precious optimizations or hardware configurations back when ANSI C was initially being done.
They could have done like in other languages and have ANSI C without UB, but then they would need to give up on some hardware features or lose in one or other benchmark.