by colechristensen · 9y ago · 0 comments
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>
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.
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.
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.
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".
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++.