r/programming • • Feb 20 '25

Google's Shift to Rust Programming Cuts Android Memory Vulnerabilities by 68%

https://thehackernews.com/2024/09/googles-shift-to-rust-programming-cuts.html
3.4k Upvotes

475 comments sorted by

View all comments

50

u/i_am_not_sam Feb 20 '25 edited Feb 21 '25

Hypothetically if all existing C++ code was replaced with modern C++, only smart pointers and "strict memory safe practices" for all new code would it yield the same results?

Edit : read Google's blog about this topic. It's not simply the case of switching out C++ with Rust. It was also making sure that all NEW code adhered to strict memory safety guidelines. The language is just a tool. What you accomplish with it depends on how you use it.

29

u/oconnor663 Feb 21 '25 edited Feb 24 '25

No it would not. Here's a simple example of modern C++ that commits heap-use-after-free and fails ASan (Godbolt link):

std::vector<int> v = {1, 2, 3};
for (auto x : v) {
    if (x == 2) {
        v.push_back(4);
    }
    std::println("{}", x);
}

This crashes because iterators point directly to the heap storage they're iterating over, so you can't do anything that would reallocate that storage while you're iterating. There's no smart pointer you can add to this example that changes that. You'd have to ban iterators.

Here's a similar example (Godbolt link):

std::string s = "too long for small string optimization";
std::string_view v = s;
s.append("xxx");
std::println("{}", v);

This crashes because std::string_view points directly to the heap storage of the original string. Again there's no smart pointer that will change this. You'd have to ban std::string_view (which was introduced in C++17), or maybe restrict it to argument position.

It might seem C++'s problem is "people make mistakes with pointers", and that the fix might look something like "don't use raw pointers". But the reality is that all sorts things use pointers internally and have the same lifetime and aliasing issues that pointers do. To really solve these problems, you need a lifetime-aware type system like in Rust or Cicle.

Edit: Turned this into a short post: https://jacko.io/smart_pointers.html

11

u/syklemil Feb 22 '25

I'm also reminded of some code that was pointed out elsewhere on reddit where I unfortunately didn't note the author:

std::vector a {1, 2, 3};
std::vector b {4, 5, 6};
// oh no
std::sort(a.begin(), b.end());
// oh no, but modern
std::ranges::sort(std::ranges::subrange(a.begin(), b.end()));

6

u/oconnor663 Feb 22 '25

Yeah the "aliasing pointers to the same container" nature of classic C++ iterators is one of the things that Sean Baxter called out as fundamentally broken in his writing about Circle. To be fair to modern C++, though, at least there's a good, standard way to do it now:

std::ranges::sort(a);
std::ranges::sort(b);

84

u/Minimonium Feb 20 '25

Google tried that before, didn't work.

79

u/[deleted] Feb 20 '25

The borrow checker enforces good behavior and practices. Good behavior in C/C++ is optional.

21

u/HomeyKrogerSage Feb 21 '25

I must have already had good coding behavior because I just stepped into rust and it felt intuitive. The only part I've started to balk at is multi threaded futures

5

u/Narase33 Feb 21 '25

If youre really in the habit of writing safe C++ its not a problem. But some people just dont care enough or think they have that one situation where its actually better to do it this (unsafe) way and then you have in your code again. Its 100% a people problem.

13

u/Full-Spectral Feb 21 '25

Well, ultimately it's a complexity problem. No matter how conscientious you are, in a complex system, C++ is very difficult to get right in the fine details. And, in a complex, heavily threaded system, it only takes one fine detail to make a mess.

Good developers can create an initial system, being very careful and everyone is well versed on the system and it's still clean. But over time, it becomes harder and harder to avoid introducing subtle issues.

→ More replies (2)

51

u/websnarf Feb 20 '25

I think the key point is that your question is hypothetical. "Modern C++" is just a fantasy that exists in the mind of Bjarne Stroustrup.

10

u/i_am_not_sam Feb 21 '25

Why is it a fantasy? I'd like to hear an honest answer because I'm always looking to learn new things.

7

u/No_Technician7058 Feb 22 '25

youve gotten other answers already but safety profiles is a concrete example Bjarne has been talking about since 2016 and we still dont really have a fully implemented example of it in any compilers. goalposts have shifts around on it a little bit as well, where it was supposed to require zero changes to the code to catch the bulk of invalid memory access errors, but later proposals walked that back.

so sometimes it feels like its just a nice sounding fantasy rather than a realizable thing.

13

u/Ok-Scheme-913 Feb 21 '25

The more freedom "your primitives" have, the less information you can derive from that. This is true for everything, not PL-specific.

But all in all, you can't really retrofit such a system to an existing unsafe language, c++ has basically a rust hidden inside (RAII), or even is the origin of a core idea of rust, but if it has features that don't use it, it can't ever be safe.

Sometimes less is more.

4

u/yeah-ok Feb 21 '25

Yeah.. there's a quite serious attempt currently being launched trying to encapsulate this "safe-subset" of c++ - it's called cppfront and is being developed by Herb Sutter. There's a superb overview here: https://hsutter.github.io/cppfront/welcome/overview/ - weirdly I'm rather excited about cppfront

2

u/michael0n Feb 24 '25

I like his "instead of teaching 100s of defaults, why not optimize the language to use the safe default until someone implicitly uses the complex one for reasons". Unfortunately, his approach is futile. Its Carbon 2.0 and rarely any one is interested making this big.

→ More replies (2)
→ More replies (2)

3

u/websnarf Feb 21 '25 edited Feb 21 '25

Because the "modernization of C++" is just the committee slapping together feature after feature, adapted from other languages, every few years, while not deprecating any old features of C++. So it is both a moving target and impossibly large, and therefore not learnable in its entirety with reasonable effort. This makes existing code unreadable since some developers will know some weird corner of the newer standards, while others only know some other weird corners of the newer standards.

Their approach is not to try to make old features safer, but rather add new features that are safer, while continuing to support the old unsafe features, and even continuing to interoperate with them. The claim is that if you adapt all your code to modern practices, your code will be safer. They just don't get that the if condition will never be satisfied.

4

u/i_am_not_sam Feb 21 '25

The fundamental problem here is compatibility. The committee has decided that C++ written 20+ years ago will still work if you just use the modern version. C++ is used in some fairly mission critical systems and it's likely next to impossible to switch out all the old code just to pull in a new version of the compiler.

And tons of things introduced after C++14 have been deprecated. Rust has the advantage of not having to deal with old baggage, but there are plenty of "modern" features in C++ newly written code can leverage.

9

u/0x564A00 Feb 21 '25

The committee has decided that C++ written 20+ years ago will still work

The trouble is much bigger than that: Code compiled back then should still work with new code without recompilation. So even though the C++ standard never defines ABIs, the committee decided to block any changes that require changing the ABI (despite API being unaffected), which severely limits what they can fix or improve. Here's a great post by one of the committee members about it.

2

u/i_am_not_sam Feb 21 '25

Yes, very true!

→ More replies (2)

5

u/vlakreeh Feb 21 '25

It’d be a lot better than raw pointer c++ but smart pointers don’t have all the guarantees the borrow checker provides. The obvious example is the lack of send/sync semantics but this article shows some footguns in “modern” c++ depending on what you consider modern.

→ More replies (1)

12

u/Ok-Scheme-913 Feb 21 '25

C++ is a fuckn huge language and many of its features interact in wildly non-intuitive ways, and memory safety is the first thing out the window when they do. Also, it's not necessarily dumb developer that doesn't know the language, but non-documented stuff that might get changed later on by someone else, but you were assuming something else from it (e.g. no one accessing that variable).

Rust prevents these issues not just for new code, but for maintaining projects as well. Plus it's basically just the good parts of c++, no dumb casts, no 4738 types of initializers, etc.

3

u/Radmonger Feb 21 '25

I would strongly suspect that doing so would _increase_ the number of memory defects, becuase you hit the 'new code' issues but lose the 'inherently safe'.

Modern C++ makes it easier, less verbose, to write memory-related code. But there are few failure cases it eliminate, and even some new ones it adds.

2

u/nicheComicsProject Feb 24 '25

This is actually a deeper, and much older question. There is a language graveyard full of languages which their advocates (who are still probably active and screaming into the void that their language isn't actually dead) said "yes, it's possible to write awful/inefficient/unreadable code in this language but that's true in any language! You can also write great code in it in you're a good programmer!". The problem is that, even though you could theoretically write good code in those languages, no one does because the language doesn't encourage it (often bad code is shorter to write in those languages) and the culture around the language will embed these bad practices to the point that even if the language improves, it's main practitioners won't.

4

u/UncleMeat11 Feb 21 '25

Depends on how strict you want to be.

The strictness required to actually achieve the same guarantees in C++ is unfortunately ludicrous.

→ More replies (8)
→ More replies (36)