641 points · by doener · 5y ago · 433 comments
On the other hand I'm slightly suspicious of this movement. Rustaceans are very, very eager to promote the language. It would be interesting to know how much this movement comes from within the Linux kernel community or if it is driven more by the Rust community.
In any case the language seems to have potential of becoming a new mainstream systems programming language in a few years.
The rust community is naturally happy to help out, but I can't even imagine us being able to drive this sort of work...
But you are right, this is not coming from the Rust community itself. In fact, several independent groups have been thinking of using Rust in one way or another for kernel purposes, as early as... 2013 (!), e.g. from Taesoo Kim:
https://github.com/tsgates/rust.ko/commit/58f0fb8fdf4063f5b24a09cbfeec81bf28a9d81b
There were others: John Baublitz had a external kernel module going on, Samantha Miller also worked on enabling a FUSE-like API to write filesystems in Rust, etc. And, of course, Alex Gaynor & Geoffrey Thomas had the most mature Rust abstractions for external kernel modules.At the moment, in the project we have a mixture of people that come from a Rust or kernel background, which has been great. And most of us have used many languages in our work, not just Rust. Personally, most of my career has been around C++ and Python.
It has an implication that Linux is something that any enthusiastic group of outsiders could force their changes into. And that there are rust people would create such a group of outsiders.
It has an implication that rust people and linux people are disjoint sets.
It's generally taking this strange adversarial view to a collaborative endeavour. People aren't "rustaceans" or not, it's not a sports team. People are people, they generally program in a wide variety of languages, and use whatever they think is best given a certain context.
I'm not sure if I've fully captured what seems "off" to me about the comment, but hopefully you get the gist.
As for asking questions, that's a clear example of https://rationalwiki.org/wiki/Just_asking_questions - but at the same time the general sentiment seems to be frequently reflected in internet comments. I don't think it's a malicious case of this, just how they chose to express their opinions.
That's not my definition of long history! My first Linux kernel was just pre 2.0 and I used make config. Actually I used make config for quite a while before it got out of hand and I started keeping copies of the config to work from instead of doing it from scratch each time I did an upgrade.
I'm not the sharpest tool ...
It's long in comparison to Rust!
You make it sound as if those are two non-overlapping sets. I don't think they could pull off this project without intimate knowledge of the Linux kernel.
The landscape has now changed and Rust has now positioned itself as a language that actually does have very key advantages (in correctness and safety). While C++ has made large strides, its advantages now lie elsewhere (eg; drawing on a wealth of performant libraries-- something that the kernel has less of a sue of).
If you look at Linus's criticism of C++ (e.g., https://lkml.org/lkml/2004/1/20/20), he criticizes a few specific things about the language - exception handling, implicit allocations, complex OO. Rust, as it happens, doesn't do any of that. Errors are passed back via return values (which is what the kernel already does), memory allocations are explicit by convention and "zero-cost abstractions" are favored, and the OO model doesn't have multiple inheritance or anything, just interfaces (which is also what the kernel already does, in C, using structs of function pointers).
So I'm not surprised that he doesn't have similar harsh words for Rust. It solves a lot of the issues with C that have been causing practical problems for the kernel (apart from confusing aliasing rules and confusing overflow rules, there was also the problem a while back where a bunch of != NULL checks got optimized out), and it doesn't have the problems C++ has - in fact it tends to solve those use cases in a way similar to the kernel's existing approach.
For my part, I've been involved a very tiny bit in Linux kernel development for well over a decade because I find systems programming cool, and I've also been involved a very tiny bit in Rust starting around 1.0 because I find systems programming cool. I started this project because I genuinely thought Rust would be a good choice, not because I was deeply involved with the Rust community and I wanted to evangelize it.
(I looked up the IRC logs where Alex and I decided to start working on this, and the context was that Alex had run into some bug with buffer length handling in the kernel, he was considering sending in some patches to improve the C abstractions about this, and since PyCon was the following week I semi-jokingly asked if we should instead spend our sprints time writing support to ship kernel modules in Rust. Which we did.)
Rust got luckier here, by the time Rust was invented programmers knew they really care about this, and so Rust explicitly distinguishes Copy (this object is just bits, so you can duplicate it by copying the bits), from Clone (this object can be duplicated, but you need to call its clone() method to explicitly do that work) and gives Move semantics to all assignments of types which do not have Copy.
So in Rust "let a = b" definitely isn't doing memory allocation, it just moves bits. If you misunderstand the situation and assumed b is still valid because it was Copy, but actually it isn't, the compiler has your back and will politely refuse to let you use variable b after it was Moved. If you did still need b you can write "let a = b.clone()" and now they both still exist but anybody can see this code might be doing something expensive 'cos it calls this clone method. And if the compiler says "Ahem, you can't Clone that" then you've just learned something very important about the thing that a minute ago you assumed was just a few trivially duplicated bits.
In such a project where allocations matter one would not stare at class definitions, one would ensure that there are no allocations by forbidding use of libraries like the STL and for example disabling operator new and the copy constructor. If the project is safety-critical there are tools which can enforce such rules.
Edit: I've clarified that I was referring to C++ libraries only.
Rust does not allocate implicitly when you use Vec or String (or any other container) ? come on..
In C++ you can write code like this:
#include <string>
#include <iostream>
void print(const std::string &s) {
std::cout << s << std::endl;
}
int main() {
print("Hello world!");
}
This compiles with no warnings, and at no point in the function "main" do you see that you're causing a memory allocation and a copy by implicitly converting your static message to a std::string, passing it to the function, and deallocating it. If you code-review "main", it doesn't look like you're doing an allocation because you're passing a const char *; if you code-review "print", it doesn't look like you're doing an allocation because you're accepting a std::string, which has already been allocated. So you get an extra, unneeded allocation in the chasm between the two, and it's very hard to track down the performance problem (or, in the worst case, a hang - memory allocation can block on flushing buffers or swapping things out, so you'd better not run into this situation in code that could itself be involved in writing to disk!).Compare the equivalent Rust code:
fn print(s: &String) {
println!("{}", s);
}
fn main() {
print("Hello world!");
}
which produces a "mismatched types" error: "expected reference `&String`, found reference `&'static str`."To get this to compile, you have to write something like print(&"Hello world!".to_owned()); , where you specifically instruct an allocation to happen.
The objection is to implicit allocations. Explicit allocations are fine.
The new() functions for these types are const (ie they can be evaluated at compile time) and produce an "empty" placeholder.
Because Rust's Strings don't have NUL termination, the empty string doesn't need any backing storage, likewise for an empty vector.
When (and more importantly in many programs if) you actually add something to the string or vector that may prompt an allocation, but you called an explicit method to do that, so it oughtn't to come as any surprise.
So it's not surprising to me that Torvalds is critical of languages that don't cater to his use case. Nor why he's less vocal about Rust. The allure of Rust is inbuilt support for multithreading, protection against data races, and an efficient memory management system.
Any feature useful for coding libraries is equally useful for kernel coding, because the overwhelming majority of kernel code is identical to what goes in libraries, and much of it is, explicitly, library code.
Remember, this is the guy who used tarballs as a version control system up until Bitkeeper gave him free (as in beer) licenses to their DVCS. He didn't hate all version control, as much as he thought that was the case - he hated badly implemented version control, which was the standard at the time with things like CVS. That's why he ultimately wound up writing Git once the Bitkeeper deal became untenable.
In this set of old e-mails from a decade and change ago[0] he specifically calls out STL/Boost being unstable and difficult to work with, C++ providing certain abstractions that have undocumented performance problems, exception handling, and hidden allocations.
Of that list, I can think of several things Rust specifically solves relative to C++.
- Rust traits make reasoning about generic code way easier than C++ templates. In C++, you just write your template, and then the template is resolved at the site of instantiation. If it's not a valid type to put in there, then the compiler tells you that you used the template wrong, but it's still your responsibility to figure out why. In Rust, however, generic types have to be constrained with traits; which list out exactly what a generic type requires. So if you misuse a generic type, the compiler can just say 'well, you need Add on parameter T here to call this', and the error will always be on the type you used, rather than some dependent generic type.
- One of Rust's core goals is "zero-cost abstractions". It does this very well, but it also has some non-zero-cost abstractions. These I'd categorize as "transparent-and-predictable-cost abstractions". For example: Rust is known for it's borrow-checker, which provides compile-time verification of memory safety. However, these might not be the most flexible memory-management solution; so it also provides shared-ownership through reference counting. This does have an associated cost, but it's easy to reason about and clearly stated. They even provided both atomic and non-atomic reference counting options because the latter has less cost associated with it.
- C++ uses an exception handling model built around stack unwinding, which requires that all code maintain a valid stack that the C++ runtime can unwind at all times. This can pose problems for kernels which almost certainly will be doing weird things with the stack that the compiler won't entirely understand. While Rust has exceptions (called panics) and supports C++ style unwinding, it also allows you to change the exception handling model to just terminating the program instead, which matches better with how the Linux kernel handles exceptions.
- Rust also heavily discourages the use of exceptions relative to C++. Panicking is mostly reserved for error conditions that are actually exceptional (i.e. unexpected), while error conditions that are expected can be signaled using return types like Option and Result. There's even special language syntax (called Try, or the ? operator) which will automatically return if a value signals an error.
The only thing I can't say Rust solves is hidden allocations, but it seems like the plan Linus has picked is to tame that beast with a Linux-specific core library, with as much as possible mapped to Linux's existing C abstractions. This probably will work out as this is the intended way to extend existing native code with Rust libraries. (It's how Mozilla integrated things like Servo into Firefox.)
It's my understanding that Rust got that term from the C++ community.
* Point one is a convenience/ease of use topic. Absent C++20 concepts or alternatively static asserts and enable_if, error messages will be harder to parse by the programmer. The one place where this may be relevant is for custom containers, but a kernel list for example wouldn't have to implement iterators and certainly doesn't need to follow the STL design which can cause hard to understand errors.
* I don't understand what you mean when you say that Rust "solves" zero-cost abstractions, but C++ has had this goal for a very long time.
* Exceptions would be disabled when doing kernel development. That being said, having exceptions in application development can be very convenient. C++ supports both, but std::optional and the like are not as elegant as in Rust.
By default, just like Ada, C++ allows to disable exceptions and use other error checking mechanisms.
As a real life example, macOS drivers don't use exceptions.
Or that Linus is going through something very respectable.
Which is good, although I wouldn’t have minded a bit of old school Linus for the anti vaxers.
Looking at the complexity of Rust versus C and the very limited benefits one would get out of adding a few drops of memory safety into a sea of C, one has to conclude that technical merit alone does not explain this decision.
In any case, I don't think Linus will write another language rant after he had an epiphany about his "unprofessional" attitude. And if there's enough corporate support combined with some grassroots support, he's probably figured out that he'd lose that battle even if he were nice about it.
I'm not even sure what this means. What do you consider a militant attitude in this context? From what I've seen, most Rust evangelists (at least here) try to explain its benefits while acknowledging cases where it may not provide something better and is instead equivalent but different or slightly worse (it's not like any language can be better in every respect).
> the very limited benefits one would get out of adding a few drops of memory safety into a sea of C, one has to conclude that technical merit alone does not explain this decision.
I don't think that's a valid conclusion, but even if it is, you haven't explained it well enough. You haven't addressed how much more complex Rust is than C no how limited the benefits would be. You've provided a tiny bit more information than "it's not worth it", which I think is far from sufficient to support that position in a discussion that can have as much depth as is easily achieved here.
> In any case, I don't think Linus will write another language rant after he had an epiphany about his "unprofessional" attitude.
It's not like he's stopped calling being stupid for acting stupid or refrained from criticizing technologies he thinks deserves it. There are recent cases (mentioned in this discussion) that outline recent cases where he's done so. I'm not sure why you would assume he's all of a sudden deciding to keep his mouth shut about what would be valid concerns to bring forth if he had them, nothing to do with interpersonal communication problems he's had in the past.
Regarding technical merit, I like to think of Rust as a C++ with switches toggled in different ways and a borrow checker on top. It's complex to think in and to write in compared to C, but it's at the end of the day much easier to write correct code in. I won't go into all the details since that would take a long time, but I hope the kernel team will write about their difficulties with Rust once they encounter them, since that should be a very fun read.
Regarding Linus, I wanted to confirm to OP that their suspicions are not unfounded, because the other answers seem a bit like gaslighting to me, especially the one claiming it's a "weird question". There is definitely more to this than technical merit, but it doesn't have to be anything ill-natured from the Rust community. My theory is that Linus' spirit has been probably broken by the corporations controlling Linux development through their many commits, his getting older and grassroots support for Rust.
Rust heads into the kernel? - https://news.ycombinator.com/item?id=27248059 - May 2021 (179 comments)
Linus Torvalds on Rust support in kernel - https://news.ycombinator.com/item?id=26831841 - April 2021 (290 comments)
An RFC that adds support for Rust to the Linux kernel - https://news.ycombinator.com/item?id=26812047 - April 2021 (261 comments)
Supporting Linux kernel development in Rust - https://news.ycombinator.com/item?id=24334731 - Aug 2020 (354 comments)
Linux kernel in-tree Rust support - https://news.ycombinator.com/item?id=23800201 - July 2020 (491 comments)
Linux kernel drivers in Rust might become an option in the future - https://news.ycombinator.com/item?id=20833639 - Aug 2019 (254 comments)
With the initial announcement I mentioned that Linux will need quite a customized Rust experience, and was hopeful that this effort could improve the situation for everyone.
It's great to see this actually happen, with changes already flowing back into core and alloc.
A lot of progress in just a few months!
My small contribution to this, https://github.com/rust-lang/rust/pull/84266, is supposed to be just that!
- C pitfalls, probably documented all over the place.
- C idioms. These are hard to locate for most languages; I wouldn't know where to look in case of C.
- Kernel-specific C idioms. This is probably easy to locate and well documented, but I'd still expect it to be several thousand words.
- Code formatting tools. Are there any canonical formatting tools for C, or is it fragmented like for most older languages?
- How to test C code, which IIRC requires jumping through quite a few hoops.
- How to deal with text, which is a nightmare outside of ASCII in most languages.
1. Rust has pitfalls
2. Rust has idioms
3. Rust in kernel would have specific idioms
4. clang-format and uncrustify are two solid choices
5. Nothing is special about C that would make testing hard.
2. You are cherry picking. He also said "These are hard to locate for most languages; I wouldn't know where to look in case of C." Rust has some advantages from for example Clippy and from a very newcomer-welcoming and helpful community.
3. Rust in kernel would indeed have kernel-specific idioms. But it'll probably be very similar to other embedded Rust and relatively easy for a newcomer to pick up. (Ee'll have to wait and see, but there is good reason to expect this.) C in kernel is known to be very hard for other C developers to pick up.
4. Thanks for the info.
5. But some things are special about Rust that makes testing easy.
6. The kernel doesn't deal much with text and even when it does, it generally doesn't need to deal with encodings (let alone modern encodings). That said, text is really a nightmare in C. Even just ASCII is needlessly complex due to null-terination, badly designed functions and the regular C UB pitfalls. At least you did acknowledge it may indeed be a problem for C compared to Rust.
We have been in contact with a set of companies and academia members
that would like to use Rust as a second language in the kernel. Some
of them have already started to evaluate Rust for their needs using
the infrastructure we have already in place.
In particular, we have got a few statements from major companies.
In no particular order:
Microsoft's Linux Systems Group is interested in contributing to
getting Rust into Linux kernel. Hopefully we will be able to submit
select Hyper-V drivers written in Rust in the coming months.
Arm recognises the Rust value proposition and is actively working
with the Rust community to improve Rust for Arm based systems.
A good example is Arm’s RFC contribution to the Rust language which
made Linux on 64-bit Arm systems a Tier-1 Rust supported platform.
Rustaceans at Arm are excited about the Rust for Linux initiative
and look forward to assisting in this effort.
Google supports and contributes directly to the Rust for Linux
project. Our Android team is evaluating a new Binder implementation
and considering other drivers where Rust could be adopted.
In addition, IBM contributed the Rust kernel support for PowerPC
which was already included in the RFC.“I hope to see a switch from C to VB very soon. I've already spoken with various luminaries in the C coding world and most are eager to begin to transition. Having just gotten off the phone with Mr. Alan Cox, I can say that he is quite thrilled with the speed increases that will occur when the Linux kernel is completely rewritten in Visual Basic. Richard Stallman plans to support this, and hopes that the great Swede himself, Linux Torvaldis, won't object to renaming Linux to VB/Linux. Although not a C coder himself, I'm told that Slashdot's very own Admiral Taco will support this on his web site. Finally, Dennis Ritchie is excited about the switch!”
At very least the Azure Sphere OS team should finally adopt Rust, instead of doing security marketing with the 7 layers of whatever, and then shipping a C only SDK.
It is like they are absent of the company security efforts, while trying to sell us a story of how much they care about security.
If I remember well, only 512KB is actually usable by OEM applications on that platform.
I was using C++ on MS-DOS.
Not even C++ is supported on the Azure Sphere OS SDK.
Ironically they usally tend to evade the question when asked about it, to the point they ended up writing a very long blog post trying to justify C, and it had nothing to do with space requirements.
Rather industry expectations and other marketing speak.
Ada may be a good language, and GNAT may be a fine Free and Open Source Ada compiler, but Ada isn't a new programming language. Software developers only chase shiny new things. Ada is held back by its beginnings as a niche language with expensive compilers, it doesn't matter that this hasn't been the case for decades now.
Rust has opt-in memory safety issues but outside of those, does not require a GC.
Rust does not have Ada's constraint system. In that way, rust is easier (and arguably less safe) to program.
Ada didn't get the same love as Rust for the same reason D goes pretty unloved. The problem systems engineers needed solved was memory safety without a GC. Neither D nor Ada solve that problem.
I don't have enough experience with Ada to comment on whether its verbose and keyword-heavy syntax succeeds in this goal.
It's not like Microsoft isn't pushing Rust on their own platform. Every time a Windows driver does a use-after-free somebody swears at Microsoft for causing a bluescreen.
I've never read anything to make me think that Rust is a safer alternative than any of these options; the guarantees of the language are just assurances of its advocates.
Well [0]
https://os.mbed.com/docs/mbed-linux-os/deprecated-product/we...
I have distinct feeling this would benefit from waiting a little bit more to have various kinks straightened out.
> Like it was mentioned in the RFC, the Rust support is still to be considered experimental. However, as noted back in April, support is good enough that kernel developers can start working on the Rust abstractions for subsystems and write drivers and other modules.
From my point of view what counts is actual kernel development. If you are going to develop kernel because it uses cool new language but you would not if it was still C, you are probably not the right person.
Now, I think Rust has potential to be good kernel language, I am mostly concerned with toolchain, ability for people to read the code with comprehension, ensure correct code, etc.
You are taking this the wrong way around. It's not about people contributing to $PROJECT because it uses $COOL_TECH, it's about people being turned off from contributing to $PROJECT because of $MEH_TECH.
If Linux was written entirely in assembly, we'd be having the same argument about the introduction of C.
Also, simply by having god damn namespaces more readable names could be used at no downside.
Why's that? C is a tedious language that makes you do so much manual bookkeeping, I don't think I'd ever write it again (if I needed C for some reason I'd write a program to generate it for me rather than doing it myself). I think any decent developer would be put off by C to some extent. Sure, the people who really want to make a kernel may put up with it, but an arbitrary enthusiasm barrier is not the way to attract good contributors.
1. rust is easier to read than c/c++
2. The toolchain is llvm based and much nicer to use than c/c++. Hell your build scripts are also rust
3. Given the choice to develop in c or rust I would choose rust
4. In my own experience I have found rust to be simpler to Deal with correctness than c/c++
(I have been both a rust and c++ developer)
https://github.com/rust-lang/rust
The git repo has over 150,000 commits, 3,000 contributors, and 9 years of release history. The last 6 years of which have been post 1.0.
Also, Mozilla has been writing large parts of firefox in Rust since ~2017. There's some interesting writeups on hacks.mozilla, including this one on reducing CVEs with Rust
https://hacks.mozilla.org/2019/02/rewriting-a-browser-compon... https://research.mozilla.org/rust/
I do embedded development on ARM Cortex-M3 and while it is possible to do this in Rust, I have experienced a bunch of issues with the toolchain and I have decided to stay on C until toolchain improves.
Don't get me wrong, I like Rust. Just don't allow liking something get in the way of practicality.
Microsoft actually did do that in the 90's.
Feels a bit like the "new more efficient battery technology" recurring post.
edit: to precise it's not that I'm not supportive of the effort, just that it would be nice to just have a post when it's actually merged. The title is a bit deceptive
The Linux kernel has become one of the most, if not the most important piece of IT infrastructure. Progress of any further developments of it as well as the security itself are prime concerns for all users. So far the development was solely limited to C, with all the tradeoffs. It is highly interesting to see whether a more modern language can be incorporated and the Rust effort looks very promising. Both from the language capabilities as well as the progress being made.
Ada, C++, Java, Objective-C, Swift and yes Rust.
In the long term, LLVM/Rust support for more architectures improves, and support for older architectures is dropped, this will become a larger fraction of kernel modules, but it will be a very long time until it is considered for something like ext5.
Note that the kernel still uses a lot of GCC specific syntax; it's just that LLVM/clang was laboriously made to understand all of that (with a few exceptions where the kernel was changed instead). And when they were almost done, the kernel started requiring another new GCC specific syntax, so they had to chase after that too.
[1] https://github.com/alkhimey/Ada_Kernel_Module_Framework/blob...
The point is to integrate the Rust language to the Linux infrastructure so you can merge rust drivers to the official code base.
They've been accepted into linux-next, which is a staging ground and used for testing, but that by no means guarantees that they will ever be accepted into the mainline kernel.
It seems to me like a Trojan horse from G and MS that pursue their own interests with their own OSes.
I don't know much about Rust so can't comment on that part. But agreed on the Scala part. Having seen Apache Kafka use Scala in the early days, when Scala was considered "hip", alongside Java code in the same codebase, I can relate to the mess it created and continues to be even today. At some point there was a plan to move away from Scala in Kafka, not sure where that reached, I stopped following that project since a few years now.
Just the opposite. We're going to see C deprecated for new code and efforts to move the existing C codebase to Rust. C is pretty much unsafe at any speed; Rust allows even junior front end developers to fearlessly contribute bare-metal code once they've learned the language.
Adding a 3rd language would be madness, Rust is already complex enough - so that window of opportunity will be closed.
Furthermore, for a language to be supported, it must have enough infrastructure (tooling, people, convention...) to support that language first, so people to review patches shouldn't be a problem.
Obviously, language should not be added willy-nilly, it must prove that it can solve some problem that the current set of languages can not solve efficiently, and base on that merit, it will choose to write/rewrite the modules that have the most of those problems first.
TL,DR: a decentralized codebase.
...
Also, why is this in big-endian order?
Let's just try to kill big-endian data, it's disgusting
and should just die already.
BE is practically dead anyway, we shouldn't add new cases. Networking
has legacy reasons from the bad old days when byte order wars were
still a thing, but those days are gone.
https://lore.kernel.org/lkml/CAHk-=wisMFiBHT7dLFOtHqX=fEve3J...To me, big endian makes a lot more sense - integers are stored in the order which you read them (mentally).
I do remember reading about how little endian enabled some type of optimization inside the CPU, but I forget the specifics.
Specifically, the problem is with "carries". When you're adding (or subtracting, or multiplying, or dividing, I'll just discuss adding) two binary values you might have to carry a 1 to the next place.
If you've got a BE value and an adder stage smaller than that value (say, a 32-bit number and 1-bit adder stages) you have to carry a 1 many times to output the result. If you're receiving the value in BE order 1 bit at a time you can't start the computation until you have the LSBs of both values, since if they're both 1 they'll affect the second bit by their carry. So you're stuck waiting for the entire value to start the computation. Further, during the computation you have to wait for every 1-bit adder in sequence.
There are "fast" adder designs that don't have to wait for every bit, but can instead work on groups of multiple bits with a carry-out at the end of the group. So if you've got an 8-bit group size, you'd have at most 3 carry delays during the computation of the output. For BE, you'd have to wait for all 4 bytes to be received, then wait for all the carry delays. For LE, you can start the computation as soon as the first byte is received, saving some time.
The larger the adder group size the more die area is needed, the stronger the drive strength of the transistors needs to be (bigger fan-out), and the slower the maximum clock of the overall system. On the other hand the bigger the group size the fewer carry delays, so addition can take fewer cycles. Most CPUs and MCUs implement single-cycle addition of their word size. Some CPUs even implement single-cycle multiplication at their word size.
Obviously this example is very contrived. This sort of thing was much more of a concern on 8-bit computers. But little endian still seems more natural to me.
Some of the other replies have minor technical reasons, but I've always preferred big endian for the readability. Having said that, I'm happy to part with the idea of big endian if it means an end to having 2 options to worry about. One thing that bothers me a lot about RISC-V is that the standard claims to allow either big or little endian implementations. Little has won and nothing new should support big endian IMHO. The benefits of either are largely irrelevant, but the existence of both is a problem. Or maybe it's that the existence of code that cares is the real problem ;-)
I'm half convinced that he was racing to be first to give it a seal of partial-approval to keep comments more on track.
Yeah, this isn't true. Low level hardware receiving data still likes to use shift registers:
* Zero shift reg
* clock in one byte, shift into shift register
* Clock in next byte, shift into shift register shifting the previous byte left one
* Repeat for as many bytes as you have
If you want this to work for a variable number of bytes, then you need most significant byte first, so that everything more significant is pre-zeroed. This is not theoretical - we did this for an FPGA network offload thing last year.Processors can't agree on endinaness, but network protocols have. "Network byte order" is a standard thing that is almost completely universal across communication protocols.
What he is saying is that for pretty much everything else (read: typical CPUs) it's all little endian now.
Basically, I understand that shifts for incoming serial bits is very convenient. But as long as you specify the "word size" used in your local memory, I do not see the problem: just use 8 (for instance) shifts for your 8-bit word and then go to the next memory location. Why is this fantasy wrong?
It is the default byte order in Java bytecode.
So I'll instead just give reasons why people might prefer to program in Rust:
- Memory management / safety (no GC, variable lifetimes are tracked by the compiler, no dangling, no null pointer ...)
- Ergonomics (built-in unit tests, feature-full std lib, unicode strings, modern dependency manager, more formalized macros ...)
- Functional-lite (you must explicitly discard unused enum variants, the "null" value is an enum variant ...)
Long story short: Rust makes it really easy to write sound software. I think you see that on crates.io where Rust packages are hosted. Lots of packages quickly reach maintenance mode and receive very few updates, but remain extremely useful. Once you've written (compiled) something in Rust, you feel much more confident that is is free of latent runtime bugs.
Without commenting on whether or not this is necessary or good for the Linux kernel, I'll say that there are probably many devs out there that feel like working other non GC languages feels like pulling teeth after having worked with Rust. And that might be part of the pressure.
Though dealing with rust dependencies by hand is usually nicer than dealing with C dependencies by hand because the build process is more standardized.
Dangling pointers are not a thing.
No double free.
Forces you to think up front about what are the possible state something could be in, and so you won’t get runtime or weird UB.
lastly, to be more pedantic for everyone who is at Linus-levels, it’s like all the best static analysis and warnings/errors all rolled up natively into the language. Please don’t bombard me with “but I can just run clang’s X and get the same thing”. No you can’t, and if you did this forces you to run it regardless.
Yes, we can.
Type inference
Language support for tagged unions (which they call enums for some reason), which among other things results in error handling which is "out of channel" instead of magic return values.
Speaking out error handling - syntax for easily forwarding errors to the calling function.
Generics, and therefore
- Libraries of collections with a rich collection of methods implemented for you.
- Library support for lazy iteration
- ...
Method (postfix call) syntax allowing for readable chaining
Hygenic macros
Compiler supported test harnesses
Compiler supported linting (that is really good)
Compiler supported automatic formatting (that is really good)
Compiler supported vtables
(pointer, length) strings
Proper namespaces
And so on and so forth
Probably because the simplest case of Rust enums (without any data other than the tag itself) can act similar to a C enum, to the point that you can "#[repr(C)]" it and use as FFI for the equivalent C enum. One understated advantage of Rust for C programmers (which is on topic given that the Linux kernel is written mostly in C) is that its syntax and keywords have many similarities with C, starting with the use of braces for blocks and semicolons to end statements.
> and use as FFI for the equivalent C enum.
Only if you're willing to accept undefined behavior if the foreign code passes you an unknown variant. For actual ffi work I've ended up using a macro that makes a "#[repr(C)] struct EnumName(u32)" with a bunch of constants for the values.
For example your Rust function that always returns 42 should probably be:
const fn fortytwo() -> i32 {
42
}
But C programmers might try: const fn fortytwo() -> i32 {
return 42;
}
And that works fine, the compiler sees that you wanted to return 42 here, and, although the value at the tail of the function is an empty tuple and thus incompatible with your function signature you never reach that tail, so no problem.2. Ergonomic use of functional idioms like sum types (Rust's enums)
3. Memory safety without GC overhead - Windows, Linux, curl, over and over again 40% of vulnerabilities in larger C projects are found to be preventable if there was a memory safe language
The ownership/lifetime system is basically novel to Rust (well, it's based on Cyclone, which would probably have been an interesting choice for the kernel too because it's based on C, but Cyclone is no longer actively developed), and it allows you to get the performance of manual memory management (no refcounting required) without either leaking memory or hitting use-after-free bugs.
Rust's ownership system also tracks shared/immutable references and unique/mutable references at compile time, avoiding a whole bunch of setups for creating race conditions or otherwise corrupting data.
> Rust's ownership system also tracks shared/immutable references
But there are some significant improvements WRT memory management/indirection.
Learning a language people do systems programming in can be a good experience but it doesn't need to be Rust for you to get that experience.
If you want to learn Rust because you want to, that's fair too.
Now, if you plan to do any kind of systems programming, C and C++ are unavoiable, as that is what the majority of the jobs still expect one to use.
Also, if you're "just starting" don't burden yourself with legacy stuff. Unlearning that when starting with Rust isn't a cake walk.
You may edit an HTML template here and there.
Maybe even some configuration work for CI/CD.
Rinse, repeat, with whatever new language/framework is hot right now.
Basically, you will be solving the same set of problems on every job, but in more convoluted and unnecessary ways, because the guy who worked at Google says that's how they do it over at the FAANG.
Rust is a pretty good language but it's not the most used. Also you have to take into account that you can't use Rust on every field.
If you're looking to be an Android/iOS/web dev, Rust is not the best option.
Web technologies? CI/CD, IT automation, etc.?
Or something more like operating systems, robotics, hardware, drivers?
Or do you want to self-educate for the sake of it, to learn different paradigms and be a better programmer in general? (Everyone wants to do this, but not everyone has the time).
Golang and Python are incredibly popular in the automation/"glue code" space.
Java is popular in enterprise development (think banks).
Systems languages are popular if you're developing... systems.
For fun and interest? Why not?
https://blog.rust-lang.org/2021/05/10/Rust-1.52.1.html
"The Rust team has prepared a new release, 1.52.1, working around a bug in incremental compilation which was made into a compiler error in 1.52.0. We recommend all Rust users, including those currently using stable versions prior to 1.52.0, upgrade to 1.52.1 or disable incremental compilation. Guidance on how to do so is available below."
Is this mature enough to be bring in the kernel ????
rust is more of a secure c++, that has its own object oriented pattern, which linux kernel uses a lot but in C.
here's the word count
rust: 13 in: 11 the: 10 to: 8 a: 6 and: 5 for: 5 linux: 5
On a more serious note, I am curious to see what license RIIR Linux will have.
I'd rather see a new kernel optimised and written in Rust from scratch rather than dragging the legacy skeletons around and also bringing the vulnerabilities with us.
> On compilers, we would like to mention all the work that has been going in GCC Rust (a GCC frontend for the Rust language) and `rustc_codegen_gcc` (a `rustc` backend for GCC). The latter now passes all `core` tests, and the former is now working on traits. We continue to track their progress as they may become the best way to have GCC-built kernels with Rust support enabled.
Writing a new kernel with all the capabilities of Linux is an absolutely enormous undertaking, billions of dollars worth: "it would cost approximately $14,725,449,000 dollars [...] to rewrite the existing code." -- https://en.wikipedia.org/wiki/Linux_kernel#Estimated_cost_to...
30 years later, there'll be a kid in university somewhere about to send a thoughtmail that says "I've written a version of..."
There is Redox, which was intended to be practical, but I'm not aware of much public interest in that. Phillip Oppenheimer blogged about one too, I think, but that's explicitly academic.
That'll take a momentous amount of effort and it'll take 20 years to get close to the adoption Linux has today. I'd rather see if we can improve Linux in that timespan.
In my experience with mid size projects the key to success has always been controlling complexity. I can only imagine that this is even more true for large projects.
Generally the complexity an additional language brings to the table is immense in several aspects.
Specifically Rust has it's own problems and drawbacks.
Looking back at the history of Rust and Firefox/Servo, introducing Rust was overall quite a disservice.
Now to contribute not only you have to learn C, but also Rust and get their complex dev environment setup..
This fragmentation is very bad, seems like they embrace the linux distro spirit.. what's gonna be tomorrow? zig support?
Lot of effort wasted in making things more complicated, definitely not a positive move
"The linux-next tree is the holding area for patches aimed at the next kernel merge window. If you're doing bleeding edge kernel development, you may want to work from that tree rather than Linus Torvalds' mainline tree. "
Being able to do kernel development in Rust should lower the entry barier into kernel a lot. Because it has more high level constructs and especially for all the safety Rust brings. Any competent programmer should be much more comfortable to start kernel dev with Rust than with C.
Rust feels like a modern language, like Go or C#. C is barely better than FORTRAN.
I'm massively more productive in Rust and I don't have to worry about a million ways of causing UB or memory bugs.
Everything from dependency management to testing to cross compiling are dreamy in Rust compared to C.
Dependency management, packaging, and testing are what really made Rust take off. The best of any language I've used.
You now are going to have two languages + bolting on a kernel riddled with chronic security holes and still supporting dead architectures and 32 bit systems.
Well see if brown-fielding Rust into the Linux Kernel is all worth it for them.
C++ support could have been viable a decade ago had it not been for strong egos on LKML refusing to admit they were wrong. Rust support in Linux is at least partially a face-saving way of backtracking on C++ in the kernel.
Rust is great, but with the sole exception of Rust's reified lifetime management, C++ is the better language.
I don't know about "better" in the general sense, but for the specific use case of the Linux kernel, Linus has identified some entirely reasonable objections (though aggressively worded) to C++: https://lkml.org/lkml/2004/1/20/20
- the whole C++ exception handling thing is fundamentally broken. It's
_especially_ broken for kernels.
- any compiler or language that likes to hide things like memory
allocations behind your back just isn't a good choice for a kernel.
- you can write object-oriented code (useful for filesystems etc) in C,
_without_ the crap that is C++.
Those objections do not apply to Rust, which avoids exception handling, avoids implicit allocations, and has a much smaller OO system that resembles what the kernel does for filesystems. Those objections continue to apply to C++.There are good, principled reasons to accept Rust and continue to reject C++.
(There are also good reasons to believe that C++ doesn't solve any of the problems with human inability to write correct C, meaning that it wouldn't be worth the cost of adding a new language: https://alexgaynor.net/2019/apr/21/modern-c++-wont-save-us/)
> the whole C++ exception handling thing is fundamentally broken
Not an argument. It's the closest thing in Linus's excretion of unfounded technical opinion to an argument, but it's nevertheless not an actual case for anything. Don't like exceptions in C++? Don't use them. (That said, exceptions aren't "fundamentally broken" no matter how many times Linus repeats that baseless slander.)
> any compiler or language that likes to hide things like memory allocations behind your back just isn't a good choice for a kernel
This is a general-purpose tirade against any abstraction whatsoever. Good software engineering is all about judiciously "hid[ing] things", including memory allocation. And as it turns out, Linux has plenty of abstractions, some of which involve memory handling. Also, you don't have to use any particular abstraction with C++: you get to choose the abstractions. The language doesn't force any on you.
Besides: Rust can do the same sort of abstractions that Linus claims disqualifies C++ as a "good choice for a kernel". It's almost as if C++ was fine even back in 2004 and that the only difference between then and now is that Linus has matured.
> you can write object-oriented code (useful for filesystems etc) in C, _without_ the crap that is C++.
This is a restatement of Linus's opinion, not an argument. You can write everything in assembler too: why take on the baggage of the heap of crap called C?
I think there exists a solid and reasonable argument along these lines, even if Linus did not phrase it, though, which is what I'm getting at. (And I suspect Linus and others do believe that argument, even if they're not good at communicating it, so it would be worth engaging it.)
It's true that you could write C++ without exception handling, and that you get to choose the abstractions. But it matters what the language makes easy for you - what is idiomatic and conventional in the language - what programmers who use that language have come to expect their libraries to do.
Otherwise you could just say that we can solve our string problems in C without switching languages by simply using length-prefixed strings and buffers and not relying on NUL termination. After all, the kernel doesn't use a userspace standard library, and even in userspace there are string-handling libraries in C that avoid those problems (e.g., http://bstring.sourceforge.net/ or https://github.com/antirez/sds).
But the fact remains that the kernel has its own implementations of strcat and sprintf nonetheless (in the lib/ directory), simply because C programmers expect them. And people call NUL-terminated strings "C strings" and length-prefixed strings "Pascal strings," even though you can do length-prefixed strings just in C and NUL-terminated strings just fine in Pascal.
It is very hard to write abstractions in C++ that work the way the abstractions in Rust work and are still natural and easy to use. No one is disputing they're possible to write. But if you look at the blog post I linked, it demonstrates that even with the benefit of decades of experience in C++ and knowledge of what Rust is doing, and even with additional language features, and even with the input of people who did in fact choose their abstractions (std::string_view was based on libraries local to Google, LLVM, and Bloomberg), you still do not get the level of safety that the equivalent Rust feature has.
Concretely,
1. C++ has language-level features (most importantly, try/catch/finally) that make error handling via exceptions easy and natural to use. Rust has language-level features (most importantly, pattern matching on sum types) that make error handling via a result type easy and natural to use. You can of course choose not to use exceptions, but you're giving up a good language feature and you don't have language support for the thing you want to do instead. This is much like saying "Don't like NUL-terminated strings? Don't use them" - technically true, but have fun avoiding string literals.
2. This is not a general-purpose tirade against abstraction. It is a very targeted tirade against implicit conversions to heap-allocated types, which are natural and idiomatic in C++. See my comment https://news.ycombinator.com/item?id=27749301 elsewhere in this thread for details on exactly what Linus is objecting to and why it is entirely reasonable for a kernel to object to it. Again, you could certainly decide to avoid implicit allocations in your nonstandard library, but it is not idiomatic C++.
3. C++'s object model is legitimately quite complex, involving things like multiple inheritance, partially-constructed objects during the constructor, and phrases like "morally virtual base". It works - there's definitely a lot of working C++ in the world - but that level of complexity isn't needed by the kernel, and (certainly in my personal experience) it's easy to get into deeply confusing situations. The kernel also cares about things like fitting objects into cachelines. The kernel doesn't need multiple inheritance with the ability to have different offsets into an object depending on what pointer type you're using, but it does need the ability to specify that objects implement multiple interfaces that carry no data (what the kernel calls "operations structures," and what Rust calls "traits"). In C++, the only mechanism the language gives you for this is multiple inheritance. There are use cases where full multiple inheritance is useful, and C++ is preferable to Rust for such cases. The Linux kernel is not one of them.
It's true that you can do all the things Rust can do in C++ if you try hard enough. But I'd reiterate the point which you made clearly, that human beings simply do not seem able to write flawless C in practice, even though it is theoretically possible, because it is simply not idiomatic. From the blog post I linked, it seems like there's no reason to expect that asking humans to write flawless and unidiomatic C++ will work out any better.
For Rust to be judged differently is a huge signal, I think.
ARM "operating system" is hardly used extensively.
Arduino's are embedded devices and can be programmed in any language but are hardly applicable across the vast range and scale of Linux deployments.
IBM's primary operating systems that aren't Unix based are written in Assembler or even RPG.
Why? How, precisely, does C++ hurt?
> It has certainly been tried and in the cases I know of, regretted.
Did it? Fuchsia didn't regret C++ in the kernel. GDB didn't regret moving to C++. (I know GDB isn't the kernel, but it's systems-y.) Android's libc, Bionic, is also written in C++.
Every single argument I've seen against C++ in systems code has been specious: people act like typing "g++" instantly implants a copy of the GoF book in your head and turns you into a design patterns robot. "I don't like it" is not a technical argument. Neither is a profanity-laced rant, as satisfying as it might be to pound out such a thing.
You can just use C++ as a safer C. Linux would have gotten huge rewards in both safety and developer efficiency if LKML hadn't spent a decade doubling down on their nonsense arguments against C++.
Well put. Given the style of C used in the linux kernel, it should have been possible to restrict the use of C++ in the same way. Yes there is lots of bad C++ in there, but it doesn't have to make its way into the kernel. The maintainer s can reject code that is uses inheritance, or templates in the wrong way, etc.
It's like believing you shouldn't use C in the kernel because it's possible to write lines that are over 80 characters long.
And no, it wasn't C++ that killed Symbian or BeOS.
Windows NT kernel was all C apart from bits of the graphics layer - friction from that team's use of C++ is a theme in /Showstopper/.
It was quite difficult to write, and new hires had to essentially be retrained. Expecting an app ecosystem to be built on Symbian C++ was unrealistic. It's the lack of an ecosystem that killed it really.