As it is, lots of major C applications already do this on a piecemeal basis and use one or more of:
-fno-strict-aliasing
-fno-strict-overflow
-fno-delete-null-pointer-checks
with gcc to keep a lid on the effects of undefined behavior (and often more or even stricter options, such as -fwrapv).The problem is that even experienced C programmers can get tripped up by undefined behavior all the time. "Yes, it does exactly what you tell it do" doesn't really cut it when the vast majority of actual humans cannot safely predict the effects because they're so unintuitive. Or, in the words of Douglas Adams:
"But the plans were on display . . ."
"On display? I eventually had to go down to the cellar to
find them."
"That's the display department."
"With a torch."
"Ah, well the lights had probably gone."
"So had the stairs."
"But look, you found the notice, didn't you?"
"Yes," said Arthur, "yes I did. It was on display in the
bottom of a locked filing cabinet stuck in a disused
lavatory with a sign on the door saying 'Beware of the
Leopard'."Speaking of which, a killer feature I'd like to see in a C compiler is a flag for debug mode which SIGABRTs whenever it enters an undefined behaviour codepath. For example, sometimes the compiler knows that if pointers alias, or an integer overflows or something, it can do whatever it wants. I want a flag which will automatically add assertions to the generated code, so at least in debug mode it'll crash if thats ever actually the case.
As far as I can tell, -O0 is the only way to avoid that particular mis-optimization in Clang.
Edge cases that have evolved into it do have plenty of problems, but it's very difficult to create a new backwards-incompatible standard which is just a little bit different.
Then again, the embedded (microcontrollers) world seems to be filled with slightly esoteric implementations of C and everybody gets along just fine.
void copy(int* in, int* out) {
for(int i = 0; i < 10; ++i)
{ *out = *in; ++out; ++in; }
}
Now, in C it is undefined behaviour if either o in or out point into the stack where the variables i, in and out live. Maybe their values will change, maybe they won't. In practice, this code will be optimised to some code that just stores in and out in registers.Now let's imagine we want to make it defined. Then the statement '* out = * in' would have to become something like:
1) Write the current values of i, in and out to memory (in case * in overlaps with any of their locations.
2) Read * in into a register
3) Write *out from that register
4) Re-read i, in and out from memory, in case they just changed.
Now, you could make that more efficient by adding to the start of the function a check which looked to see if either 'in' or 'out' pointed anywhere near the stack, but there is still going to be a significant cost. If you plan for this from the start with your language, you can drive the costs much lower.
The main thing that separates C from assembler is that you do not have to worry about what values are in registers, and which are in memory. However, that means any code which writes to memory provides a place where this can make a difference.
"The compiler can always assume writes to memory via one object don't change values in memory accessed via any other object."
Then, if you know your code can overlap, you can use some invalidate function to mark that "memory accessed via this object was changed by some statement prior, make sure to re-read values cached in registers". Because that's the odd case where you're doing something unusual. In general, "The compiler is allowed to optimise things assuming that spooky action at a distance isn't happening". You already have something very similar for atomics, which might be hidden behind a standard library, but in any case are a sequence of "lock the bus, read/write, memory barrier", telling your CPU and your compiler that memory access cannot be reordered around the memory barrier.
Seems to me that that could only happen if you had some other bug clobbering the values of in and out, or you're passing something to the function that you shouldn't be. In either case, it's an error on the side of the programmer.
> If you plan for this from the start with your language, you can drive the costs much lower.
It shouldn't be the job of the language or compiler to make up for the shortcomings of the programmer besides maybe code generation optimization.
In fact, you can't express this in C (or, restricted, whatever), so I do wonder if your assumption that because it's UB it'll compile to the optimal code is true.
I'm talking about something else, the issue of 'in' and 'out' pointing into the stack, so writing to them changing the value of the local variables. That is basically treated as UB by every C compiler, and no compiler I am aware of provides any switches which would make it easier to handle, it's just horrible and your code behaves in different ways depending on the compiler and optimisation level.
But embedded teams often severely limit the language constructs you may use, in order to avoid the foot howitzers and only have to worry about the foot handguns.
There are also many other techniques (such as pre-allocating all variables during initialisation) which can be considered a mitigation techniques for the many traps C offers.
I'm also skeptical of the quality of a lot of embedded software (and I've seen quite a bit of it).
This is not to say that C is bad, or that I disagree with you. But embedded is a bad example.
See Friendly C:
But I bet they would criticize programs for being written in assembly, if they didn't need to be.
If you could have a language with all the performance of C without the footguns, why wouldn't you want that?
I've yet to see a language that actually delivered on this claim.
Rust delivers on all these claims. And there have been others before it. Rust hits all the sweet spots for me.
Example for the first case: Writing a garbage collector runtime in Rust has most of the same problems in Rust as in C, because you have to write most of it in unsafe code, where Rust inherits much of C's undefined behavior w.r.t. pointers via LLVM. In short, you have largely the same problems and have added a hard dependency on Rust.
For high-level work, almost all [1] of what Rust gives you is memory safety and that comes at the price of dealing with a LOT of extra language complexity. But aside from dynamic memory management, memory safety isn't hard (we did that back in the 1970s and 1980s), and for dynamic memory management, we can get memory safety with a garbage collector and much less complexity. So Rust is primarily of interest for those use cases where garbage collection is not an option.
While that still gives you plenty of interesting use cases for Rust, there are also plenty of programming niches that it serves poorly.
[1] People will also mention "fearless concurrency", but guaranteeing the absence of data races is not hard. That more languages don't do it is partly because they simply neglected that aspect [2], but also because any mechanism – including Rust's – for doing so inherently constrains your options w.r.t. concurrency [3]. Plus, avoiding data races is the easy part of getting concurrency right.
[3] Concurrent Pascal had guaranteed absence of data races in the absence of pointers in the 1970s, Eiffel had done it with pointers in the 1980s, and there was a plethora of research in the 1990s to do it in various other ways.
[3] For example, there are plenty of use cases, such as certain idempotent operations, where data races are not only perfectly safe, but also desired for performance. There are also use cases where you can prove that no data races occur, but a type system cannot easily capture that.
It's too high-level for a lot of low-level work, and too low-level for a lot of high-level work.
This is true in the very specific cases that you gave, but I believe that is the minority of use cases, not the majority.Even the example of writing a GC that requires tons of unsafe code, that is not a good argument for making all the code unsafe. All the unsafe GC code would be abstracted away into a module and would be more obvious to those looking at it that they will need to be watchful for undefined behavior. Now you can proceed writing the rest of the project in safe, simple Rust.
People will also mention "fearless concurrency", but guaranteeing the absence of data races is not hard
Maybe for developers that are very familiar with the race conditions of parallel code, but definitely not for most people. Even seasoned developers will make mistakes with simple multithreaded code.Also, the reasoning behind "x is easy so why do I need my language to check it for me" is questionable. The whole point is that you have a guarantee. Have you never had a compiler catch a stupid mistake before it happened and felt relieved? I doubt it. Now imagine if instead of debugging stupid data races in your parallel code you can spend that time optimizing and improving it. I fail to see how this can be viewed as negative.
Sure Rust doesn't cover 100% of use cases, but it definitely covers more than you're implying. It's low-level enough that Redox OS can be written in Rust, but high-level enough that Firefox is now outpacing other browsers and parallelizing everything with Rust.
That code that could be "abstracted away" would be "virtually all the code" in my example.
> Maybe for developers that are very familiar with the race conditions of parallel code, but definitely not for most people. Even seasoned developers will make mistakes with simple multithreaded code.
I'm not talking about manually guaranteeing absence of data races. I mean absence of data races as a language feature.
> Also, the reasoning behind "x is easy so why do I need my language to check it for me" is questionable.
This is not at all what I was talking about. You completely misunderstood me.
> A quick grep gives us some stats: the kernel has about 70 invocations of unsafe in about 4500 lines of code overall.
My example was a GC runtime, not an OS kernel. If I have only very little unsafe code, then I could just do that in C and the rest in whatever other high-level language suits my project and not see any difference.
The bigger problem – where Rust failed to pick some low-hanging fruit, IMO – is that "unsafe" is too much like the bad parts of C. There is no medium position between "everything is defined and memory-safe" and "everything may explode at a moment's notice".
My most practical need for a low-level language is a language that is in that in-between position: semantics that remain easy to comprehend and predictable even if there are no static guarantees, and where I have to use a different strategy for software assurance. The point here is that for such a language I can resort to alternate validation tools (think Ada and SPARK for an example). Rust's unsafe mode does not handle that situation well because (like C) it does not provide a foundation for alternate validation strategies.
It's perhaps also worth pointing out that I have a formal methods background. In short, I've done formal specifications/proofs for software before. In this context, safe Rust has a fairly high cost for only providing memory safety (and few other guarantees), and unsafe Rust is not a good foundation (or at least, not much better than C) for bringing advanced tools to bear.
We find that Rust’s safety features do not create significant barriers to implementing a high performance collector. Though memory managers are usually considered low-level, our high performance implementation relies on very little unsafe code, with the vast majority of the implementation benefiting from Rust’s safety. We see our experience as a compelling proof-of-concept of Rust as an implementation language for high performance garbage collection.
[0] http://users.cecs.anu.edu.au/%7Esteveb/downloads/pdf/rust-is...
> We found that the Rust programming model is quite restrictive, but not needlessly so. In practice we were able to use Rust to implement Immix. We found that the vast majority of the collector could be implemented naturally, without difficulty, and without violating Rust’s restrictive static safety guarantees. In this paper we have discussed each of the cases where we ran into difficulties and how we overcame those challenges. Our experience was very positive: we enjoyed programming in Rust, we found its restrictive programming model helpful in the context of a garbage collector implementation, we appreciated access to its standard libraries (something missing when using a restricted language such as restricted Java), and we found that it was not difficult to achieve excellent performance. Our experience leads us to the view that Rust is very well suited to garbage collection implementation.
The underlying problem is that Rust's borrow checker cannot possibly capture at compile time the arbitrary relations between objects managed by a garbage collector and arbitrary object layouts. Whatever guarantees it provides, memory safety isn't one of them (and cannot be), even if nominally only part of it is unsafe code. Pointer arithmetic and memory safety do not mix.
What you get out of that is basically an alternative approach to information hiding, not memory safety.
> Writing a garbage collector runtime in Rust has most of the same problems in Rust as in C, because you have to write most of it in unsafe code, where Rust inherits much of C's undefined behavior w.r.t. pointers via LLVM. In short, you have largely the same problems and have added a hard dependency on Rust.
to the conclusions drawn in the cited paper. They sit in pretty stark contrast from where I'm standing.
At a severe cost in performance. Static object lifetimes cover 99.9% of a garbage collector's use cases, without the performance cost of GC, nor the nondeterministic runtimes. We first saw static object lifetimes come into their own with C++'s value semantics; Rust refines and clarifies the idea and makes memory safety an inherent part of the language itself.
Static object lifetime is to GC what static types are to dynamic types. Lisp is 1960s tech. It has failed, and been replaced with something much better.
For starters, we have to assume that we don't deal with value types (which will end up on the stack, one way or the other), but with local variables that reference heap objects. Second, we have to distinguish between tracing and reference-counting GCs.
A modern tracing garbage collector will have cost for such temporary allocations comparable to `alloca()` and those allocations will typically be inlined. The cost of deallocating a short-lived stack object is zero (yes, zero). This is possible because GCs (unlike manual memory management schemes) are compacting. Whether one approach or the other comes out on top is very situational.
More importantly, I dispute the 99.9% as a vast exaggeration. There are plenty of important use cases (such as persistent data structures, shared caches, etc.) where unique ownership is insufficient; Rust requires you to use either copying or reference counting when you run into shared ownership scenarios, both of which are more expensive than tracing GC (naive reference counting is already one of the more expensive memory management methods known, and atomic reference counting is especially expensive).
If you use reference-counting GC, then for any program that satisfies Rust's borrow checker, the optimizer can eliminate reference counts that satisfy the same conditions (assuming that the optimizer knows about them because they're part of the language semantics). This is largely what Swift does, for example.
Finally, there is deferred reference counting, which incurs only trivial overhead for objects with automatic lifetime (on the order of a fraction of a percent). This is because this algorithm incurs real cost only when pointers are written to global or heap locations; this is also why it's seen limited use in practice: it's excellent for objects with automatic lifetimes and does not rely on the generational hypothesis, but those do not constitute 99.9% of all use cases. If they were, deferred reference counting would have a far more prominent role.
This does not even account for the fact that when there is overhead, that overhead is generally trivial in an imperative language with value types.
There are use cases, of course, where a tracing GC is an inappropriate choice, but that is not because of throughput. Tracing GCs make interoperability with other GCs different, for example, and have implicit memory overhead that may be prohibitive in large applications such as a web browser (that can easily consume gigabytes of memory on a laptop or desktop machine). That said, there are alternative approaches to garbage collection that do not have those problems.
Rust is not a replacement for C in the sense of portability. People love simplifying the world into Windows/macOS/Linux, but that is not all you may want to target.
Nowhere in this sentence do I see "for every platform C targets".
Given no other requirement other than C without the footguns (memory unsafe) is there a good reason not to use the safe version? I'd say there are some, but they aren't crazy compelling (ie: developers have to learn rust, maybe harder to hire for, etc).
Tests can't establish the absence of bugs the way Rust can. You only think your C code is reliable, you don't actually know that it's reliable. Rust only appears harder because of the latent bugs in your C program that you're not aware of.
For simple cases, this may be true, for complex cases it but shifts the cognitive load up front. Which may be more frustrating, but also may prevent a large class of hard to identify, intermittent in manifestation, bugs from getting into production. Which also saves programmer frustration.
That's like saying a SawStop (http://www.sawstop.com/) lacks a simplicity of a sawblade. I mean - Yeah, sure, but sawblade also won't stop you from turning yourself into amputee.
I understand Rust can be overly verbose, but main complexity comes from the borrow checker and the effect adding another kind of type, to track lifetimes. The lifetime system is the main selling point.
There are other sources of complexity in Rust, but I am glad to say both Rust/Scala seem to be looking for a way to simplify things.
No it doesn’t.
One reason is rust doesn’t have SSE/AVX/Neon intrinsics.
Without them, you can’t get anywhere near all the performance of C, nor anywhere near advertised performance of any modern CPU.
IMO, this isn't even the right goal. The problem is that in many cases using C is itself a premature optimization. Consider two languages:
* C, which gives you performance by default at the cost of an entire arsenal of footguns with esoteric nonlocal trigger conditions
* Hypothetical language X, which has all the same footguns but engineered for safer triggering and locked up in a safe that you have to choose to open when you want C-like performance
I'd rather have hypothetical language X (which is an accurate portrayal of many real existing languages), because it's got better failure modes. Performance issues are less impactful, in general, and more importantly they are more obvious. It is usually easy to tell when code is not fast enough. The endless parade of CVEs ultimately deriving from memory safety issues, often decades old, is living proof that misuse of the footguns is frequently far from obvious.
A language that avoided it would have to be very close to C while making it only mildly more difficult to foot shoot. Everyone who is trying is overshooting and therefore not really writing an adequate replacement low level systems language. Even if they did, it would be so close to C that adoption pickup would be low, awkward, and the language would fail outright. (Think Python 3 but worse)
>But I bet they would criticize programs for being written in assembly, if they didn't need to be.
Certainly. If you're writing your web app in assembly you are very likely a crazy person unless your goal is to do something ridiculous. If you're writing some assembly in a critical path in a web server to precisely control the network stack, you might not be a crazy person (see Netflix tech blogs).
Says who? A language where every single memory access did NOT have the potential to be a buffer overflow would be much more difficult to foot-shoot with, even if it allowed you to sometimes access memory with raw pointers. Just having the ability, as in Rust, to mark code as either safe or unsafe goes a long way towards preventing footguns.
>Everyone who is trying is overshooting and therefore not really writing an adequate replacement low level systems language.
Using Rust as an example again, I don't think there's anything about being able to say "this code right here cannot cause memory unsafety" that precludes "low-level systems" programming.
Well, I'm quite bored of the endless stream of memory safety vulnerabilities that can be systematically eliminated with memory-safe languages like Rust. Note that every single one of the CVEs disclosed yesterday in dnsmasq are memory safety violations, and the fact that buffer overflows, data races, and other related errors are not only pervasive, but also tend to sit around for years in codebases[1].
> Nobody would criticize assembly for letting you shoot yourself in the foot, C is much the same.
It's completely acceptable to criticize the choice of any tool. I can and do criticize the use of C for any code that touches a network and in some cases consider it willful negligence, as using a non-memory-safe language to parse untrusted data is asking for trouble.
[1]: https://twitter.com/johnregehr/status/914663997647069184
Therefore, it follows that re-writing parsers in memory-safe languages would provide a nice bang-for-buck.
That's fine... but the billions of dollars spent on security and the massive trove of user data that's been exfiltrated due to C is kinda a problem regardless of whether you are bored or not.
> Nobody would criticize assembly for letting you shoot yourself in the foot, C is much the same.
I wouldn't criticize a developer for writing bad code. I'd criticize the language for letting them, or the developer for choosing such a language. Same with C and Assembly.
> The biggest threat to the tech sector is Linus dying and being replaced by some charlatan who insists on replacing C and using Jira.
That is... not the biggest threat. It seems extremely unlikely that that is where linux kernel development would go.
If anything replaces C I'm skeptical that more than a shift in the character of the attack surface (rather than the area) will occur. That is, there will be just as much to attack, it's just that the attacks will require alternate methods. Some attacks will be harder to employ, some less, but on average probably about the same quantity and seriousness will occur.
You can call it a meme but that doesn't change my opinion.
> Some attacks will be harder to employ, some less, but on average probably about the same quantity and seriousness will occur.
This is unfounded, I don't really know how to respond to it other than that nothing has ever really worked this way in security. You don't get less secure in one area because you were more secure in another.
I agree with you, however that doesn't address what I actually wrote.
gcc: “hold my beer while I optimize out that block of code you clearly didn’t mean to be in your program”
Or rather, because the standard "imposes no requirements". A compiler that does the obvious/sensible thing for UB can also claim conformance.
From C99 3.4.3 paragraph 3 (emphasis mine): "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)."
UB was introduced to allow skipping checks that otherwise might have added overhead, like array bound checks or null checks or to give more flexibility to how correct programs are optimized (e.g. freedom to evaluate arguments in any order). Therefore each compiler/library/os vendor could implement these cases differently.
However, it was never meant to allow compiler to assume "ok, I can see your code is totally broken, so let's break it more, cause you don't care anyway".
That's nevertheless how compiler writers are interpreting the standard right now. Take integer overflow for instance. Stuff like this:
unsigned u = some_computation();
int x = u; // because of reasons
x += 42; // hmm this may overflow, let's check that
if (x < 0) { // It's a 2's complement machine, this'll work
handle_overflow(x); // now, let's deal with the overflow
}
Now here's how your optimising compiler see that stuff: unsigned u = some_computation();
int x = u; // x is always positive.
x += 42; // signed integer never overflow
if (x < 0) { // x was positive, no overflow... always false
handle_overflow(x); // Let's delete this dead code.
}
Then, what actually happens: unsigned u = some_computation();
int x = u;
x += 42;
This is insane.[1] https://wandbox.org/permlink/dDDAJjOlm50GD1PW
It would be able to (correctly) make that assumption if `x` were a long, assuming 64-bit longs and 32-bit int/unsigneds.
When a value with integer type is converted to another integer type ... [if] the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1570.pdf
So casts from unsigned to signed must have a well-defined result, but the implementation can choose how to define it. You could in theory have an implementation that defines that casts from unsigned to signed are always positive,[1] but since that's not how GCC and every other mainstream (existing?) compiler defines it, they are not allowed to assume the result of a cast from an arbitrary unsigned integer to a signed integer of equal width is positive.
[1] In which case the compiler would be allowed to assume that unsigned-to-signed casts are never negative. This assumption would however be both safe and correct, and would have nothing to do with UB.
Let's see, that's not an assumption you can make in C, or is it? I seem to remember that a compiler is allowed to present to the programmer at least one or two representations other than two's complement.
And a footnote on that:
"A positional representation of integers that uses the binary digits 0 and 1, in which the values represented by successive bits are additive, begin with 1, and are multiplied by successive integral powers of 2, except perhaps the bit with the highest position."
3.4.3 undefined behavior
behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements
NOTE 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).
-------------
Even if you want to argue over what "imposes no requirements" means, I'd argue that "ignoring the situation completely with unpredictable results" is very clear.
The note also says (and elsewhere in the standard it reinforces this) that since there are no requirements, implementations could absolutely do things like perform runtime checks, etc. Compilers do not do this though. This isn't for no reason, but that's a separate issue.
The galling thing is that they did this to win a benchmark war against Fortran.
I've heard some horror stories and apparently the development team is pretty heavily pressured to fix a lot of things.
Exactly, if you could get all the benefits without the danger why wouldn't you?
I hardly saw any reason to use it instead of Pascal dialects, besides being "the language" on UNIX systems.
Thankfully Bjarne created C++.
Yes, it does exactly what you tell it to do and that's dangerous. It was a high level language 25 years ago, but today the metaphor should be assembly. Nobody would criticize assembly for letting you shoot yourself in the foot, C is much the same.
The biggest threat to the tech sector is Linus dying and being replaced by some charlatan who insists on replacing C and using Jira.
</offtopic>