145 points · by ingve · 2y ago · 364 comments
The author is making a massive assumption that all CVEs are equally serious but they aren't. Opening the Rust links indicates several of them are denial of service, including regular expression denial of service. Not downplaying this, but compare it to the first result in the other link, which involves potential remote code execution (RCE).
Take for example CVE-2022-21658 (https://blog.rust-lang.org/2022/01/20/cve-2022-21658.html) in Rust, related to a filesystem API. It's true, this was a CVE in Rust and not a CVE in C++, but only because C++ doesn't regard the issue as a problem at all. The problem definitely exists in C++, but it's not acknowledged as a problem, let alone fixed. That's why counting CVEs alone is meaningless.
The author concedes that CVEs are not a good metric to measure by, but implies that maybe C and C++ have too many CVEs that shouldn't actually be CVEs and that the C++ community should take more control of CVEs being filed. This is ominous, and makes me fear we might start to see fewer C and C++ CVEs because issues will be closed as "intended behaviour" or "won't fix", like the filesystem issue above.
Can you find a link that substantiates your claim? You're throwing out some heavy accusations here that don't seem to match reality at all.
Case in point, this was fixed in both major C++ libraries:
https://github.com/gcc-mirror/gcc/commit/ebf6175464768983a2d...
https://github.com/llvm/llvm-project/commit/4f67a909902d8ab9...
So what C++ community refused to regard this as an issue and refused to fix it? Where is your supporting evidence for your claims?
This would be like saying C++ the language fixed buffer overflows because GCC added bounds checking. Most sensible C++ developers know that you should not depend on undefined behavior to write correct software, and yet your argument that because some implementations (not all) have decided to provide semantics for this, that it's now okay to use it or no longer a problem.
Where does it say that? Please point to the spec that says remove_dir is allowed to have TOCTOU security bugs in a system with multiple processes.
Relevant piece of the standard: http://eel.is/c++draft/fs.race.behavior#1.sentence-2
Officially it's undefined behavior.
And here's a comment from the maintainer of the STL in MSVC regarding this: https://old.reddit.com/r/cpp/comments/151cnlc/a_safety_cultu...
It's like your front door's lock. It doesn't have to be unpickable, unshimmable, absolutely secure. It just has to put up more of a fight than a brick through the window.
We have locks on windows, but rarely bars. We have alarms that trigger sirens, but rarely indoor locks. Eliminate quick and quiet, usually good enough.
What I like about the 100% memory safe goal is that it’s a falsifiable goal.
Even the Rust style goal of “you’re memory safe if you do 100% rust and never use unsafe” has the nice property of being falsifiable.
98% memory safe is not a falsifiable goal. It gives the C++ designers the option of never actually fixing the problem while claiming they had by picking a sloppy way of measuring the “%”.
He addressed that, the cost of making it to 0 would be too great (C++ would have to break backwards compatibility) so we should try and be inline with other languages instead.
I don't understand why you're acting as if he didn't make the point he made.
> I don't understand why you're acting as if he didn't make the point he made.
My confusion is that I'd expect breaking backwards compatibility to either be completely off the table or for the amount of breakage allowed to be up for debate. If you're not willing to break compatibility at all, I feel like the goal should be to shoot as low as possible without breaking anything; if it's possible to get as low as other languages, why stop there? If you're willing to sacrifice some backwards compatibility, why not be willing to break it a little more to eliminate the last few sources of unsafety?
If the language or a library promises to catch a mistake, and it doesn’t, that’s not automatically exploitable unless the programmer has actually made that mistake. If there wasn’t a promise in the first place, there would be nothing to report.
Unfortunately, CVE can’t see the difference between reporting a bug, or reporting a theoretical possibility of having a bug that never actually happened.
I'm not saying it is right, just that concerns around soundness will likely be hand-waved away. And it is to everyone's detriment.
So funding isn't the issue. The issue is that the committee has a firm commitment to never introducing breaking changes. This commitment is so firm that it trumps literally any other interest, like making the language memory safe. That's why the author only suggests non-breaking changes in this article.
Lots of people are going to have opinions on whether this approach is the right one for C++'s long term success, but I think we'll only know in 5-10 years.
> So funding isn't the issue.
does not follow from :
> There are a lot of people being paid by their companies to work on the C++ committee and on various compiler teams. The author of the post we're discussing is a member of the committee and this article is an attempt to improve the security situation in C++.
The people working on the C++ committee are mostly working on their own time. Specific project directly funded by companies are actually quite rare. And those mostly focus on companies very immediate needs.
If someone wanted to commit let's say 25$ million over 5 years, i am sure that both C++ standards and the major implementations would make large jump in term of safety.
> The issue is that the committee has a firm commitment to never introducing breaking changes. This commitment is so firm that it trumps literally any other interest, like making the language memory safe.
Yes C++ and its committee have very strong commitment to backward compatibility. However, that's not the reason for not wanting to make C++ memory safe : from what i understand, the committee decided that the tradeoff are not worth the gain, and as Hurb explain in this article, between tooling and reasonable default, it possible to achieve pretty good level of safety in practice.
> That's why the author only suggests non-breaking changes in this article.
Just to repeat my point here: no, Hurb is suggesting non-breaking changes because of the aforementioned commitment to back-compat. Even if breaking changes were to be introduces, they would most likely NOT be to make C++ a memory safe language whole sale
One of the proposals in the article is to change the meaning of things like "if (a != b > c)" and "if (0 <= index < max)". That changes program behavior and therefore is a breaking change (for instance, the code might accidentally be depending on the "wrong" results of these odd comparisons, and "fixing" them makes it go through an untested path which does the wrong thing).
I think the commitment is more that you can’t do anything to the language that would lead to some compiler hacker who also serves on the committee to have to remove their pet optimization, regardless of whether that optimization is worth much (or anything).
Goals and messaging matter. I like that the Rust community aims for safety as a P1 goal. C doesn’t, so C doesn’t get it.
The standards document isn't the same as a C++ implementation. The implementations are actually behind the standards, at least given current contribution levels.
There are relatively few people making significant contributions to C and C++ in compilers. Funding for middle and backend features to compilers are a lot easier to justify and fund because it looks like more straightforward optimization payoffs.
A lot of the effort put into C++ implementation work goes to keeping up with the pile of features added to the C and C++ standards every three years or so.
Memory safety bugs are only one class of security vulnerabilities, and there's nothing magical about memory safeness that causes a developer using that language to suddenly become expert at writing secure code.
For that matter, some vulnerabilities actually seem much more common in memory-safe languages - try searching the CVE database for "SQL injection c++" (287 results) vs javascript (3420), Java (2160), or PHP (11300).
98% of what? CVEs? Something else?
I think it’s kind of stretching it, but these are services where issues in them could impact you, so I don’t think it’s a total non sequitur.
Say, the "typical" rust laziness ... just unwrap() because well we know for sure it can't possibly be None, right ? Do that in a form of crit code path, and while that may not open you to an exploit, it'll still down your service and damn you to a crashloop.
Yes, we should be using memsafe languages. Yes, we should be a little humble about bugs we may create. As important as it is to entirely eliminate one "critical" class, as important it is to realize even with that gone, bugs/issues/security problems will remain.
That just plain wrong. Just simply wrong. And I hope it is not a lie done on purpose.
The C++ community acknowledge the issue as soon as the Rust one posted the problem and issued a fix which is already deployed with major compilers [^1] [^2]
It does not have a CVE associated since the issue was spotted within Rust stdlib first.
This is this exact kind of FUD and zealotism that makes people hate the Rust community. I wish the community mature a bit on this aspect.
[^1]: https://github.com/gcc-mirror/gcc/commit/ebf6175464768983a2d...
[^2]: https://github.com/llvm/llvm-project/commit/4f67a909902d8ab9...
I don't see why this is true. Are you saying that people with affected code would have seen a Rust CVE and then updated their C++ toolchains? There seems to be no reason this shouldn't have been a C++ CVE other than the fact that C++ community has different standards for what constitutes safety. The lack of CVE associated with the fixes you pointed out support the original assertion rather than refuting it.
In fact, I'll tell you why there was no CVE for C++ - concurrent access to filesystem APIs is undefined behaviour in C++ (https://en.cppreference.com/w/cpp/filesystem).
Reasonable people can disagree on this though, so I can see where you're coming from. There's no reason to immediately fling around accusations of lying and zealotry. It makes the writer look immature.
That's a serious question, if I open a file for reading and another process writes to it, exactly how is the C++ standards supposed to protect against that?
A security report has been filed for both compiler and actions taken for both of the major toolchain. This is a sign of mature security processes in used by both of the major C++ compiler implementations.
CVE are one among many way to address security vulnerabilities, one way that is currently heavily under criticism [^1]
> In fact, I'll tell you why there was no CVE for C++ - concurrent access to filesystem APIs is undefined behaviour in C++
The vulnerability reported (even in case of the Rust CVE) has nothing to do with a concurrent usage of the API. I think you do not really know what you are talking about here.
> Reasonable people can disagree on this though, so I can see where you're coming from. There's no reason to immediately fling around accusations of lying and zealotry. It makes the writer look immature.
My definition of immature includes the fact of throwing false statement over the internet, getting them refuted with sources and quote included. And still stance on them. This is a sign of immaturity.
[^1]: https://portswigger.net/daily-swig/cvss-system-criticized-fo...
"The behavior is undefined if the calls to functions in this library introduce a file system race, that is, when multiple threads, processes, or computers interleave access and modification to the same object in a file system."
and was told that made this bug not a compiler issues, but just undefined behaviour, exactly as if you'd written an array out of bounds or dereferenced an invalid pointer, the compiler can do anything it likes if another program changes the filesystem while your program runs.
There is a lot to bet that this has been added for portability reasons. The POSIX atomicity guarantees on file operations are not provided on every system.
The facts are, when this issue came, it has been treated as it should have been. This is, once again, a sign of mature security processes and behaviour regarding the compiler implementers.
That is blatant nonsense. Even if the vulnerability is similar or identical, CVEs are submitted for every affected project. If it were not there would not have been a bounds-check CVE in the last 35 years. The only situation in which that might not be the case is if the vulnerability is in an upstream library, but even then you often get a CVE in both upstream and downstream (or a CVE shared between multiple products) e.g. the libwebp 0-day from late 2023 got a CVE for Apple’s various OS (two in fact) and a shared CVE for libwebp and chrome, mozilla used that as their upstream CVE in emitting a security advisory.
The CVE-2022-21658 only covers the Rust standard library, that is not upstream of either libc++ or libstdc++, and neither fix references it anyway.
The GP might have gone a hair too far in saying that C++ “does not consider it a problem at all”, but they’re correct that C++ compiler/stdlib maintainers do not consider it a vulnerability.
No this is also just plain wrong.
It was reported to both compiler through channels dedicated to report security vulnerabilities and has been fixed as such.
The fact it did not make his way through a CVE is mainly related to how CVE naming and reservation works, nothing more.
I’m surprised Herb is so defensive here. He normally strikes me as level-headed but he’s arguing in bad faith here. There’s no way a language can prevent arbitrary code execution if the programmer intentionally wants to allow it as a feature & then doesn’t think through the threat model correctly or not managing infrastructure secrets (the latter btw is mitigated by Microsoft’s own efforts with GitHub secret scanning although there should be more of an industry effort to make sure that all tokens are identifiable).
But C/C++ is a place where 60-80% of the vulnerabilities are regularly basic things the language can mitigate out of the box. No one is talking about perfection. But it’s disappointing to see Herb stuck and arguing “there’s other problems and even if memory safety is an issue Rust has problems too”. The point is that using Rust is a step function improvement and provides programmers with the right tools so they can focus on the other security issues. A Rust codebase will take more $ to exploit than a C/C++ one because it will be harder to find a memory vulnerability which is easier to chain into a full exploit vs attacking higher level stuff which is more application specific.
EDIT: And language CVEs are a poor way to measure the impact of switching to Rust because it’s the downstream ecosystem CVEs that matter. I’m really disappointed this is the attitude from the C++ community. I have a lot of respect for the people working on it, but Herb’s & Bjarne’s response feels like an unnecessary defensive missive to justify that C++ is still relevant instead of actually fixing the C++ ecosystem problems (namely their standards approach is making them move too slowly to ever shore up their weaknesses).
Sutter pointing out that memory safety isn't the only vector for system vulnerabilities would have the effect of spreading cybersecurity efforts and budgets across all of them. In that case memory safety isn't the foremost problem it's being portrayed as, and it isn't worth migrating away from C and C++.
[1] - https://www.whitehouse.gov/wp-content/uploads/2024/02/Final-...
[2] - https://research.google/pubs/secure-by-design-googles-perspe...
> To be sure, there are no one-size-fits-all solutions in cybersecurity, and using a memory safe programming language cannot eliminate every cybersecurity risk. However, it is a substantial, additional step technology manufacturers can take toward the elimination of broad categories of software vulnerabilities.
And of course, Google as well.
Not even the most fervent memory safety advocates believe that it is the sole thing that will make software secure, so arguments like this come across a bit strange.
I called out those two reports because for the first time in forever, there's actual impetus to move away from C and C++. That challenges the standards committee's usual stance that the status quo is acceptable. That's why we see Herb Sutter actually engaging with the issue of memory safety here. Compare that with Bjarne Stroustrup's earlier glib dismissal of these concerns, where his talk started with "The Case Against Switching Languages". Kinda shows where his priorities lie.
You must be new to HN, yes?
;0
You do not want the blob of D.C. putting their eyes on anything that looks like a bottomless money pit for consultants and self-proclaimed experts. Once that happens and is codified to some degree in law, it's very difficult to change or remove.
This potentially affects every government system in existence, and those systems are already some of the most legacy systems today. The US Navy still pays Microsoft to maintain support for Windows XP, so the idea this will happen in any less than a 25 year horizon is absurd. And even then, the dates can be extended. Why put a stop to the gravy train when it can keep going -- it's not like the public is even aware of just how enormous the federal government really is. Once you understand this an opportunity to extract billions of dollars from large organizations, you then have to ask what their lobbyists will do to change the laws in their favor to completely neuter the legislation codified into law.
I haven't see anyone even consider this highly likely, if not almost certain outcome.
On one hand you're saying the problem is intractable and it'll take 25 years to solve. Then why are you criticising an effort to get the ball rolling?
You're frustrated by the Government using old, outdated and possibly insecure software. Then surely the White House exhorting the Federal government to fix these issues and procure software without issues is a good thing?
Of course any change is an opportunity for consultants to make money, but that doesn't mean the change isn't needed or that the White House is wrong for starting it.
The problem in C/C++ is that pointers don't inherently communicate their bounds, so your options for adding automatic bounds checking are a) fat pointers and consequently (severe) ABI break; b) some sort of shadow memory to store bounds info (ASAN, generally considered inadvisable to use in production); or c) change the language to communicate what the bounds of a pointer are. The good news is that most interfaces will provide the bounds of a pointer as another member of the struct or the function parameter it's part of; the bad news is that actually communicating that information requires a scope lookup change that is hard to get through the committees.
It’s not an unfixable problem.
I wish we were talking about fixing it, not making excuses.
C/C++ maintainers knew this and didn't want to see their lives' work made less significant. Now the issue's been forced by (among other things) one of the world's most influential software customers, the US Federal Government, implying that contract tenders for software written in languages like Rust will have an advantage over those written in languages that don't take memory safety as seriously.
ABI breaks are not a real solution to the problem. When you talk about changing the ABI of a basic pointer type, this requires a flag day change of literally all the software on the computer at once, which has not been feasible for decades. This isn't an excuse; it's the cold hard reality of C/C++ development.
There is no solution that doesn't require some amount of software change. And the C committee is looking at fixing it! That's why C23 makes support for variably-modified types mandatory--it's the first step towards getting working compiler-generated bounds checks without changing the ABI and with relatively minimal software change (just tweak the function prototype a little bit).
Do you have any guesses on whether it could easily target WebAssembly? I'd imagine many people would like to run C code in the browser but don't want to bring memory unsafety there.
link: https://github.com/pizlonator/llvm-project-deluge/blob/delug...
union MyObject {
void* ptr;
unsigned long data;
}
(...)
MyObject obj;
obj.ptr = (void*)some_function;
(...)
store_context(obj.data);
And what would happen to such code if pointers are suddenly fat?The thing is, it's fine to take that risk if you're writing HPC simulation software, but it's much less fine if you're writing an operating system or similar.
Apple has tested this, on mobile devices even, when working on -fbounds-safety. From the slides:
System-level performance impact
• Measurement on iOS
• 0-8% binary size increase per project
• No measurable performance or power impact on boot, app launch
• Minor overall performance impact on audio decoding/encoding (1%)
• System-level performance cost is remarkably low and worth paying for the security benefit
Some more specific synthetic benchmarks suites reported ~5% runtime cost for bounds checking.https://www.youtube.com/watch?v=RK9bfrsMdAM https://llvm.org/devmtg/2023-05/slides/TechnicalTalks-May11/...
Bounds checking being omitted due to performance is mostly a myth, the only time this should ever be believed is in very specific circumstances such as performance critical code and when the impact has actually been measured!
It’s also just legacy. We’ve always done it that way so we still do it that way for ABI compat and because it’s hard to find a compiler that does it any other way.
Imagine if the story was: “you totally can have a bounds on your ptrs if you pass a compiler flag and accept perf cost”.
I bet some of us would find that useful.
You can do it in C as well, although it's a lot clunkier. I've been doing so for decades when the effort is appropriate to the task.
C is probably unfixable. But that's a different language.
Presumably compilers would allow conversion of spans to native pointer arguments when calling methods declared as "extern 'C'".
In structs there is no existing extension, but a simple accessor macro that casts to a VLA type works already quite well and this can be used by refactoring existing code.
There are still some holes in UBSan, but otherwise I think you can write spatially memory-safe C more or less today without problem. The bigger issue is temporal safety, so the bigger puzzle piece still missing is a pointer ownership model as enforced by the borrow checker in Rust.
I wouldn't call it a solved problem until gcc and clang have an auto-inserts-bound-check flag that does the equivalent of a Rust panic on every array access if it's out-of-bounds, is considered usable on production code [1], and works on most major projects (that care enough to change their source to take advantage of this flag). Overall, the problem isn't so much that we don't know how to write safe C code, it's that the compiler doesn't quite have enough information to catch silly programmer mistakes, and there current situation is juuuuust bad enough that we can't feasibly make code that doesn't tell the compiler enough error out during compilation.
> The bigger issue is temporal safety, so the bigger puzzle piece still missing is a pointer ownership model as enforced by the borrow checker in Rust.
Temporal safety is interesting in part because it's not clear to me that there currently exists a good solution here. The main problem, like existing partial solutions for spatial memory safety, is that the patterns to make it work well are known, but programmers tend to struggle to apply all of the rules correctly. Rust's borrow checker is definitely a step up from C/C++, but at the same time, there are several ownership models that it struggles to be able to express correctly, even if you ignore the many-readers-xor-one-writer rule that it also imposes. Classic examples are linked lists or self-referential structs, but even something like Windows' IOCP can trip up Rust's lifetime system.
Although, at the very least, a way to distinguish between "I'm only going to use this pointer until the end of the function call" and "I'm going to be responsible for freeing this pointer you give me, please don't use it any more" would be welcome to have, even if it is a very partial solution.
[1] Don't get me wrong: the development of the sanitizers is an important and useful tool for C/C++, and I strongly encourage their use in test environments to catch issues. It's just that they don't meet the bar to consider the issue solved.
Look at past Scott Meyers talks (e.g. [1]). He highlights how the committee has arbitrary set of principles that can be applied to justify or reject any proposal and the inconsistencies in the language are a reflection of this.
This isn't a problem of the language itself but rather that it's design by committee with 4 major front-end implementations (Intel, MSVC, Clang, GCC although I believe Intel is standardizing on the Clang front-end at least). Organizational issues like that are tough to spot but it's become clear now for several years that Rust is going to beat C++ silly if the C++ committee doesn't clean up their act and steer the C++ community a bit better (e.g. still no ABI specification, no improvements on macros, no standardized build system, modules are a joke, no standardized package system, etc etc). They're not effective stewards not least of which because they can't even take good impactful ideas from Rust and copy them.
https://www.digitalmars.com/articles/C-biggest-mistake.html
which is adding slices to the native language. This will eliminate buffer overflow errors (if the user uses that feature). D has had this from the beginning, and while it doesn't cover everything, that feature alone has resulted in an enormous reduction in memory safety errors.
BTW, D also has a prototype ownership/borrowing system.
There is, BTW: https://datatracker.ietf.org/doc/html/rfc8959
Getting people to use the standard is another matter.
> One reason is that Rust’s safe language pointers are limited to expressing tree-shaped data structures that have no cycles; that unique ownership is essential to having great language-enforced aliasing guarantees, but it also requires programmers to use ‘something else’ for anything more complex than a tree (e.g., using Rc, or using integer indexes as ersatz pointers); it’s not just about linked lists but those are a simple well-known illustrative example.
But then later on, seems to ignore the safe alternatives and commits a non-sequitur:
> That’s because a language’s choice of safety guarantees is a tradeoff: For example, in Rust, safe code uses tree-based dynamic data structures only. This feature lets Rust deliver stronger thread safety guarantees than other safe languages, because it can more easily reason about and control aliasing. However, this same feature also requires Rust programs to use unsafe code more often to represent common data structures that do not require unsafe code to represent in other MSLs such as C# or Java, and so 30% to 50% of Rust crates use unsafe code, compared for example to 25% of Java libraries.
In other words, Sutter acknowledges the safe alternatives at one point, but then ignores them later. When ignoring them, it allows Sutter to draw a conclusion as to why some percentage of Rust code uses `unsafe`. And even if ignoring those alternatives was appropriate here, I still see no reason to believe that 30%-50% of Rust crates use `unsafe` precisely because of the limitations around cyclic structures. There are many more reasons to use `unsafe`.
This is particularly misleading for two reasons:
1) There are a lot of `-sys` crates which link to C libraries, so the "unsafe" code in these crates comes from the binding to C rather than some limitation of Rust. Often there are 100% safe Rust alternatives to these C libraries as well.
2) Of the remaining crates which use "unsafe", the unsafe code is often contained to a tiny percentage of the code, so if we're looking at the overall amount of unsafe code, you're going from 100%, to a fraction of a percent.
By any fair measure, unsafe Rust is a tiny fraction of total Rust code.
In my experience, the community eschews it with a fervor bordering on religiosity.
Sure... but it's still unsafe code ... with the the consequences of unsafe code. Also doesn't also explain the 30 % to 50 % vs 25 % in Java. My guess would be that java just care less about perf. I mean if blaming a language "unsafeness" on C is an options, i submit that a lot of the unsafe part of C++ where imported wholesale from C.
> 2) Of the remaining crates which use "unsafe", the unsafe code is often contained to a tiny percentage of the code, so if we're looking at the overall amount of unsafe code, you're going from 100%, to a fraction of a percent.
Three points :
First, code volume is a good proxy only when the code samples are uniformly distributed : while the unsafe code might be a tiny percentage of the code base, they might represent a large percentage of runtime and/or a large part of the algorithmic complexity of the whole project.
Second going from 100 % to tiny fraction implies that C++ is 100% percent unsafe... and that's not the case. There is safe subset somewhere deep in there.
And third, "unsafe rust" is not safer than "regular C++" . Mixing those 3 factor makes the finally "safety" tabulation much more complicated than just counting number of unsafe regions
I dislike this argument because rust unsafe code is typically placed into a module with safe code around it protecting it.
Guess how good C++ code is written?
exactly. The unsafe keyword certainly helps but is not a panacea nor a guarantee given that a bug in the safe code that's protecting the unsafe code could be the root cause for security issues, even if it manifests itself in the unsafe code.
> but is not a panacea
Do you have a source to literally anyone credible saying Rust is a panacea?
> nor a guarantee given that a bug in the safe code that's protecting the unsafe code could be the root cause for security issues, even if it manifests itself in the unsafe code.
This just in. Rust doesn't guarantee bug-free code. Holy shit. What a revelation! Like, really? That's your problem with the argument? That it doesn't live up to the standard that bugs can't exist?
The value proposition of Rust has, is and always will be that it can encapsulate a core of `unsafe` usages in a safe API with no or very little overhead. The promise of Rust is that this power of encapsulation will lead to less undefined behavior overall. Not that it literally makes it impossible because, well, yes, you can have bugs in `unsafe`!
To head off the pedants, yes, not everything can be safely encapsulated in Rust. File backed memory maps are my favorite example. And yes, bugs in not just `unsafe` blocks but bugs in the language implementation itself can lead to UB.
And yes, Rust achieves this through a trade off. As Sutter mentioned. None of this should be controversial. But what Sutter misses is a fair analysis of this trade off IMO. He does a poor job at representing its essential characteristics.
I think it's possible to read the argument in the way that make sense.
I don't think that Hurb is making the point here that Rust code uses more unsafe code pacifically "because" the the tree-base dynamic data structures restrictions. It seems that he took this simply as an illustration of a larger point.
The point he is making is that programming language safety is always a trade-off. Rust and Java are making different trade-offs which results in a different level/kind of safety.
We should also note, even if there are "safe" alternatives in rust, it doesn't mean those alternative are viable in term of code complexity, performance, cache behavior etc... etc... So the existence of safe alternative doesn't negate the need to use unsafe if one doesn't like the trade-off those safe alternatives imply.
I don't think it's a particularly big problem that more part of rust are unsafe vs Java, and probably reflect rust focused on native performance more than anything else.
But for the purpose the Hurb conversation here, this fact is important to note.
> However, this same feature also requires Rust programs to use unsafe code more often to represent common data structures that do not require unsafe code to represent in other MSLs such as C# or Java, and so 30% to 50% of Rust crates use unsafe code, compared for example to 25% of Java libraries.
This isn't a carefully considered statement about trade offs. This is sloppy reasoning. For example, if the reality were that 99% of that `unsafe` code were just FFI interactions with programming languages that are memory unsafe by default, then that would kind of undercut the entire point here. That is, it wouldn't really be Rust's fault. It would be the fact that we've lived in a memory unsafe hegemony in systems languages for the last several decades. That's just reality.
Of course, I'm sure it isn't 99%. But I'm also sure it isn't 1% either. The reality is so much more interesting than "30%-50% of all crates have `unsafe` in them." And that reality could very well undercut the entire point Sutter is making in this part of the article.
For the sake of completeness, it's possible to express certain cyclic graph patterns without overhead in safe Rust. But it's usually too much of a hassle to bother with. https://docs.rs/ghost-cell/latest/ghost_cell/
I've been a c++ dev for 30 years. I'll be retiring in a decade (or perhaps keep going), and I doubt I'll ever see a 'safe' C++ in my working life.
If the committee were even truly serious they'd adopt epoch releases and feature flags in the language spec (see Circle, doing it for real), starting in c++26, the next release. And adopting tooling as part of the standard like every other language. As usual, C++ is the outlier here.
Then meaningful progress might start to be made in a measurable and testable way.
Instead I'll read another dozen articles like this for next 5-10 years, and any talk of tooling or epochs will be kicked down the road for another few years as usual.
But it's been a good lesson for all the other languages for better and worse.
With feature flags and epochs, it is possible to evolve C++ in the right direction with the minimum of friction and make it opt-in in a consistent fashion. Circle already proves this a feasible approach, and that's a one-man project. There's also clang tooling that modernizes old C++, and huge amounts of work on LSPs and the like for refactoring, so it is possible to provide tooling that mechanically fixes-up a large portion of old code.
This is how I expect the issue to be addressed because there is too much invested in backward compatibility. Some C++ development, usually around high-performance high-reliability systems, already operates this way to a significant extent, using an alternative re-spin of the language primitives from the ground up that make stricter guarantees and enable greater composability and verification. C++20 in particular makes a nice base for building this.
You won't be able to force people to do things in a rigorous way, but providing a complete alternative goes a long way toward enabling safer code. I've seen alt standard C++ reduce bugs by an order of magnitude in real code bases (generally, since memory safety bugs are pretty rare in modern C++ in my experience).
The rigor can be put in the tooling, at the compiler level, as a flag. Then there's no 'forcing', it's just not possible to do certain things. Which is what is being advocated.
Hoisting it a level further, to the build system, means downstream dependencies can (also) be compiled 'safely', or required to be safe, by default.
Sticking a [[safe]] attribute into the language for regular source files would be a disaster. What's the point of one safe function in a library when the rest of it isn't safe?
Having said all that, I don't disagree with anything you've written regarding idiomatic c++20 reducing safety issues, it's just that it's a problem that can be and should be addressed mechanically in the tooling. I'm just really, really, doubtful that C++ will ever get anywhere near 'safe' in the next decade, or, really, next couple of decades.
Herb mentions std::span as as safety improvement but the [] operator doesn't do bounds checks and the .at() method isn't even there yet!
Shameless plug but I discuss this issue on my blog: https://btmc.substack.com/p/memory-unsafety-is-an-attitude-p...
Herb and Bjarne have the right attitude, sadly it doesn't seem enough C++ devs or people in the standards committee do. Same applies to C.
I need to find the source, but someone pointed out that the safety advantages of Rust are, in part, cultural and I increasingly agree. People use Rust because they care about memory safety and that care is reflected in the programs they write.
weirdly I see this most often from programmers who started college less than 11 years ago. Our accidemics are not helping.
There is a human factor at work here. Rationally speaking, Herb is right 98% reduction is sufficient. But when the CTO's head is on the line, they won't listen and switch to Rust.
Infrastructure network code that runs on millions of servers worldwide is a completely different story. Being able to send a sequence of bytes that unlocks funny side-effects of a network service can be weaponised on a mass scale.
I'm betting here they don't; if they have security breaches it's due to '1q2w3e' being the password to their world-accessible PHP admin panel, and not because of C++ code.
https://www.bell-labs.com/usr/dmr/www/vararray.pdf
It is a culture thing, eventually the authors don't have any last words to say, if they let the community rule the language design, and their voice is equally one vote.
This says it all really. Nothing more needs to be said. Unfortunate.
That criticism misunderstands the actual way the C++ committee works. They're not a supreme legislative group that can dictate what a new C++ should be and everybody else is required to just obey. In contrast, Apple can dictate what the next version Swift will do. Microsoft can do the same with C#.
Instead, what happens in C++ is somebody or company makes a proposal with some concrete working code for others to evaluate and vote "yes" on. So the reality means one of the teams from MSVC, gcc, clang, Intel C++, etc have to take the lead with a Safe C++ alternative that convinces everybody else to implement.
To Herb Sutter's credit, he did make a "C++2" implementation: https://github.com/hsutter/cppfront
But his side project at Microsoft didn't gain traction with gcc, clang, etc and everybody else in the industry. So at this point, the C++ committee will be perceived as "so far behind" ... because there's nothing for them to vote on.
Similar situation happened with "breaking ABI compatibility". Google wants to break ABI but others didn't.
Yes, but your complaint about flawed C++ standards or incomplete implementations is orthogonal to what I was writing about.
I'm just explaining that the C++ committee doesn't have the power to impose changes that some people think it does. Basically, I'm saying "the sky is blue" type of statement. The C++ committee is a reflection of what the members' compiler teams want to collectively do. The committee doesn't have unilateral supreme power to dictate standards to compiler teams not interested in it. Instead, they collect feedback from people sharing proposals in papers and put things to a vote. The compilers' teams have the real power and not the committee. (What I've stated in this paragraph should be uncontroversial facts but the downvoters disagree so I'd love to hear them explain exactly what power and agency they think the C++ committee actually has.)
If one understand the above situation, then the following different situations shouldn't have any mystery as to cause & effect:
- How did the std::chrono get added to the standard library? Because Howard Hinnant made a proposal with working code, and others liked it enough to vote it in.
- Why is there's no _standard_ cross-platform GUI and audio library in C++? Why is there not standardized Safe Syntax C++ like Rust? Because nobody has made a proposal that convinced enough of the other members to agree to a x-platform GUI and audio framework.
- Why does C++ committee adds features and prioritizes things I don't care about? Because the <$feature$> you cared about wasn't proposed for them to discuss and convince others enough to vote it in.
But yes I do understand the "warts" complaint you're talking about. It's frustrating that the std:regex with bad performance got approved. In similar examples, N Josuttis in multiple conference videos has complained about the problems with ranges and views. He says it was wrong for the C++ committee to approve it. (footnote: The original author of the proposal tried to explain his technical rationale: https://old.reddit.com/r/cpp/comments/zq2xdi/are_there_likel... )
To reiterate, I'm not trying to explain away bad language standards. New features that will have flaws will continue to happen in the future whether it's created by a singular corporation like Apple(Swift) or a cooperative group like the C++ committee.
I'm just explaining why some "wishlist desirable C++ feature" isn't going to be in the standard if there's no proposal that convinces the other members to vote it in.
EDIT to reply: >When we complain about the "committee" [...] the things they choose to propose and vote for.
The C++ committee members are not static but the webpage has list of names : https://isocpp.org/wiki/faq/wg21
Clicking on various PnnnnR.pdf proposals that motivated each feature in the conformance table shows most authors are not from the actual committee members: https://en.cppreference.com/w/cpp/compiler_support
Using the above workflow to address your complaint about std::span and at(), I found this comment from the original author Tristan Brindle who proposed it and why he thinks the committee voted no:
2019-10-18T22:55:30z https://old.reddit.com/r/cpp/comments/djqdu2/why_is_stdspan_...
And I don't see a big push in the community to enable them. I think the committee is just an expression of the community on this front.
That's a choice though. You can enable these in your production builds if you want (with libstdc++ at least) and some Linux distributions have chosen to do just that.
The thing though is that these checks are NOT free and the overhead is not justified for all use cases so forcing them on everyone is not appropriate for C++.
Well, that's why they should be a flag. The question is whether it should be enabled by default or not.
You mean this implementation? https://en.cppreference.com/w/cpp/container/span/at
To quote: "Returns a reference to the element at specified location pos, with bounds checking.
If pos is not within the range of the span, an exception of type std::out_of_range is thrown."
The committee just publishes documents. It is actually far ahead of C++ implementations.
The committee would probably move faster if there were more attention (and funds and volunteer work) spent on advancing C++ implementations. This especially seems true for safety and security concerns as they tend to have more tangible problems to solve than the other kinds of standards proposals.
The standard is prioritizing the wrong things. It's normal that implementations are struggling when they need to implement something as complicated as C++ modules for example. There's no excuse for the .at() method being missing from std::span.
On the C side of things the problem is more egregious, it took over 30 years to standardize typeof after every compiler ever had already implemented something of the sort. GCC's __attribute__((cleanup)) should have definitely been standardized ages ago with so many libraries and codebases relying on it.
What does the C standard give us instead? _Generic. It's just silly at this point.
The issue is that there are two camps. One believes that precondition failures should not be recoverable and should abort the application and thus think that 'at' is an abomination. The other believes that throwing exceptions on the face of precondition failure is appropriate.
Hence what goes into the standard depends on how many people on each camp are present at each committee vote. This is also one of the reasons why the contracts proposal is not yet in the standard.
On a more practical side, .at does not help in any way to bound check the hundreds of billions of existing lines of C++.
> “First make them care, then make it easy for them to do the right thing.”
I would say first make it easy to do the right thing, making them care will be an Eternal September.
At this point I think heads need to roll before people take the problem seriously.
I think that implementing in compilers the mechanisms for doing the right thing can be done first, and relatively quickly. Which now that I think more about it, would need the right attitude on the part of the compiler vendors and standards committee.
And since you now have a proper access API, you could on theory enable bounds checks via compiler flag, even for operator[].
I have to say, this sentence annoys the heck out of me.
Old code that can't be understood needs to be rewritten anyway. And since you're rewriting, you can apply the safety rules -- which would be better anyway.
If the code belongs to a third party and they don't want to update, it means the third party is playing against you -- or, worse, that they control how you're going to move forward. It's in your best interest, in this case, to rewrite the third party dependency as soon as possible, and since you're rewriting, you can apply the safety rules -- which would be better anyway.
If the code is shared and the upstream does not accept patches and -- worse -- doesn't support forks, then you have an issue with the upstream anyway and -- guess what -- you'd be better rewriting it anyway.
All those issues are managerial issues, not software issues. Management decided that it is better to be stuck than moving forward. And they can happen with any languages, not just C++.
Adding these things as "we can't be totally safe" are like "I can't jog every afternoon 'cause bears/alligators/wild life may jump an attack me". It's pure excuse to NOT do things.
> Old code that can't be understood needs to be rewritten anyway.
I don't think it's that old code can't be understood, you can always understand what code is doing mechanically.
it's a question of can you predict the consequences. For example, if I rename this database column, what in our systems that have been built over the last 30+ years will explode? That's data rather than code, but the underlying idea is the same.
What happens is the very act of rewriting it puts you at risk of adverse effects.
Fil-C fixes it (albeit just for C, for now). CHERI fixes it (and it works great for C++). There are other systems that fix it, too.
I loved the language; I even used it for web development for a couple of years and it was enjoyable to do so; but I did step away, and at this point I'd rather use Rust (a language I neither love nor find enjoyable).
Not sure the C++ committee have the capacity to "fix" this (whatever that may mean), nor whether the industry would let them, even if they were able to recognize the cognitive burden as a problem.
Both not really welcomed in most C++ circles, where naturally one codes close to C, with a thin layer abstraction wrapping OpenGL/Vulkan/DirectX in imGui for the ultimate performance, meanwhile the same authors use an Electron based application to write their code.
This is what made eventually move away into managed compiled languages, C++ isn't really the same as used to be, my next favourite programming language similar in spirit to Object Pascal, as in the last century of desktop GUI frameworks.
It feels like the programming community can do so much better, having seen the other side of it, but there's an immense amount of legacy code that's holding us back. Especially if you're going into more serious game dev territory, it seems practically unavoidable.
I am sure that Herb wrote this with good intentions, but no concrete measures was proposed but trying to standardize compiler tools, and to some extent downplay Rust.
I agree there is a misconception around programming safety, but this reads the same as when big industry say the want to focus more on climate change.
> An oft-quoted number is that “70%” of programming language-caused CVEs (reported security vulnerabilities) in C and C++ code are due to language safety problems... That 70% is of the subset of security CVEs that can be addressed by programming language safety
I can’t figure out what the author means by “programming language-caused CVE”. No analysis defines a “programming language-caused CVE”. They just look at CVEs and look at CWEs. The author invented this term but did not define it.
I can’t figure out what the author means by “of the subset of security CVEs that can be addressed by programming language safety”. First, aren’t all CVEs security CVEs? Why qualify the statement? Second, the very post the author cites ([1]) states:
> If you have a very large (millions of lines of code) codebase, written in a memory-unsafe programming language (such as C or C++), you can expect at least 65% of your security vulnerabilities to be caused by memory unsafety.
The figure is unqualified. But the author adds multiple qualifications. Why?
[1] https://alexgaynor.net/2020/may/27/science-on-memory-unsafet...
Personally, I think C++ has too much cognitive load. Over multiple decades, many features were added and very few were removed. The result of that process is having code that reads like mixing Latin with Ancient Egyptian hieroglyphs and then followed by TikTok jargon.
I also think the same thing about Rust.
RAII adds a humongous cognitive load to a language and I'm not really sure what you do about that.
Zig is a step in the right direction with a bunch of the sharp corners in C filed down--slices and default non-null pointers is a big improvement.
However, there are some things (like reference counted data structures) that are really annoying to implement in C/Zig that are really easy to implement in C++/Rust.
How does it add cognitive load? Compared to manual resource management it certainly removes a lot of cognitive load. And what is the alternative?
Genuinely curious, since I find it quite easy to work with.
Obviously Mozilla's challenges are multifaceted and don't boil down to user-invisible code rewrites. But, at best, switching to Rust was an orthogonal engineering concern that has opportunity costs.
There's no technical solution to that problem.
If you're saying there's no technical path to success for Mozilla... well, that might be true, but I could see that being demotivating for Mozilla engineers.
Key quotes from the Google paper:
> We see no realistic path for an evolution of C++ into a language with rigorous memory safety guarantees that include temporal safety.
> In our experience, it is not sufficient to merely make safe abstractions available to developers on an optional basis (e.g. suggested by a style guide) as too many unsafe constructs, and hence too much risk of bugs, tend to remain. Rather, to achieve a high degree of assurance that a codebase is free of vulnerabilities, we have found it necessary to adopt a model where unsafe constructs are used only by exception, enforced by the compiler.
It seems like Herb Sutter at least partially agrees with the second point in his TL;DR:
> I just want C++ to let me enforce our already-well-known safety rules and best practices by default, and make me opt out explicitly if that’s what I want.
[1]: https://security.googleblog.com/2024/03/secure-by-design-goo...
Yeah that sound like most security researcher i have talked/listen to. They see the problem as safety maximization problem. While in the real world, there are 50 different other constraints that a language design needs to navigate.
The point Herb was making is that "rigorous memory safety" isn't the only bar, nor should it be. Saying there is no way to make C++ have rigorous memory safety is not the same as saying C++ can never be made safe.
"All dereferences are null-checked. The compiler injects an automatic check on every expression of the form *p or p-> where p can be compared to nullptr to null-check all dereferences at the call site (similar to bounds checks above). When a violation happens, the action taken can be customized using a global null violation handler; some programs will want to terminate (the default), others will want to log-and-continue, throw an exception, integrate with a project-specific critical fault infrastructure."
make me just feel sad about the future of C++. The problem is not only CVEs, the problem is that the language makes doing the right thing hard and doing the wrong thing easy. All larger C++ projects I've worked on already use an enormously complicated and fragile combination of compiler-warnings-as-errors, static analyzers and linters to fix these problems and standardizing these is a worthwhile effort to reduce differences between different compilers and tools and to get to a bare minimum standard that everybody can agree on. The problem is that most projects won't adopt these until the 2030s or 2040s and then they will only create a bare minimum bar of safety and convenience when new projects could just use Rust and get a very well thought out safety model and other benefits (no inheritance, const-by-default, etc) at little extra cost.
The type system and metaprogramming capablities of C++ are really nice (when compared to Rust), but at this point the language is only relevant for the existing (thriving) codebases that use it and for historic reasons, but no sane person would choose it for an new project anymore, which makes me sad. I don't see how C++ can reinvent itself and stay relevant without a radical break that takes the last 20 years of language development into account. Also, finally put some coroutine compatible event loop in the standard library FFS, it's 2024.
How about not connecting your critical infrastructure directly to the Internet.
I didn't read the article (just browse it) but here's the TLDR from the article itself:
``` tl;dr: I don’t want C++ to limit what I can express efficiently. I just want C++ to let me enforce our already-well-known safety rules and best practices by default, and make me opt out explicitly if that’s what I want. Then I can still use fully modern C++… just nicer. ```
As is normal in C++, the defaults are wrong. Developers should "opt in" for unsafe instead of "opt out" of it!
Why ? C++ guiding principle is zero cost abstractions.
Isn't this exactly what he is saying?
The stuff Herb mentions as solving "98% of the problems" do not do that. First of all, they don't do that now, because they aren't on by default. At least he accepts this, but people have been claiming that C++ is great now because all these things are easy to do, and the fact is that nobody actually does it. Every other language is shipping this as table stakes and C++ hasn't even gotten its pants on yet. Second, in the surfaces that do actually care about this (think web browsers) they are putting a huge amount of time and money into solving this regardless of what the language does by default. We're talking automatic initialization, bounds checks enabled by default, all sorts of smart pointers and "production" sanitizers. They are still being exploited. Yes, your average script kiddie isn't taking down Chrome these days. But nation states still do it. They don't care that you go to 98%! They find a bug, they exploit it.
The rest of the post is just the usual talking points against every other language that exists. A lot of it is wrong. I'm not going to dwell on the whole "Rust takes CVEs that C++ doesn't" argument because I think this misses the point, personally (Rust has a different safety model, so problems under that safety model are just as valid problems with Rust. You can't go "oh we are safer by default" and "oh actually this makes things a lot harder for us so don't judge us when things are broken). However, a lot is just wrong. Languages that do not corrupt their VMs on races are better in many ways than C++, because in C++ anything of that sort is basically a direct path to code execution. In other languages you have to work for it. In Rust people use unsafe–but that doesn't mean it's automatically as unsafe as C++. It just means that people write a little bit of code using it and then build on top of it. In garbage collected languages the runtime gets super upset if you hold on to references when it thinks you shouldn't. However, doing this is a performance and in some cases an issue of leaking resource. It is not comparable to, say, a UAF in C++. Basically, you can't just go "oh every other language has [problems I looked up on Google] this means they are also bad". Because in C++, the problems almost invariably lead to a foreign government taking control of your phone. This is not true for other systems.
Rust is 10 years old this year, yet there are no production level browsers or operating systems written in it!
I’m talking about Google. They come up with article after article about the failings of C++, yet would prefer starting their own programming language Carbon, continue using C/C++ for chrome, zircon and android.
I disagree. We shouldn’t aim for 90-98%. We should aim for 100%.
Reason: unlike logic errors, memory safety bugs are exploitable more often than not. Logic errors are usually just some useless glitch and only sometimes exploitable.
> rust has 6 CVE’s
Couldn’t quickly check if any of those six were memory safety or not.
It’s sad that rust still has memory safety issues and if that’s true then my conclusion is that rust isn’t safe enough.
Let's assume all the CVEs are memory safety issues (some are not, some are, in reality.) Even then, they're things like "a bug in the standard library" that was then fixed. All software has occasional bugs. It is not possible to never have bugs.
It makes sense in a way. If you don't aim for zero, what do you aim for? A few hands lost in a month? A few crushed fingers?
In this viewpoint I'd argue that aiming for a 98% reduction is a bit absurd: "Yeah we had an issue but it was the only one this month so it's within our budget."
Of course, goals are not the same as realised results. Getting a 98% reduction should be considered a huge, huge win. The next step should then be "what can we do to get rid of the rest?" Or at least the alternative seems odd: "We got this far, job done, nothing useful to do anymore."
Of course, the means will change. If C++ guarantees full memory safety next month, then the next steps after that won't be more memory safety but something else.
But you also balance that goal against practical reality. For example, you could end workplace accidents by outlawing work and having everyone starve to death, but that's not done because the costs are too high.
If C++ had memory safety next month then the next step would be to add stronger types. Once memory safety is a thing, you can start to add types that describe contracts and then you can ensure lots of interesting logical safety properties that aren't memory safety.
It's not a great outcome if there are memory safety bugs arising from how some Rust programmer did some stuff.
So, I would revise my statement to: "It would be sad if Rust had memory safety issues that any user of the language could run into, and if that was true, then my conclusion would be that Rust isn't safe enough."
Disregarding entirely the memory safety aspects of turning a pointer access to an index access, there are benefits for using arenas (or struct of arrays) like better cache locality on access/avoiding memory fragmentation, and bunching values that don't outlast each other into a single free operation.
There's also of course everything else, like the ergonomics, freedom from data races and so on, but I'll skip that.
That said … there are ways in Rust to do circular data structures that don't have the problems that using indexing into an array has, and are memory safe, and are within the safe subset of Rust. (E.g., Rc/Arc.)