53 points · by goranmoomin · 6y ago · 99 comments
PS: some pragmatic cleanup of UB and IB in the C standard would be welcome though.
UB is a feature, not a bug. So you don't really "clean" it up. Cleaning up of UB means a lot of overhead for programs.
for (i = 0; i < *len; i++)
array[i] = 0;
without having to check on each iteration whether len secretly points inside the array and got modified by the loop. It would be better if this were not a heuristic and there were clear compile-time information saying for sure that this optimization is safe.In case of similar but where it’s float array[N] etc then compiler can assume that they do not alias.
Some examples:
1. When C came out, you couldn't assume a two's complement machine. So some architectures would yield different results on signed over/underflow than others, and some architectures might trap on overflow. Hence, signed overflow is undefined in C.
2. Did you know the Lisp Machine had a C compiler? It did. Because pointers on the Lisp machine were tagged and bounds-checked to ensure memory safety, this compiler implemented C pointers with fat pointers, containing a reference to an object and an offset within that object. Most machines you are familiar with allow indirecting through arbitrary integers; the Lisp Machine is an example of one that does not, trapping on invalid pointer accesses. Having C and C programs available in both environments mean that indirecting through a pointer that does not point to or inside some pre-existing static or dynamically allocated object is undefined.
3. Operating systems with virtual memory can arrange things such that indirecting through 0 (NULL) will raise a segmentation violation in user code, guaranteeing a pointer value that is always invalid -- but inside the kernel you may want to access memory location 0. So accessing null pointers is undefined.
By leaving these undefined, you are not committing implementors to adapt the abstract machine to the underlying hardware in cases where hardware can widely differ, allowing for simple implementations that yield fast code on all architectures they compile for yet still allowing for a useful subset of C code to be 100% portable.
MIPS compilers for C emit "addu" instructions for signed integer additions rather than using "add", to avoid overflow traps.
Using unsigned arithmetic for signed is not just so that C programs relying on the behavior do not blow up. When overflow behavior is reversible wraparound, the compiler more freedoms in rearranging a calculation. Suppose the programmer has written some a + b + c, and ensured that there is no overflow (when it's added left to right, as the abstract semantics says). If the addition mechanism has reversible overflow, the compiler can rearrange it to do the additions in any order. The result will be the same, correct one that (a + b) + c would produce.
But the idea that two's complement itself "wraps around" is mostly a myth. Two's complement has a fixed range of representation, and a result of adding two elements from that representation can be out of that range. In that case, the truncated value whose bit pattern corresponds to the unsigned arithmetic is not the correct result.
Or just does what C does, make it UB and the programmers will be aware of implementation of overflows and won't suffer because of added checks. They will do the checks themselves if they want and handle their numbers with care
Imo the answer always boils down to performance. Java has no UB yet it works on billion devices (citation needed). It is doable, just costly.
Even if such exotic hardware is still around, the only thing that would change is that C compilers supporting this hardware couldn't call themselves "ISO Compliant" anymore, the users of those compilers wouldn't lose anything.
You'd hate a compiler where this has silly overhead:
for(int i=0; i < n; i++) arr[i];
That's because 64-bit addressing modes don't overflow the same way as signed 32-bit ints. But signed overflow being UB gives compilers license to ignore the difference and generate code that makes sense.The real problem is that C is too bare-bones and lax to be able to contain or avoid UB in day to day programs. For the aforementioned overflow gotcha, there's no way to enforce use of size_t for indexing. There's no `checked_mul(a,b)` to easily avoid signed UB. You have to make the check yourself, and if you're not careful, that check will be UB too. malloc() makes you multiply numbers often, exactly where it's dangerous. And on top of that implicit integer conversions can make unsigned arithmetic surprisingly signed.
There's surely cases where it would be hard to suggest a "equally efficient without UB" replacement (eg when it wants to fuse two i64 into one), but it feels like the current position is too far on the axis of "provided with suspicious code, the compiler should just make that garbage run as fast as possible and call it a day"
This article [0] goes into a bit more detail.
[0]: https://gist.github.com/rygorous/e0f055bfb74e3d5f0af20690759...
Nobody during C89 formulation realized that it would end up “a license for the compiler to undertake aggressive optimizations that are completely legal by the committee's rules, but make hash of apparently safe programs” that “negates every brave promise X3J11 ever made about codifying existing practices, preserving the existing body of code, and keeping (dare I say it?) `the spirit of C.'” If they had, the response would have been that “[UB] must go. This is non-negotiable.”
I’m not quite sure what the compiler is supposed to do in that case. Insert nullchecks by itself to avoid crashes?
As soon as your first pass decides to rely on the presence of the dereference as a reason for removing the null check, the dereference needs to be flagged as critical, such that it cannot be removed by a subsequent pass.
Better still, if the compiler does try to remove something that was relied on by an earlier optimization step, alert the user that something is probably wrong with the code.
Also, this would prevent one of the main benefits of function inlining. Once you have inlined a function, the values of some of the parameters may be known at compile time, resulting in lots of those if(0) parameters. But that is something that was relied on in previous passes, even though it is known to be a static value in the current pass.
How can this be: C has a standard, when many other languages do not. Thus C is "more defined" than other languages. Yet somehow it ends up being less defined.
If C had no standard, it would be defined by its implementation, just like many other languages. But because it has a standard, it has undefined behavior.
The real trick is that without a standard, implementations have to be bug-compatible. They're too defined! The purpose of a standard is to define them less.
If you get Godbolt to run the program and show the output, you'll see it change with GCC version.
Obviously what is "sensible" and what is "surprising" is subjective.
int foo(FILE *f) {
int val;
fread(&val, sizeof(val), 1, f);
return val;
}
Closer reading of the spec says something about it being fine to cast, say, an int* to a float* and then cast back before dereferencing it. In this example, we're OK, because we don't reference via the void* . But the fread implementation must do, right?I'm left feeling like it is impossible to implement fread() in C and that the standard library's API is no longer considered a good example of how to construct an API.
I guess the original motivation for it being UB to cast is to do with alignment constraints on some hardware. For example, a machine might be able to read an int8_t from any alignment but might require 4-byte alignment for int32_t. If so, then casting a non-aligned int8_t* to int32_t* and deferencing it would indeed fail on that hardware.
But some would argue that it is not right that GCC 7 breaks such code on a machine where that problem doesn't exist.
People should write these bits in assembly (as little as possible, but doing the casting and things), and then keep their C code well-defined using these low-level library routines.
The fread implementation sees dest as a void pointer and will access it going through char*, which is explicitly allowed.
Compilers incorporate inferences that can be made by assuming UB doesn't occur into their optimization because it improves code generation of correct programs.
I wouldn't say it's a minuscule factor in my daily work, as OP put it, but it's not something to agonize about if you stay mindful of avoiding common undefined behavior pitfalls. It would be very helpful if compilers were better about warning you when you're venturing into UB, but that's a different topic.
1: You can even get the shirt: https://teespring.com/shop/undefined-behavior-shirt
Many people say this but nobody "literally" believes it.
It's a way of expressing the righteous dominance of one person or group's attitude towards reasonableness over another's. In a way that forestalls argument.
"Literally anything" could literally mean global thermonuclear war.
- More applications are talking to the internet and being exposed to malicious input. There's also more money to be made in finding exploits, and more people and governments looking. At the same time, fuzzing techniques are getting dramatically better.
- Applications are more likely to run across different architectures (mobile) and different compiler versions (faster pace of compiler development), leading to more opportunities for "something weird" to happen. Multithreading is also more common.
- Memory-safe languages have taken a larger market share, and the popular attitude towards memory safety issues is changing from "bugs are a fact of life" to "this is a drawback of specific languages".
For the most part, avoiding UB is common sense when you grasp the basic abstract C memory model - types of storage and their lifetime, avoiding out of bounds array access, keeping track of the lifetime of all allocations, etc.
Do all C programmers know what strict aliasing means?
How about pointer provenance?
Have they memorized integer promotion rules?
These are all potential sources of undefined behavior that can lead to catastrophic results.
I bet most experienced C programmers with decades under their belt would fail one or more of these tests.
https://raphlinus.github.io/programming/rust/2018/08/17/unde...
[0] https://blog.llvm.org/posts/2011-05-13-what-every-c-programm...
[1] https://blog.llvm.org/posts/2011-05-14-what-every-c-programm...
[2] https://blog.llvm.org/posts/2011-05-21-what-every-c-programm...
In a past life, I depended on signed overflow to detect out of bounds memory allocations. That kind of stuff gets compiled away these days, you need to be cleverer to detect when the user is deliberately trying to invoke UB. And because the compiler doesn't believe in UB, there's the risk it's going to remove your detection logic.
IIRC C++ just decided that signed numbers are two's complement and that's that. C could really use similar thing.
Signed integer overflow is still undefined in C++.
Quoting from the abstract of that talk: "... preserving source-level dependencies through to the generated CPU instructions is achieved through a delicate balance of volatile casts, magic compiler flags and sheer luck. Wouldn't it be nice if we could do better?"
In my years of working with C its always the 'look how smart I am code' causes issues.
Keep it clean and simple. Avoid complexity and fluff features of C. And you will not going to have deal with exotic bugs.