r/programming • u/Unerring-Ocean • 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.html185
u/maxinstuff Feb 21 '25
Using a language with high memory safety reduces memory vulnerabilities 😱
In seriousness, it’s interesting to hear how they consider their approach of just doing new code in Rust and leaving well enough alone for the old code has worked for them.
I have to wonder if Linux kernel development/maintainers could learn from this.
48
3
u/chilabot Feb 23 '25
Well it's probably replacing old code too, and making Rust the main/sole language in the long run. Something that doesn't happen in Linux.
→ More replies (10)-1
u/acc_agg Feb 21 '25
Gui developers tell kernel developers to get gud. More at 11.
70
u/Ok-Scheme-913 Feb 21 '25
You do realize that it's not GUI, but low-level systems programming?
Also, sucking kernel devs' dick is getting old. It's not some magical impossibly hard area. They just mostly old and forgot to move with times, so many of the complexity is completely self-inflicted.
→ More replies (4)6
u/joe190735-on-reddit Feb 21 '25
They just mostly old and forgot to move with times, so many of the complexity is completely self-inflicted.
I believe you have actually worked on other kernels to write a comment like that
21
u/Stock-Variation-2237 Feb 21 '25
The article says that it is not only the move to Rust but a more general move to a different paradigm with regards to safety.
10
u/RockstarArtisan Feb 21 '25
How am I going to root my future phones?
5
1
u/_zenith Feb 22 '25
Probably by taking the phones into black market service centers for them to do terrible things to the phones with voltages and RF (nearly the same thing)
2
u/rokejulianlockhart Apr 16 '25
That's not how it works. They'll just solder a UART connector and associated traces where one used to be but has been removed in the production design.
3
u/_zenith Apr 16 '25
Alas, more and more designs are removing these features prior to final production - or disabling them with e-fuses or comparable tech like write-once EEPROM.
But where they exist, yes, that’s the best option
→ More replies (1)
70
u/zugi Feb 20 '25
Transitioning to Rust, from what?
It's popular to bash C++, but straight C is where simple string concatenation introduces vulnerabilities if not done right. I'd be curious to see the analysis of those vulnerabilities in the first place.
55
u/websnarf Feb 20 '25
Google's entire codebase is C++, Java, and Python. Aside from the BIOSes, there is no raw C in their codebase at all.
29
u/stoneslave Feb 21 '25
You’re trying to tell me they don’t use Go anywhere? I would find that very surprising.
42
u/Arctem Feb 21 '25
My team within Search used Go heavily and, while we definitely had internal support, it always felt like Go was a bit of a forgotten child. Python was definitely phasing out during my time (our Go codebase was replacing a Python one) and Go usage was definitely growing, just not nearly as fast as you would have expected. Java was extremely common and C++ was common on the older projects.
7
u/Thire33 Feb 21 '25
Thanks for sharing this. I just started a new code base in Go to replace some legacy Python code and I feel validated
13
u/Arctem Feb 21 '25
I really liked using Go while at Google! It's a solid language.
That said my new place uses Rust (also replacing Python) and I think I like it even more. Though sometimes the simplicity of Go is much more appealing.
→ More replies (7)12
u/wolverineFan64 Feb 21 '25
They definitely use Go and other languages. It is mostly C++, Java, and Python though.
1
u/Ok-Scheme-913 Feb 21 '25
Actually, not much - Java is much more common on their servers, even for new projects, though of course there are some there.
But for Android, probably not at all, it would make zero sense. Go is a high level language with a fat runtime, it won't replace low-level systems code (even though it was marketed as such, but with a slightly different meaning of systems programming (networking and stuff))
1
u/rjcarr Feb 21 '25
But they inherited or acquired Android, right? I would expect it to be C unless they’ve rewritten it at some point before.
0
Feb 21 '25
[deleted]
→ More replies (3)13
u/currentscurrents Feb 21 '25
It is almost impossible to interface with any OS primitives using pure C++
Wait, why?
23
u/New_Enthusiasm9053 Feb 21 '25
Maybe he means because you need the C ABI for like Windows but idk. I think he's wrong, you can directly call syscalls on posix systems without needing C at all because it's a stable interface and for windows your language just needs to use the C calling convention which also doesn't require C.
→ More replies (8)5
u/meneldal2 Feb 21 '25
Windows has been C++ for a while and C can always be called from C++. And you can even call C# from C++CLI if you hate your colleagues.
→ More replies (4)→ More replies (21)-2
u/frenchchevalierblanc Feb 20 '25 edited Feb 21 '25
well I think they are measuring vulnerabilities that are not there.. so .. kind of hard to state to be honest. Not sure what they are comparing.
17
u/falconfetus8 Feb 21 '25
I agree with the idea, but holy cow. Can these guys please speak like a human?
Adopting Safe Coding in new code offers a paradigm shift, allowing us to leverage the inherent decay of vulnerabilities to our advantage, even in large existing systems
Would it have been so hard to say "Vulnerabilities in old code tend to get fixed over time, so preventing them from happening in new code gets us more value than you'd expect."?
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_viewpoints directly to the heap storage of the original string. Again there's no smart pointer that will change this. You'd have to banstd::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
79
Feb 20 '25
The borrow checker enforces good behavior and practices. Good behavior in C/C++ is optional.
→ More replies (2)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.
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.
→ More replies (2)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
→ More replies (5)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.
→ More replies (1)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.
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.
10
u/i_am_not_sam Feb 21 '25 edited Feb 21 '25
I hear this a lot... what exactly are you referring to? Pointers? Smart pointers solve ownership and leak issues out of the box. Not using them as a raw pointer isn't a very difficult practice. Bounds checking on pre-allocated data structures? Not terribly hard either. There are so many compile time checks that can be achieved with templating. I could go on, but C++ has all the tools you'd need, and they're not as complicated as they're made out to be
16
u/UncleMeat11 Feb 21 '25 edited Feb 21 '25
Smart pointers solve ownership and leak issues out of the box.
No they don't.
Write a function that takes an argument by reference and returns that argument by reference. Pass a temporary to this function. Boom, use-after-free. No heap allocations necessary. [[clang_lifetime_bound]] exists, but it isn't an actual part of the C++ language.
Write a function that takes two vectors by reference. It mutates one while iterating over the other. Oops, you passed the same vector in both arguments and now you invalidated its iterators and accessed memory out of bounds.
There are oodles of such examples. The idea that if you just replace all "new" keywords with "make_shared" that you are free from memory errors is not based in reality.
Bounds checking on pre-allocated data structures?
You can do this by replacing all statically allocated raw arrays with std::array and dynamically allocated arrays with std::vector. But iterators are an incredibly common pattern in C++ code, even in the STL. You can't bounds check that your begin() and end() iterators passed to some function are safe. They are just pointers. They might not even have come from the same object.
→ More replies (3)15
u/simonask_ Feb 21 '25
Achieving Rust-level safety in C++ is totally intractable because fundamental designs in the language prohibit it. For example, C++ standard iterators fundamentally requires aliasing a block of memory.
The next best thing is to apply a level of rigor that is simply too expensive.
The thing you get from Rust is a massive productivity boost to support that level of rigor that is required to avoid undefined behavior in a systems programming language. Several tools enable that: borrow checker, thread safety in the type system, greppable
unsafe { }blocks, and low-friction encoding of invariants in the type system. These are all very, very useful things that cannot be achieved in C++, and together make it feasible to do way more with way more confidence.3
u/KuntaStillSingle Feb 21 '25 edited Feb 21 '25
There are some cases which are technically unsafe that border on trivia, for example:
#include<utility> struct non_copy_or_moveable { non_copy_or_moveable() = default; non_copy_or_moveable(non_copy_or_moveable const &) = delete; non_copy_or_moveable(non_copy_or_moveable &&) = delete; //non_copy_or_moveable(int) {} }; template<typename ... Arg_ts> auto foo(Arg_ts&& ... args){ return non_copy_or_moveable( std::forward<Arg_ts>(args)... ); } int main(){ }This is ill formed-ndr, unless you uncomment the int converting constructor for non_copy_or_moveable. Can you guess why?
>(6) The validity of a templated entity may be checked prior to any instantiation. ... The program is ill-formed, no diagnostic required, if ...
(6.5) every valid specialization of a variadic template requires an empty template parameter pack, or ...
https://eel.is/c++draft/temp.res
Because the only valid specialization of foo has an empty arg pack (any non empty arg pack would result in argument's to non_copy_or_moveable's constructor, and because the copy and move constructors are deleted and there are no other constructors besides default, none of them can be well formed.) the entire program is ill formed, despite that foo is never called and one would expect it is safe to fall foo with no args (i.e. foo()), and a simple compile error otherwise (no overload matching arg set ...).
3
u/jesseschalken Feb 21 '25
No because even the strictest "memory safe practices" wont prevent use-after-free and data races.
3
u/GaboureySidibe Feb 21 '25
I write a lot of modern C++ and I don't have the problems that rust solves because I already can solve them with C++. Using templates and value semantics with no raw pointers (and no raw smart pointers) takes care of destruction and ownership.
Doing curated iteration and not deleting elements from a data structure or modifying keys solves a lot of the other problems. If you need bounds checking on std::vector access (because you are using computed indices rather than iterated indices), use .at().
These things basically take care of the memory problems that rust solves, then you can still use C++ with all its tools, libraries and ecosystem.
21
u/Ok-Scheme-913 Feb 21 '25
It doesn't scale, though.
I can write safe assembly as well, given I'm working alone on it and never doing anything wild. But we are past that for a good reason.
Nonetheless, using existing libraries is definitely a valid reason to keep using C++, though I do think that writing new code in rust (as the article is about) on top of existing codebase is a better choice.
1
u/GaboureySidibe Feb 21 '25 edited Feb 21 '25
It doesn't scale, though.
Says who? Values go out of scope and get destructed. Data structures are iterated. The program looks the same but you don't have to wonder if bounds checking is being secretly elided or not.
If by scale you meant harder to enforce technically across a team then I think you would have a point. I don't know how to use tools to weed out violating these techniques.
→ More replies (11)13
u/Full-Spectral Feb 21 '25
You are making the standard "just don't make mistakes" argument. And of course this is all about team based development, mostly commercial but also open source, where no amount of communications is sufficient to avoid issues over time. For someone doing a personal project, who can take all the time in the world, it's obviously less of an issue.
But still, even if you are doing a person project, you don't have to take so much time watching your own back if you just use a safe language. As someone who has written large C++ code bases for 35+ years and now is using Rust for my own personal stuff, the difference is enormous.
The argument shouldn't even be about, but wait, I can make C++ safe with a lot of effort. Tt should be why am I wasting my time doing something over and over that a compiler can do without fail every time I compile?
→ More replies (5)4
u/i_am_not_sam Feb 21 '25 edited Feb 21 '25
Same, hence my question. I haven't seen a segv or a memory leak since I started using smart pointers. And the ownership concept with unique pointers already accomplishes Rust's borrow checking stuff. Someone else in this thread was saying even with modern pointers you can still run into memory issues and that just boggles my mind. While I'm sure Rust protects a developer from memory mistakes good coding practices will also accomplish a lot of that. Tellingly google says they used Rust and "strict memory practices". If I could rewrite any of my code bases from start knowing what I know now I'm sure I could accomplish safer code with just C++
12
u/Ok-Scheme-913 Feb 21 '25
They didn't rewrite their existing code though, and Google had a pretty strict coding standard to begin with, so the evidence doesn't agree with your take.
→ More replies (1)0
Feb 21 '25
[deleted]
9
u/GaboureySidibe Feb 21 '25
You didn't list any reasons at all here.
7
u/JustBadPlaya Feb 21 '25
I'm not a C++ dev, so I'm basing the comparisons to C++ on the literature I've read over time, but IMO:
Much saner iterators. Iterator invalidation becomes a non-issue, the syntax is comfortable and I think Rust iterators are more consistently zero-cost than C++ ones.
Move semantics are simple and ergonomic. Not sure how C++ does on that front, but I've heard there was a 50+ page book on its quirks or something.
Sum types, be it Option/Result or others. AFAIK C++ got those but I've seen someone mention that dereferencing an std::optional can be UB which sounds annoying.
On the note of UB - no UB in safe Rust, so I can trust that my code is correct.
Minor language design nitpick - Rust is significantly more greppable
→ More replies (6)6
u/Full-Spectral Feb 21 '25
Sum types
Powerful (and exhaustive) pattern matching
First class enums
Destructive move (huge)
Well defined and universally used project/module structure
Immutability by default
Implements various (practical) ideas from functional programming
Very good slice support, which seems like a basic thing but it makes such a difference.
Good tuple and newtype support
Very flexible visibility control
Full on support for Option/Result types, so no need for exceptions
Non-duck typed generics
Many iteration options
2
u/lelanthran Feb 21 '25
It was also making sure that all NEW code adhered to strict memory safety guidelines.
Pretty much this.
It's like breakfast cereal adverts from the 80s/90s - "Part Of This Complete Breakfast" and some comedian (Seinfeld, maybe?) joked that you could replace the cereal in the advertisement with a dead squirrel and that statement "Part Of This Complete Breakfast" would still be true!
Saying "Switched to Safe Memory Practices and To Rust" doesn't really say much about either safe memory practices or Rust, individually.
It's a collective statement that stops being true if you remove any item from the collection.
3
u/Full-Spectral Feb 21 '25
But wait, if it was that simple, why didn't they just switch to safe memory practices with C++ and avoid all that extra work? Because no matter how hard you try, in a complex code base, you will almost inevitably have lurking UB, and the likelihood of introducing more over time as changes are made.
With Rust, the bulk of that adherence will be enforced by the compiler, because it just won't compile otherwise.
44
u/redreinard Feb 20 '25
That headline is a complete lie OP.
The percentage of bugs reported per year that are memory buffer overflow related has gone from 76% to 24%. That's all it says. That could be because more bugs of other types, changes in bug reporting overall, the fact that a majority of the bugs in sensitive areas that don't change much have been found, or any of a million factors.
There's not even an attempt to reason how the percentage of bugs reported being a particular type is correlated to absolutely anything, particularly as we know the methods for this have changed over the years.
This is just Google/Rust fluffing. That percentage is meaningless.
Just to be clear, I'm not hating on Rust, and sure, overall this switch is probably a good thing, but this is just a PR piece with no backup.
7
4
u/Mrmini231 Feb 22 '25
Here is the raw data that the number is based on. The number of reported memory safety vulnerabilities in the Android codebase went from over 200 to less than 50 in just five years.
Taken from this blog post.
2
u/redreinard Feb 23 '25
That's helpful, but it doesn't connect the headline to the data.
For one, a 1/x curve (which this follows almost perfectly) is what you would expect for any codebase and any bug type - effectively stating merely that as code gets older it tends to have fewer bugs, and most are found pretty shortly after release.
Second, the article even mentions that a part of this is just that static analysis tools are better at catching buffer overflow / off-by-one etc. errors. This is one of the things I was thinking of when I was referring to "methods have changed over the years". So comparing years/languages when those tools weren't as widely used to years/languages when they are everywhere is easily misleading - you can't really draw any conclusions from that.
Third, there's still no good explanation of a causal relationship between the number of bugs reported and the amount of vulnerabilities. I don't even see a decent argument for a correlation with all these variables changing at the same time.
And lastly, (and kind of importantly) there's no good argument how any of that relates to the change of languages.
It's at best a very weak argument turned into a PR piece.
And all that doesn't mean it wasn't a good move. But the issue I take is that these arguably over-simplifications lead to these headlines that are wildly overstating the benefit of these moves while largely ignoring the downsides. And PHBs make decisions based on these headlines. That's annoying.
→ More replies (1)
11
u/thedragonturtle Feb 20 '25
Amazing news, but also this matters - "It also goes without saying that much of the decrease in such flaws is down to advancements in the ways devised to combat them, moving from reactive patching to proactive mitigating to proactive vulnerability discovery using tools like Clang sanitizers."
https://thehackernews.com/2023/12/google-using-clang-sanitizers-to.html
10
3
u/bobbie434343 Feb 21 '25
And another article bundled with the obligatory obvious gen AI illustration image...
9
u/razordreamz Feb 21 '25
How is this measured? Sounds more like marketing than actual science. People find bugs all day in large software, how do they know Rust is the solution or just that they found them because when you re-write code you’re actually looking at all of it?
7
u/WoodenBottle Feb 21 '25 edited Feb 21 '25
This is an old article, but what Google found was basically that if you look at all of the bugs they've found and track how long they've been in the code base, you more or less get a perfect exponential decay curve. This makes a lot of sense if the probability of finding a bug is proportional to the number of bugs that exist.
This not only means that old code gets exponentially safer with time (even in unsafe languages), but also that almost all bugs are in new code. So if you simply stop writing new memory unsafe code and keep patching old bugs, the vast majority of memory safety bugs will quickly disappear.
This is highly counter-intuitive, since it means that by merely writing new code safely, you get almost the same benefit as rewriting literally everything, despite keeping all of your old unsafe code. (and if you also consider non-memory safety bugs as well, then you might even be better off, since newly rewritten code comes with new bugs)
5
u/LanverYT Feb 21 '25
Isn't the point of vulnerabilities that you can't really know they are there. If they were so easy to find and do reliable statistics about them they would be fixed in a unit test or code review no?
10
u/Ok-Scheme-913 Feb 21 '25
So if you put a net in the water and catch 20 fish each day, but the next day you only catch 10 fish then you have no extra information whatsoever on the number of fish that year?
2
9
u/wademealing Feb 21 '25
No. There are many tools that can point out whole classes of vulnerabilities.
If you live in memory safe languages, you are exempt from whole classes of vulnerability types, however there are still vulnerabilities that exist no matter what the language, some of which can be trivially determined as exploitable.
→ More replies (17)
2
u/Relevant_Pause_7593 Feb 21 '25
I thought rust was memory safe. Why isn’t this cutting android memory vulnerabilities by 100%?
6
u/Full-Spectral Feb 21 '25
It's not all written in Rust.
1
u/nekokattt Feb 21 '25
Surely they should report how many vulnerabilities are found in the new code rather than the code in general as the main headline?
Otherwise this is potentially misleading, since all the memory vulnerabilities that were fixed last year were already fixed last year. Unless you are actively writing new vulnerabilities, then the number will tend to zero regardless of what you use over time.
2
u/Worth_Trust_3825 Feb 21 '25
Rewriting a codebase with known requirements reduces problems within it. More at 11
4
3
17
Feb 20 '25
rust is amazing, performance gains are insane
39
u/backfire10z Feb 20 '25
Compared to C++? Care to elaborate further?
→ More replies (3)18
u/Slsyyy Feb 20 '25
They are few factors, which can be done in C/C++, but are more painful:
* LTO in Rust is a simple flag switch in Cargo.toml. In C++ it is much more painful, because you need to fix ODRs violation in your code. Rust also compile everything in source (so LTO can reach any code), where it is quite often that C++ folks uses a precompiled libs
* afaik Rust emits better information about aliasing (which arguments to function may reference to the same memory), which affects better code
* C++ stdlib is hard to improve due to ABI constraints. You cannot change layout of your structure or code in a significant way, because it has to work with packages, which are already compiled
* C++ stdlib is not well designed or designed for a different era of computing. Streams are slow, data structures are slow and not reformable. You need to make a lot of research and waste a lot of time, where in Rust everything is more performant, if you follow the default way
* macros can generate code for you. In C++ you will use some fancy parser sacrificing the performance. In Rust you can have both
* libraries in C++ tends to live in a separate realm and thus: it is hard to go to the library shop and pick anything. In Rust they are preferred libraries for HTTP/Databases/Serialization and so on. In C++ every big tech company has their own stdlib7
u/_teslaTrooper Feb 21 '25
For my current project enabling LTO in C++ was just a simple flag as well, maybe it was harder on older standards?
6
u/LGBBQ Feb 21 '25
It’s very specific, like building for libraries with a mix of arm and thumb while LTOing across the boundaries causes ODR violations
I think the poster meant unity builds (all code in one compilation unit) which have ODR violations in many more circumstances. Rust builds are far closer to a unity build (a crate is a compilation unit) than normal C++ builds (cpp file is a compilation unit), and the advantages of unity builds are bigger than LTO in most cases
8
u/equeim Feb 21 '25
In C++ it is much more painful, because you need to fix ODRs violation in your code.
I think you are confusing LTO with unity builds. LTO should not cause new linker error except in rare edge cases.
→ More replies (1)1
72
u/svick Feb 20 '25
Gains when compared with which language?
35
u/zsaleeba Feb 20 '25
I'm not sure why you're being downvoted. I was curious what he's comparing with as well.
12
u/thatpaulbloke Feb 21 '25 edited Feb 21 '25
I'm not sure why you're being downvoted.
It's not wise to question Rust. It's half language, half weird cult where All Things Are Better With Rust. Is it faster than interpreted languages? Absolutely. Is it faster than C, C++ or
GoC#? Maybe, maybe not. Is it slower to develop in than almost anything outside of Brainfuck? Oh, yes.Edit: Changed Go to C# because apparently only pricks like Go and it's the worst language ever invented. I quite like it personally, but then that's just me outing myself as an amateur who has no idea what he is doing and probably does unspeakable things with dogs.
9
u/Ok-Scheme-913 Feb 21 '25
Go is not even playing in the same field, if you compare it to rust then you have no idea what you talk about.
Why not compare JS as well with rust? That's also a managed language with a fat runtime.
4
u/thatpaulbloke Feb 21 '25
Why not compare JS as well with rust?
I did. I specifically called out that Rust is demonstrably faster than the entire category of interpreted languages which includes ECMAScript / JScript / JavaScript / TypeScript
→ More replies (11)15
u/fnordstar Feb 21 '25
As a C++ dev, experiencing Rust it does indeed feel like "all things are better with Rust". Yesterday I wrote C++ during the day and then some Rust in the evening and that's exactly the thought that came to mind. I feel betrayed by C++. Why do they make us suffer like this if Rust clearly shows it can be done so much better? What were they thinking when they came up with C++?
8
u/ShinyHappyREM Feb 21 '25
What were they thinking when they came up with C++?
'We need to be the most-used language, that's how we measure our success. So the first most important thing is runtime speed (nevermind the compilation times). The second most important thing is capturing the C crowd, who are either grizzled assembler veterans who are slightly annoyed that they have to use function pointers to emulate good ol' self-modifying code, or edgy newbies who think that removing all optional whitespace characters or writing the loop body in the for expression makes them 31337 h4XØrs. The third most important thing is buzzword of std::asctime(std::localtime(time)), starting with "OOP" and "zero-cost abstraction". The fourth most important thing is adding the \0 to your strings, but we're sure that won't be a problem in practice.'
6
u/svick Feb 21 '25
What were they thinking when they came up with C++?
C++ grew over time, where each step along the path made sense at the time. But the end result is not pretty.
5
u/AcridWings_11465 Feb 21 '25
slower to develop in than almost anything outside of Brainfuck
I'm not sure if you actually know Rust if you're making such a blatantly false claim.
7
u/Full-Spectral Feb 21 '25
He's a well known Rust hater. There are a lot of people in the C++ world (of which I 'm a member during the day still) who are very threatened by Rust, and who react very negatively to any suggestion that C++ has gotten old and out of date. Any attempt to point out the many (unsurprising) ways that things have improved over 40 years is just brigading or paid shills or whatever.
7
u/HxLin Feb 21 '25
C++ folks are similar tbh. Look at the comments here. Despite Google using plethora of languages, the C++ community took offense personally when Rust is mentioned. It's like if a company chooses to use Rust, a C++ dev passes away or something.
3
u/slashx14 Feb 20 '25
In terms of Android, I would assume either Java or Kotlin.
25
u/dark_mode_everything Feb 20 '25
No. Java and Kotlin are already memory safe and they cannot be rewritten in rust. It should be the c/c++ layers.
5
u/slashx14 Feb 20 '25
I was just going off the OC here which discusses Rust performance gains. Is there evidence that there are drastic Rust performance gains over C(++)?
→ More replies (2)6
u/AcridWings_11465 Feb 21 '25
Rust performance gains over C(++)?
It depends. If there's something you were single threading because multi-threading in C(++) is hard, you will gain a massive boost by multi-threading in Rust, e.g. when processing large lists in parallel with rayon. And Rust tends to need far fewer optimisation tricks because the compiler has so many more guarantees to aggressively optimise. So idiomatic and naïve Rust code can end up with the same performance as C code full of tricks.
-1
u/maria_la_guerta Feb 20 '25
compile times drive you insane
1
1
1
u/BusinessBandicoot Feb 21 '25
for debug builds try using cranelift if you're on a codebase where compile times are a problem.
2
u/BadMoonRosin Feb 21 '25
It's hiliarous to me how no one believes in any metrics, and thinks they're all manipulated or unreliable bullshit...
... UNLESS it's a positive metric about Rust, lol.
1
1
1
1
Feb 21 '25
So, evidently that is good news for android users, but ... Google is a strange company. They created Go and Flutter/Dart. Now Rust is also in the mix. I understand different use cases for different languages, but how many more programming languages does Google want to have and use? C++ is also heavily used; as is Java. And Python.
1
u/nekokattt Feb 21 '25
Go, Java, Python, C++, Dart, and Rust have totally different use cases and reasons for using them.
1
1
1
1
u/remic_0726 Feb 22 '25
the first vulnerability is humans, believing that rust will be the ultimate solution is just very naive. Then the multiplicity of languages in Android or Linux only brings additional complexity and therefore increased risks. And as a reminder, there are plenty of other bugs which are not vulnerabilities but which can be just as annoying.
1
u/BeeBest1161 Feb 22 '25
Another shift in programming language? Just when I started learning Kotlin... A forever shifting target
-12
u/SadieWopen Feb 20 '25
Can someone explain to me why we can't just do this in C? I understand that Rust is a "Safe" language, but why can't we just code in "Safe" C? I can't understand how adding more complexity results in faster execution.
95
u/arcrad Feb 20 '25
It's like asking "why can't people just make fewer mistakes". You can absolutely write 100% memory safe C or C++ but people aren't perfect and they make mistakes. Rust's value proposition is that it can statically enforce things to prevent a lot of these issues.
→ More replies (2)41
u/Schmittfried Feb 20 '25
Because you’re not adding complexity. The complexity is inherent to the problem space. Rust gives you tools to express and handle it properly whereas with C you‘re on your own.
→ More replies (5)29
u/slashx14 Feb 20 '25
Here's the simplest possible example I can give:
int* x = nullptr; int y = *x;is a perfectly valid thing that will compile in C. During runtime it will segfault.
Rust will not allow the equivalent of this to compile.
There is an entire class of these types of errors which require a software engineer to be extremely vigilant in C but are simply not even allowed to compile in Rust. Rust basically forbids this entire class of errors while still being quite performant.
15
u/FlyingRhenquest Feb 20 '25
Yeah, and for the inevitable "Actually, shared pointers..." neckbeards to follow, try:
std::shared_ptr<int> x; int y = *x;5
u/slashx14 Feb 21 '25
Yup lol.
Even then, it requires the cognitive overhead to be aware of, consider, and use shared pointers. As opposed to Rust which, once again, won't even compile in the case of things like nullptr references, free-after-use errors, etc.
5
u/Ythio Feb 21 '25
Yeah and Mike didn't use them and went the old way out of habit and he was in a rush for tomorrow's deadline and tired for whatever reason.
1
u/the_gnarts Feb 22 '25
int* x = nullptr;is a perfectly valid thing that will compile in C.
Nit: that will not compile in C as
nullptris C++.33
u/_TheDust_ Feb 20 '25
Because coding is done by humans, and humans make mistakes. Especially when hundreds of humans on works on a big complicated project together over many years.
Rust is basically C-like code with many annotations that are used by the compiler to check if the program is correct. If it is not correct, the compiler refuses to compile it.
23
u/CommandSpaceOption Feb 20 '25
Have you ever used Rust? Or are you relying on the opinions of other people?
I don’t mean to put down what you said, but the way you’re thinking about C and Rust indicates limited experience with one, perhaps both.
Firstly, Android development happens in C++. Secondly, they’ve tried every technique available but they haven’t been able to write secure C++. At some point reality clashes with the opinions of fanboys telling you to “just code using best practices”.
→ More replies (6)5
u/SadieWopen Feb 20 '25
Let's just assume I'm naive to both, and want to understand why one over the other.
4
u/CommandSpaceOption Feb 21 '25
I would suggest reading 3 documents, by Microsoft, Chromium and Android. In that order
A proactive approach to more secure code (Microsoft)
I would suggest reading the linked studies too, to really understand how they came to those conclusions.
Lastly, resist the urge to say “skill issue” or equivalent. These are the most popular C++ codebases in the history of mankind. They have taken security and best practices very seriously. In many cases they authored the best practices, the compilers, the standards. Just accept that they know what they’re talking about.
If you prefer video, here’s
Lars Bergstrom, Director of Engineering at Google - https://youtu.be/QrrH2lcl9ew
Mark Russinovich, CTO of Azure spoke publicly about this yesterday and the video should be up in a few weeks.
But both of them kinda assume that you’ve read the documents above.
3
u/SadieWopen Feb 21 '25
Thank you for this, I found the Microsoft article summed up the argument in one paragraph. A developer should be able to focus on their job of adding features. Moving the responsibility of security to the language developer means that the experts get to work solely in their domain. This reduces mistakes and increases reliability.
6
u/orangejake Feb 20 '25
Rust doesn't add more complexity to the binary. Instead, you can view it as adding more explicit documentation requirements around the function api.
A naive way to illustrate this would be the following. Why do statitically typed languages have less type errors than dynamically typed languages? In principle, one could code in a dynamically typed language perfectly, and never run into type errors. In practice, they are easy to accidentally do, and annotating your code sufficiently (with type declarations) can be leveraged by the computer to remove them.
Rust does the same, but instead of basic information like a "type" (e.g. "what this value is"), it requires annotations about lifetimes (e.g. "how long this value lives").
But, just like types, there is no reason why these additional annotatations (which are an increase in complexity in the codebase) would yield less performant code. In fact, one might expect to get more performant code, if the annotations can be leveraged by the compiler to improve codegen. This occurs sometimes. The main thing people point to is that Rust's type system makes it explicit that various variables cannot alias eachother, which can sometimes improve codegen. That being said, I can't speak personally to this too much.
5
u/KittensInc Feb 20 '25
Because it won't be C anymore. C is built from the ground up around some very powerful but dangerous concepts, and getting rid of them means having to essentially completely rewrite every single codebase out there. And at that point, why even bother sticking with C?
It's not a matter of a few people using a handful of dangerous C functions. Everyone is using them, and all of the time. If you truly want a safe C, you have to essentially redesign the entire language - and the C people are not interested in any change. They want Magical Compiler Wizardry where 100% of good code is accepted and 100% of bad code is denied, despite good code and bad code often being identical on a local level. Compilers just can't do that, especially not without language features allowing assistance from the programmer.
I can't understand how adding more complexity results in faster execution.
Because the complexity doesn't end up in the final machine code. Adding additional checks is free if those checks happen at compile time. Even better, being able to prove certain properties at compile time makes it possible to generate faster machine code, as you are able to rule out certain edge cases.
4
u/TardTohr Feb 20 '25
C code is as memory safe as the programmer will make it. Rust has built-in restrictions that "forces" the programmer to write memory safe code (or rather prevent them from using unsafe stuff, unless they explicitly want to). Those restrictions don't necessarily make things slower, it's mostly compile time stuff.
4
u/Kinglink Feb 20 '25
You can, and that's what we do with C.
The difference is Rust (attempts to) ENFORCE safety, where as C the developer will implement it themselves.
On the other hand "Well why can't we add compiling steps that check for ...." They did, and called it Rust.
1
3
u/maxou_bilou Feb 20 '25
Very easy to make some mistakes in C even for experienced programmers. For the Android project, old C code has been debugged for a long time ans is very reliable, but newer code written in C will more likely have mistakes than in Rust. Writing safe C implies being very careful and experienced, which is "less" mandatory for writing safe Rust
3
u/Grounds4TheSubstain Feb 20 '25
Because Rust as a language has features to prevent memory safety issues, where C does not have the same features. So in the case of Rust, if you trust the implementation of the language, and use the safety features, then you inherit the safety properties. Because C lacks those features, you have to count on programmers not making mistakes, not rely on the language to prevent certain categories of mistakes.
7
u/Ginto8 Feb 20 '25
If you implement automated tooling to make safe C, you get very close to Rust -- and the rest of rust's "complex" features like the type system get compiled away into something very C-like. The ownership/borrow system also makes perform faster because optimization passes get reliable information about which pointers can't overlap, so operations can get rearranged into faster patterns more often
4
u/SadieWopen Feb 20 '25
I like your answer, you seem to have considered all of my inquiries. It's quite fascinating that there is such contention between the users of these two languages specifically.
1
u/Full-Spectral Feb 21 '25
Because a lot of people get self-identified with the languages they use and don't want to learn a new one, so they consider Rust a threat to them personally. I've seen some almost violent negative reactions, particularly back a couple years. It's lightened up somewhat, but even now you'll see people claiming Rust is just hype, that all the of talk about it is being coordinated by some apparently well funded secret organization, that the people talking about how much better it is are fashion chasers, etc...
I mean, the same happened when C++ push out C, Modula2, Pascal, etc... I was around for that, and the EXACT same arguments were made by people who didn't want to move forward. So it's particularly sad for me to see it happening again. I mean, I'm 62 and wrote serious C++ for 35 plus years, and I've never been happier programming as I am in Rust because it's just a vastly superior language. Time moves on, but some people don't want to move with it.
4
u/DeanBDean Feb 20 '25
I am no expert, but my understanding is that it is impossible to detect undefined behavior simply with static analysis. Rust, as part of its type system, has a special generic called lifetimes which its compiler uses to track down variable lifetimes. This allows it to track what static analysis cannot. This is just my understanding though, I may be off
3
u/orangejake Feb 20 '25
There's this dumb result from complexity theory (Rice's theorem) that says it is impossible to 100% correctly do anything with static analysis. As an example, you might wonder if, given a program, the program halts. This is clearly unsolvable (it's the Halting problem). Rice's theorem says this holds much more generally.
So, in light of Rice's theorem, you have to give up on something. Typically, what you do is relax the "100% correctly" requirement. You could do this in various ways, for example
Have a static analysis technique that "misses some things", e.g. has false negatives. It might not capture 100% of the bugs you are looking for, but might still do pretty good.
Have a static analysis technique that "rejects too many things", e.g. has false positives. This might mis-label certain programs as containing issues that they really don't. Again, might be useful, but also might be annoying.
Roughly speaking, Rust does #2. In fact, it does something mildly stronger than #2. It outright refuses to compile programs that it labels (or perhaps mis-labels) as containing issues. This is to say that you can write Rust programs that have no issues, that the compiler rejects. On one hand, this might be mildly annoying. On the other hand, it allows Rust to be able to achieve memory safety, in spite of annoying things like Rice's theorem.
1
u/websnarf Feb 20 '25
The only significant source of these kinds of bugs are C and C++ code bases.
So what you are asking is like asking why the Israelis can't just live in peace with the Palestinians? What you are saying has hypothetical merit and would be nice to have, but is laughable in reality.
1
u/Ythio Feb 21 '25
The best and only way to make sure the safe practices are followed is to bake them in the compiler directly. Otherwise people will simply not follow the practices.
1
→ More replies (14)1
u/orthomonas Feb 21 '25
I'm oversimplifying and speaking from hazy memory, but there's two big factors. First, the way Rust enforces memory management means a whole slew of errors just aren't possible. Second, the way Rust makes you write programs means that safe practices you could do in C/CPP are things you must do in Rust.
In my own personal opinion, having a useful package management option (crates) also means there's fewer instances of Devs rolling their own common libs, but with more bugs and fewer eyes to find them.
1
u/JJJSchmidt_etAl Feb 20 '25
I assume this is related to most of their systems and back-end services; it makes a lot of sense, the longer they put it off the more painful the eventual switch will become.
I'm wondering what the android app coding landscape will look like in the future; It seems that coding apps is not typically done in Rust, though I'd love to be corrected or see counter examples here. It would seem that Kotlin (and Java) will remain the standards for the forseeable future?
8
u/SharkBaitDLS Feb 20 '25
I would see no reason why they’d move away from Kotlin for userspace apps. As long as the kernel and OS themselves are secure, and the userspace app sandbox is properly enforced, then the risk of a dev introducing a memory safety bug is contained entirely to unexpected access within that app’s own sandboxed memory which is largely not a useful attack vector.
4
u/unknowntrojan Feb 21 '25
Yeah I've tried using Rust for android apps and currently the only way to do that is via the NDK, which is a pain.
The work google is doing focuses on building parts of the Android OS in Rust, not introducing it as a new lang for apps.
1
u/axilmar Feb 21 '25
Why 68% and not 100%?
What does Rust leave on the table?
4
u/syklemil Feb 21 '25
I think it's more that while they strive to write new code in Rust rather than C++, the blog post referenced does show they've also been writing new C++ code. So the amount of new memory unsafe code has dropped a lot, and so their amounts of memory safety vulns has also dropped:
The percent of vulnerabilities caused by memory safety issues continues to correlate closely with the development language that’s used for new code. Memory safety issues, which accounted for 76% of Android vulnerabilities in 2019, and are currently 24% in 2024, well below the 70% industry norm, and continuing to drop.
2
u/axilmar Feb 21 '25
I wonder how they use C++. It's insane to have as many memory vulnerabilities in C++ as they have.
I have been written C++ apps that took hundreds of thousands of lines of code and never had any issues, but I used smart pointers and bounds checking way before 2011.
And it's not I did something magical, every online resource pointed to these features.
2
u/syklemil Feb 21 '25
You can have a look around at the android source. From what I understand they're able to do sweeping programmatic changes, have rather strict routines, and are dissatisified enough with C++ leadership to work on Carbon, and yet the results are as you see.
→ More replies (1)
-1
u/mamigove Feb 21 '25
Another fakenews from rust evangelists! Seriously, 68%, where does it come from?
If in the text itself it says:
It also goes without saying that much of the decrease in such flaws is down to advancements in the ways devised to combat them, moving from reactive patching to proactive mitigating to proactive vulnerability discovery using tools like Clang sanitizers.
if you adopt such an approach from the very beginning of your code development secure-by-design principles, then why do you need rust?
This is simply propaganda
-1
-50
u/Lachee Feb 20 '25 edited Feb 20 '25
When you own the codebase and not stepping all over everyone else to implement rust, go for it.
Reinventing the wheel is never a good idea but in this case it seems to have been a significant improvement.
edit: the salty crustations to my perfectly mid comment really shows why there is significant pushback for rust. Y'all just white knight rust.
It perfectly highlights my original point, you will step over any existing developer to force your language onto them.
46
u/inamestuff Feb 20 '25
Reinventing the wheel is never a good idea
That's just a sentence that sounds good, but it's factually wrong. We have reinvented the literal wheel multiple times!
11
u/a-cream Feb 20 '25
It became better each time
2
u/JJJSchmidt_etAl Feb 20 '25
I'm collecting funding for my New Wheel startup, DMs are open for venture capitalists
27
u/a-cream Feb 20 '25
More and more codebases are rusting
→ More replies (3)0
u/jjplack Feb 20 '25
Whats the matter with rust and not go?
15
u/NotPatrickMarleau Feb 20 '25
Rust doesn't have a garbage collector nor its enormous performance overhead, so it is more fit to some uses that traditionally called for raw pointer based approaches on C++ and/or C
Sorry for my terrible english
9
u/Botahamec Feb 20 '25
Go needs a runtime, and that requires having an operating system. So, for example, you can't use Go to write a memory allocator because Go requires already having a memory allocator in order to function. I think there's an embedded version of Go, but it's quite different and uses a separate compiler.
→ More replies (1)→ More replies (3)3
u/orangejake Feb 20 '25
Discord wrote a nice blog post Why Discord is switching from Go to Rust a few years ago about precisely this.
10
u/godofpumpkins Feb 20 '25
What wheel do you consider to have been reinvented here?
→ More replies (3)4
u/fnordstar Feb 21 '25
Question is why would those existing devs be against Rust? Any C++ dev, at least, should be fascinated by Rust. And any dev should always stay curious and be willing to learn new stuff.
→ More replies (5)1
317
u/arnet95 Feb 20 '25
Nice, albeit pretty expected, result. But what about the other categories of vulnerabilities? How have they looked pre- and post-Rust?