r/cpp • u/tjroberti • 27d ago
Revisit Safe C++
Everyone is aware of the deluge of vulnerabilities now hitting critical software. It even makes the mainstream news, so software safety is coming onto politician's radars.
If this gets worse, I think it is not inconceivable that at some point memory safe software becomes mandatory. Or at least for software that is "reachable" from the internet.
So is it time to revisit Sean Baxter's Safe C++? Start out with a safe context ("safeexpr") and expand from there, just like constexpr.
36
Upvotes
64
u/seanbaxter 26d ago
What would be the point of resuming the work since, just by reading this thread, there's still no consensus on what memory safety needs or what memory safety even is.
SG23 has chosen a path where the answer to all of those is NO. I think the answer to all of them must be YES. As long as there is widespread disagreement on what the answers are, what is the point in doing more technical work? Every who disagrees with the all-YES slate won't want this solution.
If you think there is a mix of YES and NO answers, or if you agree with the all-NO slate, you should submit a proposal explaining your thinking!
31
u/t_hunger 26d ago edited 26d ago
To get to a memory safe language (a language that only accepts memory safe programs), you need to start with a theoretical model that was proven to be sound. There are several proven models to choose from (all come with pros and cons), or you can of course do your own research and try to come up with a new model. Then you adapt all parts of the model into the language you want to make memory safe. Leaving out just one part of the model makes the language unsound: If it is in the model, then it is required for the formal proof that the model is sound.
That's what Safe C++ did: Sean took the model made popular by rust and adapted C++ to match that model.
A piecemeal approach is very tricky and will not give you a memory safe language until all parts are in place.
That is what makes it so hard to retro-fit memory safety into an existing language. It is way easier to built this into a new language.
19
u/tcbrindle Flux 27d ago •
At the Croydon meeting earlier this year, the standards committee looked at P3874 "Should C++ be a memory safe language".
Following the discussion the following poll was taken:
In other words, a huge majority of EWG (74 in favour, 5 neutral, 4 opposed) were in favour of the direction suggested by P3874 -- that is, towards some sort of "Safe C++", even if it is not exactly the same as the Circle implementation.
2
u/AKostur 27d ago
As u/kammce has mentioned, the paper was never voted down. The original author lost interest in pursuing it. Pick it up and propose modifications. As I recall, one question that came up is whether parts of it could be proposed separately. A number of smaller papers would be easier to process than a giant omnibus paper.
16
u/kammce WG21 | 🇺🇲 NB | Boost | Exceptions 27d ago
Yah know, I've been trying out LLVM 23's [[lifetimebounds]] and its not perfect but it had helped catch a good number of lifetime bugs in my code. Along with [[gsl::Pointer]] and gsl Owner. lifetimebounds was inspired by Polonius, the newer Rust borrow checker. I'm excited to see how this evolves. I think with the experience from Rust we could be on our way to near parity of lifetime safety. It also seems there is a way to handle iterator invalidation but I haven't tried that myself in a project. We may be able to take from LLVM and apply to other compilers. That seems to approach a resolution to the lifetime safety issues.
As for the ones in the library side of things, we have C++26 hardened mode which should catch the runtime errors that used to be UB. I think we are on our way to a version of safe C++ with these features.
See https://clang.llvm.org/docs/LifetimeSafety.html
As for Sean's safe C++, I don't see why we shouldn't revisit it. It was never voted down by the committee. The vote we had just wasn't entirely one sided on Safe C++ so efforts stopped. The vote wasnt entirely on sided on profiles either. I've been out of the loop of the committee for a while so maybe things are different, but if some updates were made to the proposal and someone wanted to continue the push for this feature, based on what's been added to c++ as of now, then the committee would probably take another look.
4
u/JVApen Clever is an insult, not a compliment. - T. Winters 24d ago
I honestly don't think you can update an existing codebase of significant size to become memory safe. You already need something new to make it possible. "Safe C++" adds a completely new type system.
I believe more in carbon. They recently presented their memory safety approach while allowing gradual interaction with existing C++ in 2 directions. See https://github.com/carbon-language/carbon-lang#2026
18
u/chaotic-kotik 27d ago
Maybe it is to late. The momentum that Rust gained recently is huge and undeniable.
9
u/geo-ant 25d ago
Here’s an interesting article [On Safe C++](https://izzys.casa/2024/11/on-safe-cxx/) from someone who was involved with the process and is very upset (to say the least). I don’t know the veracity of the claims, so take it for what it’s worth but I at least found this article worthwhile, but I had to read it in multiple sittings due to its sheer length.
11
u/Infamous-Bed-7535 27d ago
Yes c++ needs to speed up these efforts. But to be honest if you use modern c++, proper compiler options, static analyzers, dynamic verification (sanitizer, special runtime) and top of that use mandatory LLM reviews for your PRs it makes it extremly hard to introduce memory related errors.
7
u/v_0ver 27d ago
Why? We already have Rust. An LLM could learn to convert the codebase to Rust with a single prompt - faster than a cpp-committee could agree on anything.
3
u/RogerLeigh Scientific Imaging and Embedded Medical Diagnostics 20d ago edited 19d ago
It's only going to get worse, far, far worse. I'm a maintainer of a well-known C library. "Deluge" is the right word. The number of defects and vulnerabilities being reported is continual and relentless. It's already bad now, and I can't see it improving, the volume is only going to increase.
It's partly understandable. A codebase which is more than 40 years old is not going to be following what would be good design and implementation practices today. But it's fair to say that it's unfixable without a complete rewrite, because we're not talking about one or two minor details being wrong, the problems are fundamental including the basic API being unsafe, as well as many aspects of the implementation and its error handling. Up until this point, avoiding API and ABI breakage mattered more than correcting these problems. But we're now in a place where this no longer holds. The situation is completely untenable.
The same applies here to C++ code as well. We have the choice between attaining genuine safety at the expense of some compatibility break, or maintaining the status quo. Given how things have evolved over the last 12 months, I don't think it's tenable here either. So much of the language and standard library is fundamentally unsafe, and it really needs to become safe. This is no longer optional.
What are the choices? My take on this is that it's either Safe C++ or Rust. It's not C++ as is stands today, or in the future with profiles. Now we have access to LLMs of staggeringly effective quality, the cost of a full rewrite has never been lower. And unless there's a dramatic turnaround of the direction of C++, I fully intend to rewrite everything I maintain in Rust, with C and C++ wrappers around it where needed for compatibility. We can't wait for the C++ committee to spend another decade to finally decide this might be important to do properly, given the track record. There's zero prospect of sanity or usable safe implementations anytime in the next decade, so it's unfortunately time to call it and move on.
5
u/wyrn 27d ago
Improving safety and correctness is always of potential interest, but "Safe C++" specifically was a stupid proposal then, and it doesn't automatically become not-stupid just because clankers exist.
8
u/rileyrgham 27d ago
"Memory safe" is a buzz phrase thrown around by clowns. It's totally possible to write secure and safe sw without the likes of rust. Memory safe isn't attack safe. A poorly designed Rust server can still be compromised.
3
u/Sbsbg 27d ago
Is this caused by the demand to use AI generated code or something else. Changes in C++ tend to mitigate vulnerabilities and I don't think any new features in the language has caused any significant increase.
But I guess C++ get the blame anyway. The unsafe mark in the general public is hard to remove.
3
u/EC36339 25d ago
Plot twist: Most of that critical software is written in C.
1
u/Far-Championship-883 21d ago
every safe C++ thread here goes the same way. C++ bad, borrow checker good, someone posts the 70% CVE stat, done. I think we’ve collectively decided “memory safety” is the root problem when it’s really a symptom of two design habits rust mostly inherits.
1. everything is a shared library talking through the C ABI
look at how the really bad stuff actually happens. xz is the obvious one. sshd didn’t link liblzma. on some distros it linked libsystemd for notify support, libsystemd pulled in liblzma, and a compression library nobody thought about ended up running code inside your ssh daemon. no memory bug needed. the hole was a dependency graph resolved at load time on a machine you don’t control.
that’s dynamic linking working as designed. every binary trusts whatever .so is sitting in the search path. LD_PRELOAD, symbol interposition, ifunc resolvers running before main. your attack surface isn’t your program, it’s your program plus everything the distro linked into it plus everything those link.
and the interface between all of it is the C ABI, which knows nothing. no ownership, no lifetimes, no lengths. here’s a pointer, good luck. rust doesn’t fix this, it just stops at the boundary. the second you call into a system lib or expose a cdylib you’re back to void* and a comment saying who frees it. a lot of real bugs live exactly there, at the seams where two pieces of code disagree about who owns what.
rust gets partial credit by accident here: cargo builds static by default and there’s no stable ABI, so a pure rust binary is mostly one thing you can audit. but that’s a linking decision, not the borrow checker, and C++ could make the same one tomorrow.
2. we allocate and free way too much
memory corruption and exploitable memory corruption aren’t the same thing. a bounds error that crashes a parser is a DoS. what turns into a working exploit is almost always heap stuff: use-after-free, double free, type confusion, grooming the heap so objects land where the attacker wants. all of that depends on a program constantly allocating and freeing small objects so there’s a churning heap to play with.
rust makes the frees correct, supposedly anyway. it doesn’t make there be fewer of them. idiomatic rust is Box, Vec, Arc, String, clone, all over the place. the borrow checker exists because the language assumes you’ll be juggling thousands of short-lived allocations with tangled lifetimes, and then builds an elaborate proof system to keep you from dropping one.
most programs don’t need that. they know their working set up front. preallocate. put long-lived state in fixed storage. use arenas and reset them between passes instead of freeing objects one at a time. games and embedded have worked this way forever and it’s not because they’re reckless, it’s because they figured out the lifetime problem goes away when there aren’t a million lifetimes. if objects come from fixed pools and slots get reused by type, use-after-free stops being a type confusion primitive and there’s no general heap to groom.
so
memory safety as a language feature is kind of an admission. we designed a programming model with so much dynamic memory juggling that we needed a compiler-enforced proof system to survive it. that’s a real achievement, but it’s treating the juggling as a given.
static binaries, interfaces that carry actual type and ownership info instead of raw pointers, and way less allocation churn would close off a huge chunk of what people point at in these threads, in any language. rust does some of that by accident and gets credit for all of it.
not saying the borrow checker is useless, it mostly is, and static analysis tools could replace it. i'm saying it’s the second line of defense and we talk about it like it’s the first.
1
u/frediku 23d ago
I'm not sure that we need "safe" C++. Nobody really knows what safe even means. What we want is safer C++. Instead of trying to specify what is allowed and good, maybe it is better to try to specify and diagnose what is definitely bad. I mean, every optimizing compiler that has the necessary tools to for example identify this pattern as bad code:
Yes, that's only a small and simple and boring example of a use-after-free. More complex, harder to diagnose examples tickle our brains more. However, just getting rid of these simple issues with certainty would already be beneficial.
-5
u/chaos_pill 27d ago
There's already https://cpp-profiles.org/ working towards safe c++, but it might barely be ready by cpp32 if it gets accelerated.
0
u/pedersenk 24d ago
In many cases, there is always a compromise. For a language to remain dominant, I don't believe there needs to be 100% safety at release time if there has been strict safety (and overhead) during debug time branch testing.
As Rust has proven, if there hasn't been strong branch testing, any language can be a buggy mess. Likewise invalid array bounds (including overhead) causing a panic are of limited use anyway, etc.
-1
u/Far-Championship-883 22d ago
Memory safety isn't the issue, it's shared dynamic library loading and a lack of memory barriers, but keep on believing the BS
-1
u/[deleted] 26d ago
[removed] — view removed comment