173 points · by Mindless2112 · 10y ago · 173 comments
You know, in my experience, things would be great if people actually turned on warnings. I write all my new code with -Weverything with a few noise categories turned off. Everybody should build code at this level from day 1.
[0] http://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html
On the project I run, the CI will reject your code in CR if it doesn't compile under two different compilers with all but a handful of warnings turned on as errors, runs and passes tests, and passes various linters, including a check for undocumented types, variables, parameters and return values. IMNSHO, every project should be like this. Once it's setup, it's a breeze and doesn't impede development speed at all.
At home, I turn on -Wall -Wextra for starters, enable about a dozen more for good measure, with -Werror as the pièce de réisistance.
But why can't it just produce something different on each system?
Allow me to call it as I see it: the modern interpretation of undefined behaviour is bullshit. What compilers do today should be the recourse of absolute last resort, and the sort of thing that makes its authors feel bad. But it seems to be treated as a matter of course.
I don't know what to say.
Mandatory reading: http://robertoconcerto.blogspot.co.uk/2010/10/strict-aliasin... ("Everyone is fired"); https://groups.google.com/forum/#!msg/boring-crypto/48qa1kWi... ("these people simply don't understand what most C programmers want"); http://blog.metaobject.com/2014/04/cc-osmartass.html ("please don't do this, you're not producing value")
int main(int argc, char **argv) {
uint32_t x = (uint32_t)0x12345678<<(uint32_t)32;
printf("x<<32 = %x\n", x );
}
(Almost all compilers make a warning about the shift size)
gcc 4.9.2 on Debian x86: 0x0
gcc 4.9.2 on Debian x86, -O3: 0x0
clang 3.6 on Debian x86: 0x0
clang 3.7 on Debian x86: 0x0
gcc 4.9.2 on Raspbian ARM: 0x0
tcc 0.9.27 on Raspbian ARM: 0x0 NO WARNING
tcc 0.9.27 on Debian x86: Segmentation fault NO WARNING
clang on El Capitan: 0x5a788cb0
clang on El Capitan, -O3: 0x54049be8That's easy to explain. The optimizer replaced the instruction with an undef [1], which has no live range. So it printed the value of some random register, which happened to be 0, 0x5a788cb0, or 0x54049be8.
Here's a good example from the llvm blog: ( http://blog.llvm.org/2011/05/what-every-c-programmer-should-... )
> Signed integer overflow: If arithmetic on an 'int' type (for example) overflows, the result is undefined. One example is that "INT_MAX+1" is not guaranteed to be INT_MIN. This behavior enables certain classes of optimizations that are important for some code. For example, knowing that INT_MAX+1 is undefined allows optimizing "X+1 > X" to "true". Knowing the multiplication "cannot" overflow (because doing so would be undefined) allows optimizing "X*2/2" to "X". While these may seem trivial, these sorts of things are commonly exposed by inlining and macro expansion. A more important optimization that this allows is for "<=" loops like this:
> for (i = 0; i <= N; ++i) { ... }
> In this loop, the compiler can assume that the loop will iterate exactly N+1 times if "i" is undefined on overflow, which allows a broad range of loop optimizations to kick in. On the other hand, if the variable is defined to wrap around on overflow, then the compiler must assume that the loop is possibly infinite (which happens if N is INT_MAX) - which then disables these important loop optimizations.
If a programmer writes "X+1 > X", chances are this is an overflow check. Doing this is perfectly defined by the standard if X is an unsigned integer, but not if it's signed. That's what doesn't make sense, since they could've made the unsigned case undefined as well.
which allows a broad range of loop optimizations to kick in
What sort of optimisations exactly, and just how significant are they? I don't believe C should be a language where the compiler does all sorts of high-level optimisation; it should be a straightforward "do what I say" type of language where you get almost exactly what you write, and the only optimisations should be at the level of things like instruction selection --- the optimisations that a programmer would not be able to do at the source level.
In that case, you're asking for easily 3x-5x less performance in the software you use every day, if not more. You can get essentially this by turning on -O0 and compiling, say, Firefox. This is done in debugging, and it's a terrible browsing experience.
Compiler optimizations are really, really important. CSE, GVN, LICM, SROA, etc. aren't done for fun. They're done because modern software depends on them to be fast.
Writing low-level "post-optimized" code is at odds with good engineering practice. If you can't factor things out into functions and count on an inliner to inline them and then propagate away constants, SROA away intermediate structures, etc. then you're essentially telling programmers they can't factor code out into functions. If your compiler refuses to do the Hacker's Delight integer divide optimization (which, by the way, you need good constprop to make good use of a lot of the time), then you're telling programmers they have to get out their copy from their bookshelf and compute the magic number every time they want to integer divide fast (especially on ARM). This sort of thing puts a huge drain on developer productivity and maintainability.
Well, if you could remove one instruction per loop on most computers (especially conditionals that could cause a branch mis-prediction), the effect of that in terms of performance is pretty staggering. Instead of thinking of it as an optimization, think of it as a check that doesn't need to be inserted into the code. If you can tell the compiler "I promise I won't overflow this variable", that's a lot less error checking it needs to insert on every iteration.
> I don't believe C should be a language where the compiler does all sorts of high-level optimisation; it should be a straightforward "do what I say" type of language where you get almost exactly what you write
Well, you could just compile with -O0 then. I don't necessarily agree with C on this, but it's pretty clear the community has made the decision to prioritize speed over safety. Nothing wrong with that, but if safety is your priority you should probably look at things other than C. Even if you were to define undefined behavior, it's a spectacularly dangerous language.
If the programmer writes
for (i = a; i < b; i++)
then it's not clear if you need to check 'i' for overflow; Assuming that 'i++' is greater than 'i' allows the compiler to, say, unroll the loop.It does make sense if you understand the historical context: There was a time when some processors still used ones-complement representation for signed integers. That's why the highest performance choice of instructions for signed integer addition would give different results in the overflow case on different processors. Which is why the standard leaves the behaviour undefined, so that compiler writers can choose the instructions that make for the fastest signed addition on the respective target, while programmers can not rely on any specific behaviour.
None of that applies for unsigned integers, and also, the common overflow behaviour of unsigned integers is commonly used intentionally for many types of computations (such as in cryptography), so it is both useful and it doesn't cost anything in terms of performance to define the semantics of unsigned overflow.
They might not insist on exactly this, but they already leave this sort of possibility open by suggesting that undefined behaviour could result in the program behaving "in a documented manner characteristic of the environment".
If the standard writers' hands were tied by having to cater for every system they'd ever heard of, even the stupid ones where shifting by 32 (or whatever) results in rand() (or whatever) - implementers' hands are not! They have only one system to think about!
If that system happens to be one of the stupid ones - well, anybody working on it will have exactly the same problem.
But if it isn't one of the stupid ones - why do they insist that their users should behave as if it is?
There's an argument to be had that some undefined behaviour should rather be unspecified or implementation-defined, but compilers making use of it for aggressive optimization? That's by design.
Quoting another article by John Regehr:
My view is that exploiting undefined behavior can sometimes be OK if a good debugging tool is available to find the undefined behavior.
Thus -fsanitize=undefined.
I would expect that a single-pass compiler like gcc would look at the toolchain's target ISA, compare it to these switches, and then generate extra shim code to adapt any cases of target-arch-does-X into code-does-Y-on-X, while letting do-X-on-X just translate directly. Basically the same way floating-point code gets compiled: architectures that support it get it, architectures that don't get a shim.
Meanwhile, a two-stage compiler with an intermediate representation, like clang, should generate IR with granular types specifying the chosen behavioral semantics on each operation. The second step in such a toolchain becomes much more formalized: rather than taking code that can contain undefined behavior as input, and then "defining" it during translation in some random heuristic manner, you just take code that already specifies the behavior it wants in full, and then attempt to generate target-arch code that does whatever it says in the most efficient manner possible while not breaking any of the guarantees the IR asks for. In other words, your code-generation stage becomes a static recompiler, like this one[1] for the NES ISA.
And you can always specify a switch at code-gen time that will error out the compilation if you've done something that has caused shims to be inserted. Or even a switch to throw away the behavioral semantics the IR asks for and substitute your own, like happens in most performance-focused emulator software.
Possible undefined behavior ranges from ignoring the situation
completely with unpredictable results, to behaving during translation
or program execution in a documented manner characteristic of the
environment (with or without the issuance of a diagnostic message),
to terminating a translation or execution (with the issuance of
a diagnostic message).
Permit me to suggest that when there is a choice between making things behave in a documented manner characteristic of the environment, or something else - don't go for the something else.Rejecting translation outright aside, undefined behaviour is the strongest language the standard uses for illegal constructs. I do not see it as undefined in the sense of lacking a common definition (eg is 0 a natural number, or not) but something that is undefined the way 0/0 is undefined in maths.
In a way, the criticized behaviour of aggressively opimizing compilers is a consequence of ignoring the situation completely with unpredictable results. It's the same line of reasoning that makes restrict useful, just on steroids.
It could. That is indeed how Rust, for example, defines it.
But in C "unspecified values" have a way of turning into undefined behavior really quickly.
Here's an actual bug we have in Rust [1]:
let index = 1.04E+17 as u8;
let array = vec![1, 2, 3, 4, 5];
println!("{}", array[index as usize]); // segfault
Why does that segfault instead of emitting a safe panic? Because the IR looks something roughly like this (in C notation): double tmp = 1.04e+17;
uint8_t index = (uint8_t)tmp;
vector *array = make_a_vector();
if (index >= array->length)
panic();
printf("%d\n", array->ptr[index]);
The optimizer correctly determines that the cast from double to uint8_t results in an undefined value. In LLVM terminology, undefined values can arbitrarily change value over their live range, and this is allowed per the C specification. So LLVM is allowed to replace the conditional "index >= array->length" with "false", and this is indeed what it does, leading to this code: double tmp = 1.04e+17;
uint8_t index = (uint8_t)tmp;
vector *array = make_a_vector();
printf("%d\n", array->ptr[index]);
And with that, LLVM optimizes out our bounds check, and safe code is able to perform arbitrary memory reads and writes. Note that all we needed was an unspecified value resulting from a floating point cast!The fix is probably going to be to stop using LLVM's floating point conversion instructions and to instead use some "safe conversion" intrinsics that we'll define.
> What compilers do today should be the recourse of absolute last resort, and the sort of thing that makes its authors feel bad. But it seems to be treated as a matter of course. I don't know what to say.
You might think that I would think this way too after fighting bugs like the above, but I actually don't. I appreciate the performance that undefined behavior brings to C, and I think we'd have much slower programs without it. Undefined behavior resulting from strict aliasing is the reason why a for loop setting an array to zero can optimize to a 10x faster memset, for example. And heavily inlined series of functions, as well as generic libraries like the C++ STL, frequently require these optimizations to get reasonable performance. I think it's not an exaggeration to say that much of the software performance we take for granted—stuff you care about, like codecs, games, browser implementations—is the result of optimizations that are enabled by undefined behavior.
More specifically, the problem is that processing this operation is not producing error; it instead propagates the problem and produces invalid code. That's a situation where nobody wins.
I think we'd be better off if many undefined behaviours were instead implementation defined. If, instead, LLVM had converted the double to some integer and then chosen the lowest 8 bits from that integer, we'd have gotten some random value - but at least the comparison wouldn't have been ignored. The comparison should only be ignored if the compiler can prove that the value definitely lies within the range; if it isn't sure, it can't remove the comparison. The programmer wrote it for a reason; ignoring the intent of the programmer is a bug.
On strict aliasing, I'm against it without explicit opt-in over a delimited subset of source code. I understand that using & is going to harm the performance of my code; I think that's an acceptable tradeoff for more predictable behaviour. If it harms the performance of C++ vector iterators, for example, I don't care: strict aliasing rules are a worse cure than the disease of C++'s poorly thought out abstraction tools. Let a subset of the program follow Fortran rules if it's required.
I believe that you and others think that's an acceptable tradeoff. At the end of the day, though, most people want C compilers to produce the fastest code possible. Compiler authors are just responding to what users want. The example below is actually an excellent example of this.
> If it harms the performance of C++ vector iterators, for example, I don't care: strict aliasing rules are a worse cure than the disease of C++'s poorly thought out abstraction tools.
It's not just C++. Consider (from Chris Lattner's blog post):
float *array;
void zero_out() {
for (int i = 0; i < 100; i++)
array[i] = 0.0;
}
People saw compilers missing the optimization to compile this to a memset, and filed bugs against them. As a matter of fact, though, that is an illegal optimization to make unless the compiler is able to take advantage of strict aliasing. That's because, absent strict aliasing, array[0] could legally be a type-casted pointer back to "array" itself, even though almost nobody would actually write that code.The reason why compilers implemented strict aliasing rules is that their users demanded that they fix "optimizer bugs" like the one above. And, honestly, I can't blame either the compiler developers or the users. Strict aliasing ends up being one of the things that's often important for performance. The problem, if anything, lies with the C language.
IMO the best thing would be if the compiler would insert code to print to screen a warning and exit the program, if it comes across undefined behaviour. (This is different from sanitizers, that check for all places whether undefined behaviour will occur).
(This is explicitly allowed by the standard. Consult its definition of undefined behaviour.)
Why not create a compiler that does what your users want? Why spend your time creating a stick to beat them with?
Then again, I think languages shouldn't have undefined behaviour and that programmers who use languages with undefined behaviour deserve what they get.
See also here:
http://blog.llvm.org/2011/05/what-every-c-programmer-should-...
a->thing = 42;
if (a == NULL) {
return;
}
Obviously that code is wrong; I should check for NULL before using a. But because I dereferenced a, the compiler can assume a must not be NULL, and just removes the null check as dead code. This scenario has caused problems in the kernel, and made bad bugs even worse.At runtime we have the clang and gcc undefined behaviour sanitizers, but they aren't free in terms of performance.
The situation gets worse when we start talking about a friendly semantics for races and OOB array accesses.
I don't have anything to say about races, but OOB array accesses should simply do what you'd expect the hardware to do: attempt to access memory at the location the array indexing equation gives. It may segfault, or it may access some other contents in memory. That's what any C programmer would probably expect.
if (a > 1)
b++;
array[b] = 0;
c = a + 10;
Under your suggested semantics, can the compiler use the value loaded from `a` at the point of the if() statement to calculate `a + 10`? Or does it have to emit a reload of `a` after the array access, in case `array[b]` was an OOB access that overwrote `a`?The compiler's implementation defined behavior would simply be "if you tell me to write a value to an address, I'll create assembly that tries to write that value to that address". That's all. If this address is outside the allocated range of the array, there is no guarantee that it's safe that write this value, or that it won't break something else.
So in your example, no, the compiler is not required to reload 'a'. The compiler is allowed to presume that the array[x] syntax will have no affect on the value of a local variable, whether that variable is stored in a register or on the stack. The compiler is not guaranteeing safety, just best effort.
if (a > 1)
b++;
array[b] = 0;
if (a > 1)
foo(a);
We might see foo() called with argument 0 when that's apparently impossible - the OOB write has apparently "reached forward" (it can also "reach backward").This is why it ends up just being "undefined behaviour" - to do better either you have to somehow exhaustively document all the kinds of weird things that can happen ("it writes to the memory" isn't enough, because of the way that can interact with the optimiser) or you have to unreasonably constrain the optimiser.
I don't have anything to say about races, but OOB array
accesses should simply do what you'd expect the hardware
to do: attempt to access memory at the location the array
indexing equation gives. It may segfault, or it may
access some other contents in memory. That's what any C
programmer would probably expect.
The problem is that defining OOB array access this way means throwing out pretty much every semantic guarantee from the rest of the language. There is really no friendly way to define writing an arbitrary value to an arbitrary location. By way of example, pretty much every (non-embedded) C implementation since 1972 supports recursion by writing an address of code to execute to memory. If you have semantics allowing a programmer to write to that location, then you can start executing literally any piece of code you want to. On some platforms like x86 you can execute starting in the middle of an instruction.For example, "return" would stop meaning "execution resumes at the callsite of this function" and instead mean "execution resumes at the callsite of this function or maybe somewhere else if someone wrote to arr[-5]". The article makes a big point about the controversy of giving memcpy() the semantics of memmove(); how would you like the semantics "memmove() unless a concurrent thread is running, in which case anything might be written to dest and src might be overwritten."
... so, why not do that then? We have, for perhaps the first time in 40 years, a candidate for a systems language that can truly replace C, that has truly different semantics (i.e., not C++, which is still profoundly C with a lot of stuff bodged on the side). I'd suggest trying to use Rust, and working with that team to nail down whatever remaining issues may yet be undefined in Rust that may cause trouble in the future. Whatever remaining practical problems there may be (and my impression is that that isn't really a long list), work on resolving them.
Again, I am not being sarcastic or cynical; it is truly my estimate that it would be easier to get people behind that than to fix C at this point. Probably by a good two or more orders of magnitude. Obviously we're not going to rewrite all existing code. Obviously there's a lot of code still to be written that is so deeply embedded in C that there's no practical alternative to adding more C to it, even in a world of FFI support and such. But if the people who care about the idea of BoringC or Friendly C start getting behind Rust, getting their hands dirty with it, and doing what the Mozilla project is doing to find places where they can start slotting subsystems in cleanly to existing code bases, you may just be able to start creeping out of the mess we're in now.
And... who knows. If this becomes acceptable, then generally considered a good idea, then best practice, then perhaps even something you need to do unless you want people to think poorly of you... perhaps real change will prove to be less intractable than we thought. People consistently overestimate change in the short term but underestimate in the long term. It is, perhaps, not too much to hope for that huge swathes of our fundamental systems could be running on Rust in 20 years, instead of C.
So I'll reemphasize once again... yes, I know I'm proposing a staggeringly enormous change. The only thing that it has going for it is that I still think it's easier than the staggeringly-enormous-squared other choice.
Something's gonna happen. After all... what's the alternative? That C is still the foundational language of the entire computing world in 2035?
Seriously?
Honestly I think your view of technological adoption is fairly naive -- I don't see much content here other than "everyone get behind Rust!".
IMO the more realistic approach is a systems approach: make it so that badly written C code doesn't completely hose your system. I like the application compartmentalization work (Chrome style, DJB style), and capability work like Capsicum. And LangSec work in making safe parsers. The trusted computing base has to be reduced. Not every line of C code should run in a trusted context!!! Principle of least privilege. We know (or should know) all this stuff.
That is many of orders of less magnitude less work / cost, and I think actually feasible. Coherent and secure systems architecture is more achievable than everybody writing perfect C code or everybody switching to another language.
Another thing the Rust community should be working on is easy and efficient IPC with C programs. So you can rewrite a secure core in Rust and communicate with legacy C/C++ running in an untrusted OS context.
And also fixing the mess that is Linux containers, so it isn't so difficult to secure them (i.e. see Docker's security issues)
I think you may not have seen much content because you weren't looking for it very hard; for one thing, you seem to have simply instantiated for me an instance of the fallacy I mentioned. People overestimate change in the short term, but underestimate it in the long term.
"IMO the more realistic approach is a systems approach: make it so that badly written C code doesn't completely hose your system."
We've been doing that for 40 years. Since it is already a sufficient problem that C can hose the process it is in, even perfect process isolation is not sufficient. Building all the protection code in C also has a track record of demonstrated failure. You're basically proposing we continue doing the exact same things that are also the reason we're having this conversation in the first place. If this plan worked, we would not even be here.
I'd also point out that if we're talking track records, capabilities have failed pretty comprehensively to date.
"We know (or should know) all this stuff."
And yet, here we are. Theory says this ought to work. Reality says it isn't. Reality wins.
"Another thing the Rust community should be working on is easy and efficient IPC with C programs. So you can rewrite a secure core in Rust and communicate with legacy C/C++ running in an untrusted OS context."
More evidence that you "didn't see much content" in my post because you weren't looking for it is that I already said that.
Finally, I'm arguing the first derivative and you're arguing the zeroth. I think it's perfectly feasible that much more of the code written in 2035 will be in Rust than in C, and people will look at you funny if you insist on writing a new subsystem in C. If you think that's unthinkable, well, that's the long-term underestimating fallacy I was talking about. Since, as I already mentioned in my post, Mozilla is already starting to do this it's hardly unthinkable that by 2035 everybody will be.
With respect, you clearly read what you pre-judged and expected to read in my post, not what I actually said. If you found that to be "naive", well, I don't think that comes from me.
Application compartmentalization is certainly difficult in practice, and should be made easier, but it is deployed and it's a lot easier than rewriting all code in a different language.
ffmpeg is a great example. It is hideously broken, with thousands of likely security bugs [2]. Now let's compare these two strategies:
1) Rewrite EVERY video codec in Rust
2) Reuse existing code, but run it in a completely
untrusted process (no OS privileges), and only
communicate with IPC.
The claim is that #2 is much more achievable than #1. You could say that #1 takes orders of magnitude more work, which is true, but that doesn't even quite capture it -- it actually scales differently because for #2 you do constant work and get security for ALL video codecs. It's O(1) vs O(n).Why not get secure foundations by 2025 instead of 2035? What I'm arguing for is a hybrid, heterogeneous architecture -- instead of rewriting 100% of code in Rust, rewrite 5% in Rust and isolate the remaining 95%. That gets you a better result which much less effort.
These techniques predate modern browsers -- they are used in qmail and djbdns. [3] [4]
I agree with the idea that most people underestimate change in the long term, but that is orthogonal to my point -- we get get secure systems faster with a different technique, in a shorter time frame.
Also, if you look at the code we're using today, it is perfectly reasonable to conclude that in 2035 we will be using a lot of the same code. People are still using Linux (1991), GNU tools (started in the 80's), Python (1990), Perl (1985), PHP (90's), etc. In 2035 is undoubted we will be using code from 2015 -- in fact it is likely we will be using code from 1985 in 2035. Those are the economics of software. Stable code is extraordinarily valuable and long lasting.
But the good news it that we can be running C code from 1985 in 2035 and still have secure systems!
I apologize for saying your post was naive, but I can tell from your original post and response that you haven't worked with security or operating systems very much. I have some impatience because the "rewrite everything" response reminds me of people who think they can rewrite an old codebase do better, when in reality they would end up with something worse [5]. There is a lack of subtlety and lack of understanding implied when you want to start completely from scratch.
Browsers like Firefox and Chrome didn't even start from scratch. Firefox was derived from decades-old netscape code, and Chrome reused Webkit, which was derived from Konquerer. Google has infinite money, but didn't rewrite Android from scratch -- it is based on Linux and hundreds of other open source projects. Code lasts A LONG TIME -- simply suggesting that everyone rewrite it is not helpful. It's an economic impossibility.
[1] Deployed by code you are using every day: (Chrome, Firefox, IE, Safari, etc.)
https://en.wikipedia.org/wiki/Process_isolation
http://www.chromium.org/developers/design-documents/multi-pr... https://developer.mozilla.org/en-US/Firefox/Multiprocess_Fir...
[2] https://googleonlinesecurity.blogspot.com/2014/01/ffmpeg-and...
[3] http://cr.yp.to/cv/activities-20050107.pdf -- see "extreme sandboxing".
[4] http://cr.yp.to/qmail/qmailsec-20071101.pdf
[5] http://www.joelonsoftware.com/articles/fog0000000069.html
I thought Chromium had a library for this (for multiple C++ processes), but I guess it is sort of ad hoc now?
https://www.chromium.org/developers/design-documents/inter-p...
https://www.chromium.org/Home/chromium-security/education/se...
C has the use-case of zero-dynamic-allocations. AFAIK, Rust is not very compatible with that mode of use.
Lots of intrusive nodes pointing freely at one another, is an example. I've heard some Rust libraries approximate intrusive allocations almost perfectly, but not quite perfect.
Bugs and undefined behaviour is too easy for programmers to write when the level of abstraction is low. Too much boilerplate to get wrong. But too low a level is also bad for an optimizer. It cant assume it understand the programmers intention with the code.
C++ tries to fix some of this by creating a higher level language and library on top of C. Low level code is considered unsafe, when higher level abstractions can be used as replacements.
Some examples of replacing low level with high level. Raw (owning) pointers and manual memory management are replaced with RAII value semantics and occasionally smart pointers. Raw loops are replaced by container iteration and better yet by STL algorithms. Casts are replaced by templates. Threads and mutexes are replaced by tasks and async, etc.
Eventually the idea is to subset C++ so that we can rip the C out of C++.
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppC...
If you write a library with a function which accepts variables x and y and computes x[y] (or x<<y), there's no way for the compiler to know in advance whether the user will pass in well-behaved values for x and y. If you insist on the behavior being defined in pathological cases, then the compiler must add some kind of branching logic in there to check what's passed in at runtime. In other words, spend time doing things the programmer didn't ask for.
Maybe when we make more progress with formal proof-generating languages, we can create a "friendly" C where the compiler refuses to compile the code until it's accompanied by formal proofs of UB-avoidance.
That's entirely feasible. I headed a team which did that for a dialect of Pascal over three decades ago.[1] It's since been done for Modula III, Java, Spec#, and Microsoft Windows drivers.
One reasonable thing to do is to have the compiler generate run-time assertions for every statement which has a precondition for defined behavior. All pointer dereferences get "assert(p != 0)". The shift problem in the original article gets "assert(n > 0); assert(n <= 32);" Now everything has run-time checks.
Then you try to optimize out the run-time checks, or at least hoist them out of loops. A simple prover can remove about 90% of the checks without much effort.
[1] http://www.animats.com/papers/verifier/verifiermanual.pdf
With a 32 bit x, the expression x << b | x >> (32 - b) can be translated to a single "roll x b bits to the left" instruction. But it is only possible if >32 shifts are treated as undefined.
It requires extreme care (assuring no memeory leaks is comparably a walk in the park), and will make your code much less performant. But it's possible.
Working in Perl, I run into this a lot. When 'there is more than one way to do it' is a driving principle, it's easy to be inconsistent in usage and design. There's a tradeoff here -- it's easier to write code, because you can pretty much write your solution however it pops into your head. However, it's harder to read and maintain, because you have to recognize many many different patterns of usage. When code has been around for awhile, it starts to get an eclectic mix of patterns blended together, which can be frustrating to run into when you're trying to fix that code.
How do other people deal with this? Part of it is language choice, I'm sure. Large companies tend to use languages with less stylistic freedom, which helps teams write code more consistently. But within a given language, how do you balance freedom and consistency, so that people can understand each others' code effectively without being overly burdened by restrictions about how they can write code?
Namely, how compact and readable is the generated asm? When we read the asm, can we easily follow what the compiler has done and _why_?
As an ignorant fool, in my mind C is still a shorthand for writing assembly, to save old programmers from continuing to be or new programmers from becoming "assembly language programmers". Obviously many years have passed and "C" has become an institution and means much more to so many people. Aopologies to those people. I am just a fool.
I see the _theoretical_ "C compiler" as nothing more than a code generator, spitting out assembly. Obviously the _practical_ C compiler is very different. Base on the way it's used, it seems inextricably linked with a "preprocessor" (glorified sed).
It is said that asm has a "one to one" relationship with machine code. Theoretically, we can look at asm and determine its machine code equivalent without any "clever" algorithms.
My humble, ignorant fool's opinion is that it would be better if C had a closer relationship to the asm the "C compiler" generates.
Maybe not "one to one" but at least "predictable, boring".
Forgive me for having opinions about overly complex things few people can comprehend (e.g., a "modern C compiler"). I am just an ignorant fool who likes code generators. Especially ones that output assembly.
It also would be interesting if those who think there is enough demand start a crowdfunding campaign to prove that there is enough demand.
For me, the former compliments the later. The less code I have to read, the better.
There are going to be a lot of trade offs in any friendly C spec. Appreciation for both sides of a trade off is valuable in making good decisions.
Honestly I think the biggest problem here is social. Every programmer thinks they're smarter than others. If you give them a button marked "remove all safety checks, increase performance by 1%", they'll press it. Those who wouldn't press it have probably already moved on from C.
So I would say a C virtual machine wouldn't be a very fruitful endeavor, Most user space applications can be written in a Memory safe language, while the most incumbent C code, kernel and system libraries probably can't or at least shouldn't be executed in a virtual machine.
Also, if friendly C is a problem, does that mean that friendly C++ is in the realm of the impossible?
You get friendly C, a new way to think about warnings, and your old code can still be compatible with the new virtual architecture.
Next up, world hunger.