Hacker News new | ask | show | jobs
by riwsky 1465 days ago
Even though it'd be a while before this really affects the Chrome codebase, it's a real testament to how well Rust nails the safe-but-low-level niche. Google does not lack resources to tool (or staff!) a C++ codebase correctly, nor does it lack resources to build languages[1] targeting these specific problems; that they'd consider Rust isn't just because "it's there".

[1] https://github.com/google/wuffs

2 comments

Story time.

I worked at Google years ago and there was a presentation once done on some optimizations done on Chrome performance. This is probably 10 years ago now.

So C++ has std::string of course. C libraries however use "const char ", which has lots of problems. The C++ designers allowed you to avoid friction here by allowing you to pass a std::string to a function expending a const char . Technically, this is an operator method.

It was discovered that the Omnibar in Chrome went through many layers of translations between std::string and const char *, back and forth, such that there were approximately 25,000 string copies per keypress in the Omnibar.

So my point is that even with a ton of resources writing good, efficient and performant C++ is still nontrivial. And that's really the point of Rust (well, one of them).

> The C++ designers allowed you to avoid friction here by allowing you to pass a std::string to a function expending a const char . Technically, this is an operator method.

It's the other way round. You can pass a const char* to a function expecting a std::string. Passing a std::string to a function expecting const char* will generate a compile error.

You need to call c_str() on the std::string if you want to pass it as a parameter to a function expecting a const char*.

I'm not sure if this is what OP was referring to, but in the ancient past before the STL was fully standardized, some implementations had an `operator const char*` in std::string to allow implicit conversions.
> the ancient past before the STL was fully standardized

Specifically the "ancient past" here is prior to C++ 11 when C++ decided now it wanted to actually define how its string type works because C++ 98 and C++ 03 strings are both even more dangerous than most things are in C++ and had to be put out of their misery.

> because C++ 98 and C++ 03 strings are both even more dangerous

... how so ? they were just CoW which is actually I think the better choice most of the time... now there are copies all over the place

The C++ API lets you take references into the string. These, understandably, are lightweight, no C++ programmer would expect a reference into the sixth character of a string s[5] to be expensive to make or carry about, but they're mutable and as a result of being lightweight they are not reference counted...

So I've got the string "IR Baboon big star of cartoon" and I take references into it, which are cheap and then you use your C++ 98 copy constructor to get another string, which of course also says "IR Baboon big star of cartoon", when you took it -- and then I scrawl "I AM Weasel" on top of my string using my reference and now your string was changed because it was COW.

If you liked COW for this purpose Rust has std::borrow::Cow which is a smart pointer with similar flavour, Cow<T> is a sum type that's either a thing you own T (and thus you could modify it) or it's a reference, perhaps &T (and thus you can't modify it) but which promises you could get an owned thing (e.g. for strings by deep-copying the string) if you need one. Methods that would be OK to call on the immutable reference (e.g. asking how many times an ASCII digit appears in the string) work on Cow<T> and if you find you need to mutate it (maybe in a rare case) you can ask the Cow for the mutable version, if it already had the owned version you get that, if not it will make one for you.

Rust's traits kick in here, Cow<T> requires T: ToOwned, which is a trait saying "I can make an immutable reference to T into a new thing T you own", obviously types you shouldn't do that to simply do not implement ToOwned and so you can't make a Cow of those types. The standard library provides in particular an implementation of ToOwned for &str which makes Strings from it.

CoW strings with atomic reference counting was definitely the wrong choice for a multi-core universe. The performance penalty is way too high. If you need that semantic there are other ways to get it.
Perhaps, but in the in the ancient past before STL was standardized, Chrome didn't exist.

10 years ago (when the parent mentioned they were still at Google) c++11 was already out.

While it's true that the Standard Template Library is truly a "long time" ago, being a 1990s project, the poster's phrase "before STL was standardized" actually refers to C++ 98 and C++ 03 where the C++ standards don't specify std::string internals.

Originally C++ doesn't have a string type, the C++ 98 standard does standardize a string type but it's only loosely specified. Most implementations do something "clever" which it turns out is a bad idea (this is a recurring theme in C++. Only in C++ 11 does the standard say OK, we'll prescribe how the string class actually works, making it more complicated but hopefully avoiding the worst problems.

Chrome was launched in 2008, and much of its internal structure was far older having incorporated work by Mozilla and Apple.

> work by Mozilla and Apple

Don’t forget the origin of WebKit, KHTML from the KDE folks.

Ten years ago was 2012. C++11 came out in 2011. Do you believe a big codebase like Chrome would be converted to C++11 less than one year after the spec was published? I find that unlikely but i never worked on such a big codebase so i wouldn't know.
The STL was mostly standardised in C++98, 1998. There were additions in C++03 and C++11, but nothing like removing this type of overload.

Long running systems were still using pre-standardisation libraries for string up to 2012 however, so you may well have come across such projects.

> C++11 came out in 2011

C++0x was a thing, with varying levels of support from all major compilers, for years before C++11 was finally ratified.

In the context of my original comment though, no matter how dated the code base, I think it unlikely that Chrome was using any variant of std::string that had an implicit conversion operator for const char* such that string could be passed as a parameter to a function taking const char* without needing to call c_str().

Ja, they have no excuse. They mostly just don't care. And why should they? Google cares nothing for them.
Based on the code changes made at that time, it seemed that Chrome developers didn’t know how to write performant C++ code.

Those were not difficult to understand C++ features either, but basic ones which were very well known by then. I remember reading Bulka & Mayhew’s Efficient C++ (published in 2000) which mentioned the importance of avoiding copies, calling reserve and many other techniques.

So your point is wrong. Not copying strings all over the place, calling reserve, not creating temporary containers are junior-level C++ skills.

Yes.

In two words, Google programmers are, as a rule, vastly overrated. They can maybe rope in 100,000 cores on one query, but nothing in their recruiting selects for good coding habits.

Anybody coding C++ in this day'n'age and getting use-after faults needs to go to the back of the line. They will certainly succeed in writing new Rust code that is as bad as their old C++ code. (Note: deadlocks are officially "safe".)

Recently Google made a big push to change the std::string constructor from a null char* to yield the empty string, instead of honestly segfaulting. That failed. They had a half-baked (and hellish, for users) async/await design they tried to put up as worth delaying the whole feature into 2023. That failed.

So where are those mythical "good C++ programmers"? I keep hearing that if only you find them, your C++ will be secure. But so far nobody has found them. Not Google, not Microsoft, not Mozilla.

Rust succeeds, because it does not rely on programmers writing bug-free code. Bad Rust code is not as dangerous as bad C++ code.

BTW: deadlocks are not exploitable for RCE, and are quite easy to debug compared to data races and heap sprays.

There is a very great deal of good C++ online. Google and Microsoft are handicapped by their need to hire in huge numbers, and must take who they can get.
I don't normally want to be personal, but ncmncm you chime in with this thread each time. Can you give an example of what you yourself have written that would live up to your standards? I'm curious what type of thing you're talking about.
If all the dependent C libraries are replaced with C++ versions, then the no.of translations will become zero?
Nominally, yes. But conversions between C strings and `std::string` are just a small corner of the problem: C++ makes it very easy to accidentally call copying constructors and perform nontrivial copies when doing e.g. implicit argument conversion.
Yep, another serious performance problem (also at google, not in chromium) was caused by inaccurate declaration of lambda arguments in an STL algorithm call … ie std::something(begin, end, [](std::pair<foo, bar> foobar) -> bool {}). The actual type (iterating over an unordered map, I believe) would have been const foo, but the compiler correctly concluded it could implicitly create a pair of foo,bar by copy from pair of const foo,bar. These were the days before such arguments could be declared “auto” which would have avoided the problem.

You have to think very very carefully about every line and character in C++ to figure out what it’s doing. Sometimes the easiest way to review it is to compile it and read the assembly.

Conversions that create copies are always explicit in Rust (unless it's a copy type, which strings aren't). Conversion between the string types is at minimum taking the borrow of it and then taking a copy of the borrow is once again explicit. You can also cheaply use a CoW wrapper to get a no-copy string passed around into plenty of places.

The point is, with rust you have more options to enforce no-copy through the type system.

How would Rust help here? Isn't it famous for having too many string types?
It's the 'too many string types' that helps.

With C++, if you have char*'s (because you don't need to own the memory) and you pass it to a function that takes a const std::string& (because it also doesn't want to own the memory), then there will still be an implicit conversion to a temporary std::string (involving an allocation) despite neither the caller or the callee needing to own any memory.

With Rust, if you have a &str (because you don't need to own the memory) and you pass it to any function that takes a String (or even the unidiomatic &String), then you will get a compile error. There won't be any implicit conversion of types and therefore no implicit allocation. If you really want to pass it, you need to explicitly convert it, making the cost of the allocation explicit.

Rust's "too many strings" model says "there are many different ways in which you can use string-like objects, each with their own performance tradeoffs. Know which one you want to use in your code or I won't compile".

This discussion is making me wonder if windows-rs [1], the crate with official Rust bindings for all Windows APIs, is doing something that's not idiomatic Rust. Specifically, for any Windows API function that takes a UTF-16 string as a parameter, the signature for that parameter is something like "impl IntoParam<PCWSTR>". The crate then implements that trait for String and &str, so you can pass a normal Rust UTF-8 string (even a string literal), and it'll be automatically converted to a freshly-allocated, null-terminated UTF-16 string (which gets freed after the function call). That seems like it could lead to the same thoughtless inefficiency as in the story about the Chrome omnibox.

[1]: https://github.com/microsoft/windows-rs

Well that will be necessary until windows gets UTF-8 APIs. Probably not soon. Until then there are various optimizations you can do, like caching the UTF-16 conversion alongside the UTF-8 string (good for calling OS APIs frequently with with long-lived strings), allocating temporary UTF-16 conversions on the stack (good for infrequent calls with strings up to a certain size), or storing raw UTF-16 strings as opaque bytes in Rust memory (good for providing strings back to the OS that you got from the OS).

You should try to avoid calling OS APIs in general and cache the results as much as possible. Who knows what the performance characteristics are of an API that has to serve 7 layers of historical OSes simultaneously. Unless you're directly interfacing with the kernel you shouldn't expect much. Omnibar-like layered calls between your app and the OS are a worst-case scenario regardless of conversions.

winapi does support UTF-8 on recent versions:

https://docs.microsoft.com/en-us/windows/apps/design/globali...

That might hide it from the caller, but the function that receives that IntoParam type will still need to explicitly call the conversion function.
Yes, and all those receiving functions are auto-generated as part of windows-rs.
It would most likely suffer from similar problems when interacting with the C and C++ APIs in the rest of Chrome though (e.g. what to do if you have a Rust String, but the other side wants a const ref to a C++ std::string).
Use a CxxString: https://cxx.rs/binding/cxxstring.html

At some point there will need to be an allocation when crossing Rust -> C++ boundary because Rust strings are not null-terminated.

The difference Rust makes is that unlike C++, it is always explicit when the allocation occurs.

Unfortunately the restrictions mentioned on that page make it quite a pain to use in practice.
My minor, unpolished grievance with Rust's approach is that you have to do this for all kinds of types (e.g., Path vs PathBuf). It's tedious to have to write these pairs all the time, along with all of the trait implementations and so on. It almost feels like it would be nice if the type system could allow us to write `String` or `PathBuf` and automatically generate the corresponding `str` or `Path` types.
> With C++, if you have char*'s (because you don't need to own the memory)

If you are using C strings in C++ you are either doing something incredibly low level or don't care about performance at all. C strings require strlen calls or something equivalent for basic operations and you can easily run into code with exploding runtime if you aren't extremely careful.

> If you are using C strings in C++ you are either doing something incredibly low level or don't care about performance at all.

…or interoperating with C code?

But the temporary copy only happens going from const char * to std::string, so the C code would have to be calling C++ code.

std::string to const char doesn’t (usually?) require copying.

psst... std::string_view
A step in the right direction if you have a compiler with c++17 support.

Note: chrome only supported c++17 features in Dec 2021 [0], and whether std::string_view is allowed to be used is still 'to be determined'.

0: https://chromium.googlesource.com/chromium/src/+/HEAD/styleg...

A variant of what is becoming string_view in the standard has existed within Google's codebase(s) for years. I don't recall using it much in Chromium when I worked in there, but it's all over Google3 and is now in absl (Google's open sourcing of some of its base c++ components).

Chromium has "string_piece": https://chromium.googlesource.com/chromium/src/base/+/refs/h... which is at least 9 years old (was moved from elsewhere in the repo into base/ then)

Ah yes, the one that still just wraps a raw pointer in the end

https://github.com/isocpp/CppCoreGuidelines/issues/1038

And then someone will convert a std::string_view to a const char* and things will explode...
A mixture of culture and technology.

Technologically, Rust's only built-in string type, &str, is a reference to a string slice - that is, you can't change it (the reference isn't mutable) and it is both a pointer to the start of some UTF-8 and the length of the UTF-8.

What encoding? Always UTF-8. Only UTF-8. Not "Well, it's kinda UTF-8 but..." it's just always UTF-8. This moves the burden to a single place, your text decoding code, to do things correctly, and great news - the entire world is moving to UTF-8, so you're on a downhill gradient where every week this works better without you lifting a finger.

That reference knowing the length is brilliant. Trimming whitespace off a string? You can just make another immutable reference to the smaller trimmed string. Zero copies. Slicing a URL up into components? You can do that too, zero copies. And yet it's all memory safe.

Now, Chromium is not some raw firmware for a $1 micro-controller, so it has library types like Rust's alloc::string::String (you can just name it "String" in normal Rust code but that is its full name) which, as its presence in alloc suggests, is an allocating String type, you can concatenate them, you can make them by formatting a bunch of other variables, the default ones are empty, the data goes on your heap and so on. But, String is AsRef<str> which means if what you've got is a String, and what you're doing is calling a function that wants &str Rust is OK with that and it costs nothing at runtime. Why? Because that &str is just two of the elements of the String type you had, the pointer into the heap and the length, it's easy.

Rust has lots of other types for stuff like Foreign Interfaces, like CStr and CString (for the C-style NUL-terminated array of bytes which might be text) but your pure Rust code shouldn't care about those, often it can say (unsafely) "Look, the C++ promises this is UTF-8, we'll take their word for it" or "I only need it to have bytes in it, let's make [u8] and we're done".

Culturally, Rust programmers write &str when that would do. There's a strong cultural pressure not to write String when you really mean &str, and the compiler won't let you write &str if you needed String. So this results in less thunking of the sort complained about in C++

In C++ when I see `DoX(y)` I have to worry every time about temporary lifetimes, copy vs move operator, and a bunch of other things that are easy to miss during code review. It is so easy to accidentally copy large strings around many times in a performance critical loop.

Rust makes all of that easier to see during code review. It is very explicit about these things.

I'm a Google employee working on chromium and chromeOS and have been asking internally about rust support for over a year now, so it's exciting that it's making progress.

It's a complicated but well-thought out system which tends to avoid copies by making them explicit in the source code and preferring taking references or slices which are cheap operations.

The string slice for example is an Unicode-capable view into bytes of the string (immutably pre-compiled static bytes in the binary, bytes of fixed length on the stack or heap-allocated). The aliasing rules are enforced by the compiler, so it is safe to throw around pointers and sizes and not to worry about buffer overflows, as long as it compiles.

Everyone’s trying to justify the response when the honest truth is that no, Rust doesn’t solve the problem of abstraction layer impedance mismatches causing ownership to be dropped only to be reacquired at the next level. On a sufficiently large/complicated code base, the problem will arise.

As others have mentioned, various kinds of string types are baked into the language which makes it ergonomic to do “the right thing” from the get go, but hard to say. I would be skeptical of claims that it would make a difference, especially in the interim where you now have an added impedance mismatch with C++, Rust, C.

> Rust doesn’t solve the problem of abstraction layer impedance mismatches causing ownership to be dropped only to be reacquired at the next level

The expression of what C++ does here in Rust is awkward and, I think, nobody has proposed it because you'd never write that. Basically C++ char* is a raw pointer. Rust does have those, but you'd never use them in this context.

What you would use is either the borrowed slice reference &str or the owning String type, but in both cases we have an owned object and there's our crucial difference. If you've got the owned String, and I needed an owned String, I should ask for your owned String, and we're done.

In C++ "dropping" ownership as you describe is no big deal, the C++ design doesn't care, but in Rust if you actually drop(foo) it's gone. The references to it can't out-live that, if it's gone then they're gone. If you write code that gives away references and then tries to drop the thing they're references to, Rust will object that this is nonsense, because it is nonsense, you need to ensure those references are gone before dropping the thing they refer to.

As a result I feel you're greatly under-estimating the ergonomic difference.

> In C++ "dropping" ownership as you describe is no big deal, the C++ design doesn't care, but in Rust if you actually drop(foo) it's gone

I think you’ve built a straw man of my argument and then argued with that.

Clearly I meant that it seems possible that a sufficient complicated call stack could still be set up to jump between needing the owned String type and the borrowed &str type. That’s what I meant by dropping ownership as that’s what’s happening in the c++ code when you go between char*/string (the API is dropping its need for ownership). The argument of “ If you've got the owned String, and I needed an owned String, I should ask for your owned String, and we're done” is weak because that same argument would apply to C++ code and yet the code still ended up that way when you pasted together components in a very large code base. Now maybe it’s a bit simpler because you have string, string&, const string&, and const char* and doing that antipattern that happened in C++ just wouldn’t be ergonomic in Rust. Maybe. But that feels like a very thin argument and not “this is impossible in Rust”.

I am definitely not arguing that it's impossible but my experiences with Rust lead me to think you've significantly underestimated how important those ergonomics are.

The "I should ask for your owned String" argument does not apply equally well in C++ because of a crucial design infelicity in C++. Your caller may well not have an owned std::string.

In C++ raw char pointers are totally a thing. Because std::string is a late addition (if you learned C++ in the early 1990s a "string" class was maybe an interesting exercise, not a library type) the string literals aren't a built-in string type, and much of the API isn't shaped for such a type either.

Now, the effect is those are (sometimes) owning pointers, it is possible I own some C++ string in this sense, and all I have is a pointer into it. If I give you that pointer, it's not because I didn't give you the owned string, that pointer is my owned string. You want a std::string and there's no reason I would have one at all.

You can mutate these strings, but of course you can't extend them because you've got no way to know how to communicate with the allocator, maybe they live on the stack, or in a private heap. At the time this seemed like a good idea, today we don't think so.

That’s just poor software. A poor Rust dev would be one who clones everything.
`.clone()` is visible right in your code, though, unlike the implicit conversion/constructor magic.
But you could write a C++ class with a manual .copy() method and a deleted copy constructor (and other conversion constructors not implemented).

Doing that seems a bit easier than integrating a whole new language into your project (although I know Rust would have other benefits).

You could do that if you are the author of std::string. Unfortunately, very few of us are.
For me, the fact that the Linux project has decided that Rust will be included in the kernel was the point Rust has become a success. It's pretty clear at this point that Rust will be around for decades and start to replace the well established C space.
> the Linux project has decided that Rust will be included in the kernel

Isn't this a bit oversimplified? IIRC the Rust support was only started as an option for writing device drivers in Rust, not actual kernel code, and even this relatively simple use case looks like a herculean effort which required changes to feed back into Rust - which is a good thing of course, but currently it looks like the Rust ecosystem benefits more from that project than the Linux ecosystem ;)

Firstly yes, not all Linux targets are supported Rust targets, as a result if you were to rewrite Linux memory management code in Rust you can't ship that without breaking some Linux platforms. Over time it is expected that: Linux will stop caring about some very, very old targets; Rust will gain support for some more targets (especially those that aren't very, very old) and so this issue goes away. Meanwhile drivers cannot run on all targets so them being in Rust doesn't change whether your target can run Linux.

Rust for Linux was driven by existing Linux developers. So they obviously think that's great news for Linux not just for Rust. One reason is: Nobody else was delivering a viable way forward. If there were ten of these safe low-level languages and by doing nothing Linux could be sure one would pick "Make ourselves suitable for Linux" as its goal then they could just sit back. Instead Rust is the only game in town, so it's either adjust Rust [ e.g. Rust for Linux alloc crate doesn't have the concatenating + operator on String like your userspace Rust does because that's the sort of thing which makes Linus angry ] or risk not having any safe path forward for the foreseeable future.

And yes, ultimately whether Rust for Linux goes into the Linus tree at some point is always ultimately a decision for Linus Torvalds. It's just that he made friendly noises about it, and there are people putting the work in, so it's like for dozens of other prospective Linux features, we can assume it will land but we shouldn't assume when.

Rust For The Kernel Could Possibly Be Merged For Linux 5.20: https://www.phoronix.com/scan.php?page=news_item&px=Rust-For...
Initially for device drivers. Rust isn't precluded from other parts of the kernel forever. It's just that device drivers are an obvious starting point.