144 points · by synergy20 · 2y ago · 144 comments
These should be table stakes when talking about "safe" languages (or subsets thereof); I hope these authors have or propose plans for these classes as well!
(I agree with the more general critique here, that any adaptation invasive enough to provide these properties in C might as well be its own programming language.)
Xr0 is not limited to memory-safety, its goal is to eliminate the possibility of writing C code that results in undefined behaviour. A good analogy can be drawn to how Typescript wraps Javascript and provides type safety. Think of Xr0 as a wrapper to C that guarantees you don't violate C's safety semantics.
(Other proposals that I’m aware of seek to forbid those parts of the language outright, or add some kind of runtime instrumentation like isoheaps. Neither of these is particularly palatable for pre-existing codebases with deep, undocumented language feature and ABI assumptions!)
Like this idea a lot. Does that mean it could be used to convert C projects in a strangler pattern style?
This obviously covers type safety, but also spatial memory safety, and can be extended to temporal memory safety, and even some concurrency aspects.
This has been proven for fairly large subsets of programming languages and even some full languages (like SML). Unfortunately, it doesn't hold for most mainstream ones, because programming language theory is often ... under-used ... among language designers.
I would add that temporal safety is significantly harder than spatial safety (spatial safety is only hard in C if you do not want to break the ABI), so it is nice that this project is focusing on it.
"Safe" and "safety" are very overloaded English words that come with a lot of baggage, and perhaps it would be prudent to stop using these broad, nonspecific terms for things like programming languages.
"Memory safety" is a coherent, reasonably well-defined concept, and it's fine to talk about something like that. But what does a broadly, generically "safe" programming language even mean?
(I can't find anything about it in this page)
Avoiding UB in single threaded programs is the easy part. It's harder for a low level language like C, but not too hard.
But avoiding UB in multithreaded programs is very very hard. Many "safe" managed languages have UB when you misuse synchronization mechanisms, like Go.
Some languages Java and OCaml manage to avoid UB when you have data races. They do so by disallowing some compiler optimizations. OCaml is the better one in this regard (see the paper "bounding data races in time and space")
Is there any proposal or rough ideas or musings or anything that might suggest how Xr0 could possibly guarantee data race freedom?
Would it be something like Rust's Send & Sync traits? Or something else entirely?
I don't see why I would ever choose this over Frama-C which basically does the same (and is actually battle-tested). I just don't see a niche:
- No full control over runtime needed: Java, C#, Python, ...
- Full control over runtime and memory safety: Rust
- Full control over runtime, memory safety and provable absence/presence of certain behaviors (i.e. aerospace, nuclear reactors, ...): Frama-C, CBMC, Astree, ...
Where does Xr0 fit in and how does it differ from existing technology? The fact that they don't even mention any of those tools makes me believe that they are either not aware of them or that they are aware and the difference between this and Frama-C is just syntactic. Not a good look either way.
What is significant about Xr0 is how it applies these old ideas. Xr0 is designed for programmers rather than mathematicians, so to us syntax matters a great, great deal.
I don't think you're under any obligation, I just think that not discussing prior art is a bad look.
> What is significant about Xr0 is how it applies these old ideas.
I don't see anything new about the application of these well-known ideas either. Especially nothing that could explain why Xr0 would be widely used, while Frama-C is extremely niche.
> Xr0 is designed for programmers rather than mathematicians, so to us syntax matters a great, great deal.
Proving (the correctness of code) is an inherently mathematical task. So if by "mathematician" you mean someone who does mathematics, then all of your users will be mathematicians.
Contract.Requires(start > 0);
Contract.Ensures(someReturn != null);
I loved it. It gave you much (not all) of that "if it compiles it works" good vibes that Rust has. Though, oh boy, were you in for a surprise if you think that Rust compiles slowly. You could probably do something similar with C: CONTRACT_REQUIRE(x == 0 || x == -1);
if(x) {
void* result = malloc(1);
CONTRACT_ENSURE(result != null);
CONTRACT_CALLER(free(result));
return result;
} else {
CONTRACT_ENSURE(result == 0);
return 0;
}
The nice thing about that is you could have a compatibility .h that asserts/nops the macros, making the code compile in ignorant compilers.https://docs.rs/contracts/latest/contracts/
Ada has Design by Contract built into the language (not a library):
https://learn.adacore.com/courses/intro-to-ada/chapters/cont...
DbC is awesome because it formalizes what conditions must exist before and after a piece of code runs and defines who (caller vs. callee) is responsible for what parts.
void x() {
int * p;
p = malloc(1);
if(0) {
free(p);
} else {
free(p);
}
}
0v: src/ast/stmt/verify.c:228: stmt_sel_exec: Assertion `!ast_stmt_sel_nest(stmt)' failed.void x(int f) { int * p; p = malloc(1); if(f) { free(p); } if(!f) { free(p); } }
And this doesn't, as expected:
void x(int f) { int * p; p = malloc(1); if(f) { free(p); } if(f) { free(p); } }
edit: another assertion failure:
void x(int f) {
int * p;
p = malloc(1);
if(f) {
free(p);
}
f = !f;
if(f) {
free(p);
}
}We've put a fix in for this on a dev branch for now though: https://github.com/xr0-org/xr0/issues/43
Does it always make sense to strictly enforce code that will be optimized/changed during compilation? Or does Xr0 run after compilation/linking?
How to handle things like unions where you want data in a nice mixed-type struct that is used locally and can also be sent as a stream of uint8_t over a wireless connection? Then, the last function that needs to use the memory frees it. Or is that still fine as long as you malloc once somewhere, free once somewhere, and annotate that the memory region will be accessed as more than one dereferenced type?
Much more important: Will the proposed changes be understandable enough for your average CS undergrad to learn in four months of halfway diligent study? (Then again, you might do away with students taking time to debug improper malloc/free and whatever else falls under the scope of Xr0...)
This doesn't need to be perfect though. Just incrementally better than the status quo.
Have you looked at them? Always good to look at prior art, it's not easy what you're trying to do.
Pretty sure I still have the CCured code lying around in a backup somewhere, I downloaded it and played with it long ago. If it's truly not available on the net anywhere, I suppose I can try to dig it up.
Are any of the many "safe versions of C" getting any traction? There have been so many. It's not a technical problem. It's a mindshare problem.
The future in this area may be something that takes in existing C code and uses a LLM to recognize idioms and annotate. Without some automated way to convert legacy code, this isn't going to happen.
(One big problem with converting to Rust is that Rust's data model is so far from C/C++ that you can't really convert much existing code. You have to rethink the design to fit the affine type model. That's hard.)
https://www.youtube.com/watch?v=Gij9UQy_JEQ
https://github.com/pizlonator/llvm-project-deluge/blob/delug...
Right now I'm ~90% through a major rewrite to use GC instead of isoheaps, because then I'll go from rewrite-a-bit (Fil-C previously required malloc calls to be annotated and for some unions to be changed) to rewrite-nothing (malloc will Just Work and so will unions).
I hope there are others also trying various alternatives. It's too soon for most of these things to tell what traction they may or may not get.
https://www.cs.purdue.edu/homes/rompf/papers/xhebraj-ecoop22...
I haven’t looked at what GCC has in a while because I don’t want to get gpl tainted. :-/
True, but that's likely going to be the case as well to convert to any ”safe version of C” as well, because in the general case the safety of a C program is undecidable: to make it safe, you have to restrict it to a subset of behaviors that can be statically proven as safe, and the borrow checker and “Rust's data model” is just that.
So there's no direct translation from a C++ object hierarchy to Rust structs.
The verbosity of the annotations is the most jarring thing at the beginning. However, do you find any of them unclear? Because we're optimising for similarity to C before terseness.
Though if one wants C and safety and a great language you can get there via, Rust -> Wasm -> C (via wasm2c).
It would be cool to see this applied to say, rsync.
Presumably it's easier to rewrite part of your app rather than the whole thing.
But I'm all for a safe version of C17 (or C23/24). It's so disappointing that there isn't a standard memory-safe compiler/runtime/ABI. (And while they're at it, the stack should grow up rather than down.)
Perhaps CHERI or similar will catch on someday. Maybe Apple could try implementing memory checking for clang and Apple Silicon.
It looks as though the idea is that you can annotate existing code, which is a lot easier than rewriting.
That's not necessarily true though.
Half decent C code already has a coherent memory management strategy. The problem is that humans can't follow even pretty straight-forward memory management strategies 100% of the time. If you have a function that returns memory the caller is required to free, or accepts a parameter that the function takes ownership of, that can be easily expressed but hard to get right every time.
In fact, functions typically document this... in half-decent C code. So we're really talking about formalizing the expression of memory management documentation that already exists and is already understood.
> And you're not getting as much safety bang for your buck for the effort as you would in a rewrite in actually safe language.
I just can't think of what the rational argument for this could be. A complete deep rewrite -- where the new language requires reorganizing the code at a low level so that a lot of existing logic cannot be reused (as-is, or transformed in certain specific ways) -- is extremely costly. It is on the order of the total cost of writing the software in the first place plus the entire cost already spent maintaining it over time. Some costs -- like the goodwill of users/adpoters -- simply cannot be paid again at the same rate. For large scale software there would be numerous regressions over a long period of time, while at the same time the software stops adding many new features, since all the focus will on the rewrite and bugs related to the rewrite. I will stand corrected if there is more than one or two exceptional cases of large scale software making a successful transition of this sort without paying a massive cost.
But rewriting assumes I learn a new language on top of rewriting.
Safe C provides an incremental migration path from unsafe C to safe C. And you don't need to completely rewrite, but instead address the issues flagged, which will often be a lot less work and risk than an actual rewrite in a new language. (This seems obvious to me, but apparently not?)
Safety annotations is the directions that C++ has been attempting without much success for a while though, so I'm not very optimistic. But I'm always happy to see another attempt.
Would you go into a thread about emacs and say, "Why would anyone use emacs over vi?" And if not, what makes you think you should do that here?
https://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html
The syntax?
Obviously that's not "the only problem", else there wouldn't be huge style guides forbidding tons of practices to make programs safe for NASA and other such uses, aimed at the expert C programmers hired there.
Also obviously that is not "a problem irrespective of which language we are talking about", unless half-knowing the language has the same impact and the language have the same footguns, which is nowhere near true for other languages versus C. You can "half know" Java and not ever get a buffer overflow. You can know C quite well and still get all kinds of dangerous bugs into the code.
I have 10+ years experience (and consider myself highly proficient) in C#, but my interaction with expression trees is mere hours where I've only once or twice needed to solve a very specific small problem which I could do with a small tweak to code copied from Stack Overflow.
Rust and C++ lately have been particularly quickly moving targets to keep up with, where C is still pretty much the same as C99. The compilers are better, their warnings are better, sanitizer modes are incredible, but the things you type into your text editor to express your program structure are still pretty much the same thing.
But those are exceptions: I've definitely felt like I've known more than I really did about at least C, C++, Java, Scheme, Python, Go, bash, Javascript, cron, and several assembly variants, and those platforms did little to stop me from learning about my inexperience in difficult, sometimes embarrassing, sometimes expensive ways.
I'm a big fan of more compile time analysis any way it can be done, and whatever can't at runtime. More types, more proofs, more fuzzing, more sanitizers, and also where possible, more restricted execution models than Turing-complete. Any code that can't prove itself correct is a serious liability. I just also like C... it's got many footguns, yes indeed, it's practically constructed out of only footguns, but there are only like 8 of them, and they're all right there waiting for you to get to know them. It's like having a few good sharp knives in your kitchen. You get to know each well, using them one at a time---and if any is missing from the block you pause everything and look around very carefully.
Relatively tiny and with a disproportionate number of footguns.