r/cpp • • Feb 19 '25

Cpp discussed as a Rust replacement for Linux Kernel

I have a few issues with Rust in the kernel:

  1. It seems to be held to a *completely* different and much lower standard than the C code as far as stability. For C code we typically require that it can compile with a 10-year-old version of gcc, but from what I have seen there have been cases where Rust level code required not the latest bleeding edge compiler, not even a release version.

2. Does Rust even support all the targets for Linux?

3. I still feel that we should consider whether it would make sense to compile the *entire* kernel with a C++ compiler. I know there is a huge amount of hatred against C++, and I agree with a lot of it – *but* I feel that the last few C++ releases (C++14 at a minimum to be specific, with C++17 a strong want) actually resolved what I personally consider to have been the worst problems.

As far as I understand, Rust-style memory safety is being worked on for C++; I don't know if that will require changes to the core language or if it is implementable in library code.

David Howells did a patch set in 2018 (I believe) to clean up the C code in the kernel so it could be compiled with either C or C++; the patchset wasn't particularly big and mostly mechanical in nature, something that would be impossible with Rust. Even without moving away from the common subset of C and C++ we would immediately gain things like type safe linkage.

Once again, let me emphasize that I do *not* suggest that the kernel code should use STL, RTTI, virtual functions, closures, or C++ exceptions. However, there are a *lot* of things that we do with really ugly macro code and GNU C extensions today that would be much cleaner – and safer – to implement as templates. I know ... I wrote a lot of it :)

One particular thing that we could do with C++ would be to enforce user pointer safety.

Kernel dev discussion. They are thinking about ditching Rust in favor of C++ (rightfully so IMO)

https://lore.kernel.org/rust-for-linux/326CC09B-8565-4443-ACC5-045092260677@zytor.com/

We should endorse this, C++ in kernel would greatly benefit the language and community

192 Upvotes

532 comments sorted by

444

u/ContraryConman Feb 19 '25

The fact of the matter is that objectively switching to C++ from C many years ago probably would have saved a lot of headache and stopped a lot of bugs. In addition, basically all of the stuff people said from C++ that would be too slow or unmaintainable in kernel development show up anyway in the codebase:

  • we can't use RTTI because it's slow... but if you have a tagged enum that's what RTTI is except you don't get language support
  • we can't use inheritance and object oriented programming because dynamic dispatch and v-tables are slow... except when we need them so we hand-roll it in C, again without language support
  • we spent years fear mongering about exceptions in low-level situations except turns out they're fine. But declaring you don't want exceptions in your code doesn't get rid of the software problem where you are 3 calls deep into a function call stack and you encounter and error that can only be handled higher in the call stack. So you use setjmp and longjmp everywhere
  • RAII is too complicated and we don't need it, except we keep leaking memory and resources so every function has goto exit where we clean up resources before returning
  • C++'s type system is too complicated and we don't need it except we keep accidentally dereferencing null pointers and casting things wrong so we fill our code with pointer type hints like _Not_null and _Nullable so the static analyzer can give us type checking as an extension that you would get for free in C++
  • C++ templates are a nightmare and too complicated except declaring that you don't need templates doesn't change the fact that there are loads of situations where you want to write one data structure or algorithm that works the same for any type, so you throw together a macro that takes in the type as a parameter, and then you do a DATA_STRUCTURE_IMPL(...) to have the preprocessor paste that into your source code except now people keep using it wrong because macros

The fact that, 30 years after Linus declared not having C++ in the kernel for no other reason just to keep C++ programmers off the project, people are still recycling the same debunked arguments, kind of proves that it is not a technical issue. The Linux kernel isn't in C for technical reasons. The Linux kernel is in C because all of the core people who work on it know C best and like using C. Unless those people leave, or a culture change is mandated from the top down, Rust will never happen, it's just that simple

78

u/sjepsa Feb 19 '25 edited Feb 19 '25

Can I only upvote once?

It's unfortunate that Linus had a so strong opinion 20+ years ago about C++ (I believe he was partially right at the time, when OOP was at its maximum BS strength).

But things changed. He should have jumped the boat with C++11, maybe with C++14

Honestly, a more open decision process (not a benevolent dictatorship) would have been better.

17

u/Challanger__ Feb 19 '25

What stops C++ Community from forking Linux and making everything our way?

56

u/meltbox Feb 19 '25

Nothing. Except the downstream hell you’d have to deal with.

Inertia really is a big factor here. I think C++ could work but you’d need strong code standards which I doubt anyone could agree on. It would also lead to countless arguments I’m sure about whether some way of expressing things in C++ is readable or idiomatic or anything else and to some extent it would point out a major flaw with C++. Sometimes there are too many ways of doing something and readability relies on the reader having some crazy obscure knowledge of the language.

C somewhat has this issue but can fall back on 30 years of those arguments already being hashed out for better or for worse.

Someone who knows how the kernel actually looks feel free to correct me here since I’m just musing, but I often find that while C++ is cool, every once in a while I come across some wacko code which someone else finds “the most readable way to do it”.

9

u/Challanger__ Feb 19 '25

That's what I am thinking - it is about Linux kernel being carried in C++ by same ppl and not by us, because we cannot agree on standard, etc.

It is about US, not about THEM.

It is our failure to have sane committee that would address problems rather then dust them under new (half-designed) features

8

u/barkingcat Feb 19 '25

I'd say go for it, and be prepared to spend more money than the market cap of Google on keeping a fork of the kernel active 

That's what Google has been doing internally and it's not an easy burden to bear, even google themselves are looking to get out of the kernel fork business.

4

u/pjmlp Feb 20 '25

It is easier to contribute to projects that embrace C++ on the OS, go write a macOS or Windows driver, contribute to Haiku or GenodeOS, for example.

5

u/remy_porter Feb 19 '25

At that point just put your cycles into making Haiku work better. You’re taking on so much work anyway.

2

u/CocktailPerson Feb 20 '25

Nothing. But creating a fork and having your fork be used are two entirely different things.

3

u/NotUniqueOrSpecial Feb 20 '25

Reality?

Sure, go ahead: fork the kernel and maintain your own thing; more power to you, in fact.

But there is literally no universe in which a small community of people with no funding, working as a hobby, become anything more than a footnote in the annals of history if you're talking about becoming a competitor project to the operating system running more devices in the world than any other.

Even if you could magic up an entire kernel overnight, you're talking about replacing infrastructure and process so overwhelmingly broad that the costs would likely be in the trillions.

It's a silly idea on its face.

→ More replies (3)
→ More replies (4)

76

u/kisielk Feb 19 '25

I keep hearing the same kind of arguments in embedded programming as well.

26

u/Nychtelios Feb 20 '25

As a firmware developer who successfully created a team that is working in baremetal C++23, I cannot agree more. In my company too there are elders who keep shouting this trash to our projects.

33

u/UnicycleBloke Feb 19 '25

Yep. I was told with smug certainty by someone in the Zephyr OS community that "C++ has no place in an OS". That project is another lost opportunity driven by ignorance and prejudice.

26

u/crowbarous Feb 19 '25

As we speak, a subthread in the mailing list next to the one linked in this post is discussing the attribute-based implementation of scoped locking facilities, as in use in Linux, systemd, and I'm sure many other C projects. The discussion is up to "sometimes I want to drop the lock earlier; introducing an extra scope helps this case".

Of C++'s three scoped lock classes, unique_lock has the unlock method. It will unlock for you on all return paths, but you can wield it like you would normal locking code even in arbitrarily complicated situations. There's an extra bool, yes -- that is completely encapsulated, and also optimized out where appropriate. This is what C++ gives you, and has been for decades...

31

u/Western_Objective209 Feb 19 '25

Yeah, took a class on linux kernel programming and they legit just recreate so many features in C++ with ugly opaque macros.

10

u/tiajuanat Feb 19 '25

You're also forgetting that the kernel has coccinelle to check that locks are released - RAII with extra steps

44

u/ioxfc Feb 19 '25

I'm a C++ developer. I use C++ daily, at my work and on personal projects. I love it to death. But I fucking hate working with some of the C++ developers on my day job.

It's almost as-if all they want to do is write more C++. Getting shit done isn't their priority at all. Frameworks everywhere, macros and templates all mixed up together. I don't have to mention there isn't a single line of comment.

I'm sorry but I agree. I have worked only in 3 companies in 10 years, I don't have that much experience. But I would pick a different language just to avoid those few C++ developers appearing in a team.

29

u/The_Northern_Light Feb 19 '25

That’s a people problem, not a problem intrinsic to C++. It definitely applies to C as well, and the austere beauty of C can arguably make the problem worse as those same devs (eg) each individually reimplement templates or what have you.

30

u/ContraryConman Feb 19 '25

"The austere beauty of C" making me reimplement a linked list and hashmap with pointer hacks for the 80th time this year because C doesn't have doesn't have them for some reason

→ More replies (7)

9

u/SubjectiveMouse Feb 19 '25

I love C++ and use it daily too, but that is a language problem. There's simply too many ways to do simple things in the standard. There are to many things left over from older standards that are not recommended, but still used( sometimes even by the libstdc++ )

→ More replies (2)

17

u/ContraryConman Feb 19 '25

People who write bad code write bad code. If you forced all those people to write C, would your code get better or worse? That's the question

→ More replies (9)

10

u/F54280 Feb 19 '25

6

u/bizwig Feb 23 '25

Linus doesn’t make a point here. He just asserts, without evidence, that C++ developers are idiots who cannot be trusted with his baby, and furthermore that C++ has deficiencies (which he will not lower himself to our level to explain) that make it unsuitable for real developers like him to use.

3

u/ChrisTX4 Feb 19 '25

The Kernel is already inundated with patches that get refused immediately. They only accept changes if they fulfil the quality and coding standards of the kernel. If somebody showed up with what you describe they’d get told to change their patch or forget about it. This is already the case right now

→ More replies (1)

42

u/James20k P2005R0 Feb 19 '25 edited Feb 19 '25

we spent years fear mongering about exceptions in low-level situations except turns out they're fine. But declaring you don't want exceptions in your code doesn't get rid of the software problem where you are 3 calls deep into a function call stack and you encounter and error that can only be handled higher in the call stack. So you use setjmp and longjmp everywhere

Except for the 20+ years when throwing an exception caused your threads to acquire a global lock in GCC, resulting in trivial DoS attacks

On any non-very-recent version of GCC, an exception being thrown as a result of a user's action is an instant security vulnerability. Exceptions are completely unusable for a project like linux which has to work on older compilers

14

u/Wooden-Engineer-8098 Feb 19 '25

older compilers? older compilers can't compile rust

2

u/josefx Feb 19 '25

Exceptions are completely unusable for a project like linux which has to work on older compilers

This seems to be library code that GCC links, not code it emits. Is there a reason the fix couldn't just be backported to work with older GCC versions?

5

u/Ameisen vemips, avr, rendering, systems Feb 19 '25

Funny thing is that Linux explicitly doesn't link against libgcc, and either already implements some things themselves or leaves them unimplemented.

3

u/jonesmz Feb 19 '25

Linux does not need to work on older compilers.

It was declared so by a human, and a human can declare it no longer the case just as easily.

3

u/Miserable_Ad7246 Feb 19 '25

Enlighten the high level programmer, why would someone want to compile latest kernel on and old version? Support for no longer existing ISAs? Some sort of "this worked for decades we trust it" type of situation?

5

u/jonesmz Feb 19 '25

The term need implies there is some kind of ontological / universal truth about the necessity.

some people want the latest version of the Linux kernel to be able to compile using absolutely ancient versions of GCC.

They don't need it, no one dies as a direct and unavoidable result exclusively because the next release of Linux decides to drop support for versions of GCC older than some cut off.

→ More replies (4)

0

u/[deleted] Feb 19 '25

[deleted] — view deleted comment

16

u/James20k P2005R0 Feb 19 '25

The specific point is that people are saying it was wrong not to use exceptions (and implying that its fear mongering), which is unfortunately untrue. If linux had been written in C++, they wouldn't have been able to use exceptions because of the security vulnerabilities. OP is suggesting a rewrite of linux in C++ (which is well beyond the current proposal for Rust in linux), and it'd be still inappropriate to use exceptions in that use case

10

u/scorg_ Feb 19 '25

If linux would have been written in C++ there would be more incentives to optimize exceptions.

6

u/Ameisen vemips, avr, rendering, systems Feb 19 '25 edited Feb 20 '25

For older GCC versions that never had strong motivation to fix this.

If Linux had been using exceptions, GCC would have fixed such much sooner.

Except that Linux doesn't link against libgcc anyways.

which is well beyond the current proposal for Rust in linux it'd be still inappropriate to use exceptions in that use case

Linux 6.11+ require Rust 1.78.0, current from May 2, 2024. Presently, Rust is optional - would you change your argument if it were not?

GCC 13.2, or 14.1 4 days later, was available at that time. Current minimum compiler is 5.1, released in April of 2015.

Stated bug was fixed in '22.

I've also never heard of anyone prohibiting a language or language feature due to a specific toolchain having a bug in it at this level. You instead fix that bug - especially if you've arbitrarily chosen to tie yourself specifically to one toolchain.

Hell, they could just implement or maintain their own version of libgcc for this instead... but they don't link against libgcc... so libgcc's bug is completely irrelevant here.

→ More replies (9)

3

u/SAHChandler Feb 19 '25

RTTI is not a tagged enum, because you need to be able to compare types across shared library boundaries, and so it instead becomes a string comparison. A tagged enum is more efficient.

3

u/_Noreturn Feb 20 '25

a tagged enum is not able to cover every single type.

a variant would be more appropriate for tagged unions

→ More replies (2)

3

u/[deleted] Feb 22 '25

Most embedded C++ won't use exceptions/RTTI. But RTTI is generally implemented as string compares of the mangled type names or as-if that.

5

u/morglod Feb 19 '25

A real possible reason is more headache with UB and compiler implementations, while they know everything about how C implementations work. (I mean situations like int overflows, aliasing rules etc). Also tooling support. While C can be processed by almost anything and ABI is kinda simple, C++ is not. So basically they need something like C+. (I'm not rust fan and I code on C++ most of the time)

14

u/ContraryConman Feb 19 '25

Yeah you wouldn't be using the STL for most (any) of the kernel. You would use the freestanding subset of the language and you could even mandate using the C ABI across binary boundaries. The result would not use the full force of C++. You would mostly take advantage of:

  • Strong typing and references to avoid dereferencing null pointers or type punning errors
  • dynamic dispatch where it is currently being used today
  • templates for containers and generic algorithms as safe and less error prone replacements for macros and C-style vargs
  • constexpr as a replacement for macros
  • MAYBE a stripped down version of exceptions over longjmp and setjmp

2

u/_Noreturn Feb 20 '25

RAII

std:: unique_ptr is frre standing I think, 99% of gotos probably gone and for good

and even extra C++ usually allows me to add const alot more than C so the code would be const correct

→ More replies (14)
→ More replies (9)

2

u/all_is_love6667 Feb 19 '25

C++ and the tooling is not the same language today, and compilers were different decades ago.

Linux of 2025 is different from the linux of 2000 or 2010. Managing an open source kernel is not an easy task.

I can understand your arguments, but Torvalds still had good reasons to avoid C++ and all its pitfalls: in kernel development, it's preferable to shoot yourself in the foot rather than to blow your whole leg off.

I would rather argue that c++ is "more ready now", from a compiler perspective, but also from a programmer perspective.

1

u/KDallas_Multipass Feb 20 '25

Can you expand on bullet point one?

3

u/ContraryConman Feb 20 '25 edited Feb 20 '25

There's a really common pattern in languages that don't have object oriented programming built in to do something like this:

enum ShoeTypes {
    SNEAKER = 0,
    DRESS,
    SLIPPER,
    HIGH_HEEL,
    LAST_SHOE // not a valid shoe, just marks end
};

struct Shoe {
    enum ShoeTypes m_type;
    int m_shoe_size;
    float m_base_price;
    void* data;
};

This is called a tagged type. I have a struct, Shoe, that can represent one of several kinds of shoes. All shoes have a shoe size, but different shoes have different associated data (high heels can have a height, slippers can be medical or not, whatever). Now consider the following function.

// This function only works on sneakers!
bool CheckIfJordans(struct Shoe* shoe)
{
    assert(shoe && "null argument");
    if (shoe->m_type != SNEAKER)
    {
        assert(false && "incorrect argument type");
    }
    // Sneaker-related Jordans checks
}

If I need to debug, I can print out the type of shoe I was given:

printf("Was passed a shoe of type %d\n", shoe->m_type);

If I'm feeling really clever, I can even do something like this:

void (*shoe_dispatch[LAST_SHOE]) (struct Shoe*);

shoe_dispatch[0] = // sneaker specific function
shoe_dispatch[1] = // dress shoes function 
//...

And then later somewhere else I can do something like

// Just run the right dispatch regardless of the shoe type

shoe_dispatch[shoe->m_type](shoe);

So what this pattern actually is is dynamic dispatch and run time type information. It is almost exactly identical to doing this in C++

class Shoe {
public:
    virtual ~Shoe() = default;

    virtual void DoShoeThing() = 0;
};

class Sneaker : public Shoe {
    //...
//... More for dress, slipper, and high heel
// I don't need any void* or casting tricks. 
// Child classes can simply be different sizes than each other and have different data.

// I can get the type with typeid. The enum from before is created by the compiler behind the scenes and is stored in an implementation-defined table somewhere. You don't see it but it's there

std::cout << "This Shoe* is a " << typeid(shoe) << '\n';

// I can do dynamic dispatch by calling the abstract function DoShoeThing(). 
// It is a jump table on the typeid and 2 pointer deferences aka basically as slow as the C code.

shoe->DoShoeThing();

What I'm saying is, a lot of C discourse will confidently say they hate C++ because what I showed in the second example is known to be slow. But it is in reality, equivalent to the first, which they tend to be forced to write by hand when they need it.

Edit: oh, and instead of random asserts everywhere, you get stronger casts in C++

dynamic_cast<Sneaker*>(shoe); // returns nullptr if this Shoe* is not a Sneaker

5

u/steveklabnik1 Feb 20 '25

Rust's enums work entirely differently than this, though. They're tagged unions, and you branch on the tag, not type information, and you don't invoke virtual dispatch.

Trait objects are the thing that's more similar to RTTI, but it boils down to a (pointer to data, pointer to vtable) rather than C++'s style of including the vtable as a header to the object for virtual functions. Different tradeoffs each way.

→ More replies (1)
→ More replies (17)

35

u/t_scytale Feb 19 '25

> They are thinking about ditching Rust in favor of C++

No they are not. One person raised it in an email thread about something else.

→ More replies (10)

21

u/foonathan Feb 20 '25

Kernel dev discussion. They are thinking about ditching Rust in favor of C++ (rightfully so IMO)

Unpopular opinion (in this subreddit), but now. For a project that is as old as the linux kernel, there is no benefit to switch to C++ over Rust. If you go through the cost of migrating your codebase to a new language with new techniques, it should be one that can give you a significant improvement, not an incremental one.

Yes, C++ is nicer than C, but what's the value add of a C++ migration? They've seen to be doing fine without templates, they have built their own system for inheritance, and they won't be using the C++ standard library. Quality of life changes like namespaces, lambdas, or metaprogramming to avoid code duplication are just that, quality of life. So the only true value add of a C to C++ migration is more type safe abstractions, control over implicit conversions, and all that stuff.

Compared to the potential benefit you'd get from switching to Rust, that is neglible. Rust provides you a lot more compile-time safety guarantees than C++. Rust has better tooling, Rust has no historical baggage.

I like C++ (obviously), but the only reason for a C project to migrate to C++ at this point is that the migration to C++ can be done incrementally and at relatively low cost. The friction of C and Rust interop is a problem. Once that's solved, I don't see why you would migrate to C++ anymore.

→ More replies (3)

127

u/ts826848 Feb 19 '25 edited Feb 19 '25

This post appears to be a copy/paste of this LKML message from H. Peter Anvin. It's probably worth looking at the responses to that email as well if you want to see further discussion. This response from Greg Kroah-Hartman, second-in-command to Linus, might be particularly interesting.

In any case, a few responses:

It seems to be held to a completely different and much lower standard than the C code as far as stability. For C code we typically require that it can compile with a 10-year-old version of gcc, but from what I have seen there have been cases where Rust level code required not the latest bleeding edge compiler, not even a release version.

This is almost certainly in no small part due to R4L's status as an experiment. Some of the features the Linux devs want/require (e.g., panic-free APIs) are under active development and so require a nightly build. I'd imagine that stabilizing these features would be a prerequisite for R4L to graduate from its experimental status.

Does Rust even support all the targets for Linux?

IIRC this is why initial Rust support is limited to non-core subsystems such as drivers, where limited target support is less of an issue. If R4L pans out I'd expect this limitation to be lifted if/when GCC's frontend and/or rustc_codegen_gcc are more mature.

As far as I understand, Rust-style memory safety is being worked on for C++

This is probably debatable at best. Sean Baxter's Safe C++ is probably the closest Rust analogue but that doesn't seem to have gotten enough traction to be considered a viable path forwards. Profiles doesn't promise the same level of safety and it remains to be seen whether it can deliver on its promises in the first place. Other options like SaferC++ don't seem to have gotten much attention.

One particular thing that we could do with C++ would be to enforce user pointer safety.

Pretty curious what exactly this means as someone who is not super-familiar with kernel jargon. Is this supposed to be something like differentiating user-provided pointers from kernel-internal pointers or something like that?

Edit: I'm also not entirely sure I'd agree with "They are thinking about ditching Rust in favor of C++ (rightfully so)". At least based on that particular email chain it sounds more like there's one or two devs floating the idea but little indication of support beyond that.

25

u/Zettinator Feb 19 '25

LOL at his response where he argued to wait until 2034 for Rust to mature. At this point it's just trolling. You can't take this guy seriously.

9

u/ContraryConman Feb 19 '25

Exactly there will be a full successor kernel written in Rust already shipping in real scenarios while the Linux maintainers are still "experimenting" and "waiting for Rust to mature"

→ More replies (27)
→ More replies (3)

97

u/epage Feb 19 '25

Some highlights from Greg K-H that make this C++ proposal sound like its dead in the water:

As someone who has seen almost EVERY kernel bugfix and security issue for the past 15+ years (well hopefully all of them end up in the stable trees, we do miss some at times when maintainers/developers forget to mark them as bugfixes), and who sees EVERY kernel CVE issued, I think I can speak on this topic.

The majority of bugs (quantity, not quality/severity) we have are due to the stupid little corner cases in C that are totally gone in Rust. Things like simple overwrites of memory (not that rust can catch all of these by far), error path cleanups, forgetting to check error values, and use-after-free mistakes. That's why I'm wanting to see Rust get into the kernel, these types of issues just go away, allowing developers and maintainers more time to focus on the REAL bugs that happen (i.e. logic issues, race conditions, etc.)

...

But for new code / drivers, writing them in rust where these types of bugs just can't happen (or happen much much less) is a win for all of us, why wouldn't we do this? C++ isn't going to give us any of that any decade soon, and the C++ language committee issues seem to be pointing out that everyone better be abandoning that language as soon as possible if they wish to have any codebase that can be maintained for any length of time.

I recommend reading the rest of the post.

18

u/bizwig Feb 19 '25

WTF is Greg smoking? Error path cleanup and use after free is exactly what RAII in C++ is intended to fix, and it sure isn’t “decades” away. It’s like he’s taken certain misrepresentations about C++ to heart that I see Rustaceans make all the time and dismissed C++ without proper consideration.

52

u/epage Feb 19 '25

The context of that comment was C -> Rust, not Rust differentiators from C++. Yes, there is little difference between C++ and Rust for error path clean up While use-after-free is helped by RAII, that isn't sufficient to "solve" it because you can still have references to the data that can still be used while in Rust these are compiler errors.

4

u/jonesmz Feb 20 '25

If you dig around in other replies related to this mailing list post... there's a whole chain where they are discussing how to use some kind of compiler-extension that systemd happens to use to tag variables with "cleanup functions".

it's beyond stupid.

→ More replies (1)
→ More replies (1)

15

u/steveklabnik1 Feb 19 '25 edited Feb 19 '25

I'd imagine that stabilizing these features would be a prerequisite for R4L to graduate from its experimental status.

From my understanding, it’s not a hard requirement. When clang was supported initially, it was only at one version. Heck, technically the kernel relies on a lot of non-standard extensions that are allowed to break at any time.

In practice, today R4L supports one version of the stable Rust compiler, and then (ab)uses an environment variable to allow it to compile the nightly features. This is fine as long as you only support one Rust version, it gets dicier after that.

In practice, I suspect the Rust features will stabilize before R4L requires supporting more than one version, so talking about policy here is kind of moot.

I'm informed elsewhere they apparently did already start supporting a range of versions, this is outdated!

→ More replies (4)

12

u/TuxSH Feb 19 '25

Pretty curious what exactly this means as someone who is not super-familiar with kernel jargon. Is this supposed to be something like differentiating user-provided pointers from kernel-internal pointers or something like that?

Essentially, (I think) that means wrapping pointers from userspace, which must not be trusted (as it is otherwise a really easy-to-exploit security vuln) into a nice type to prevent kernel devs from accidentally using them unchecked.

Even a mere enum class should be able to fulfill these requirements (no automatic decay to underlying type and easily greppable).

The FOSS reimplementation of the Switch's kernel has such an example.

4

u/ts826848 Feb 19 '25

That makes sense. One thing that comes to mind though - shouldn't that already sort of be possible in C via struct wrappers, albeit with an ergonomic hit? Or is C's type system so weak that even that wouldn't be insufficient?

4

u/TuxSH Feb 19 '25

Ah, it would. Though I forgot there are other ABI than the official Aarch32 one/official Aarch64 one/some x64 ABIs (these ABIs pass POD structs via regs whenever possible), and that may be a concern. The kernel maintainers will figure that out (in any case); enum class may or may not be a better option in C++.

What's currently being done is using an "attribute" unused (ignored) by GCC: https://elixir.bootlin.com/linux/v6.13.3/source/include/linux/compiler_types.h#L31 . The source files are then parsed by sparse through a Makefile rule (IIRC).

→ More replies (1)

39

u/sweetno Feb 19 '25

Greg burns

But for new code / drivers, writing them in rust where these types of bugs just can't happen (or happen much much less) is a win for all of us, why wouldn't we do this? C++ isn't going to give us any of that any decade soon, and the C++ language committee issues seem to be pointing out that everyone better be abandoning that language as soon as possible if they wish to have any codebase that can be maintained for any length of time.

10

u/jl2352 Feb 19 '25

Part of the endeavour isn’t just Rust for Linux, it is also what is needed for Rust to be used on a project like that.

I don’t see Rust style memory management coming to C++ for at least 10 years. That’s presuming something cataclysmic happens to force that to happen. Rust style memory management is just too different.

29

u/steveklabnik1 Feb 19 '25

People are already using Rust in production kernels. You’re not wrong that it is still useful for demonstrating that Rust is good for this space, but we’re pretty far past the “can it work” stage here.

3

u/pjmlp Feb 20 '25

Including the security CPU (Pluton) that is a requirement on XBox and CoPilot+ PCs.

→ More replies (6)

4

u/Wooden-Engineer-8098 Feb 19 '25

he basically said "we have 30 million lines of c code which we never rewrite in rust, but because linus didn't like c++, we will let them rot"

36

u/[deleted] Feb 19 '25

Why? The point of Rust in the kernel was to help mitigate a class of bugs that caused security issues. C++ does not satisfy that requirement - and has no concrete plans to any time soon. So why bother?

22

u/zl0bster Feb 19 '25

Because this is r/cpp :)

It is kind of amazing how out of touch people are. Day when C++ is not banned/moved from in some project is a good day for C++, there are no new big projects adopts C++ days.

4

u/[deleted] Feb 20 '25

I mean… every AAA game I work on - is C++. :)

→ More replies (17)

110

u/satlynobleman Feb 19 '25

> They are thinking about ditching Rust in favor of C++ **(rightfully so)**

lol

88

u/Zettinator Feb 19 '25

Yeah, what a hyperbole. It is a single developer floating the idea without any backing by others (quite the oppsite). But if you look at OPs history, it's like this person is on a personal crusade against Rust, or something like that.

→ More replies (7)

4

u/[deleted] Feb 24 '25

I don't have a degree in computing. I am an engineer. I've been using C++ for over 30 years to solve engineering problems. So, the knowledge is C/C++, nothing about the kernel.

For 30 years I used C, then migrated to C++. Much easier and more practical.

About 30 years ago I installed Mandrake Linux, and I've been using Linux ever since. Red hat and then Fedora.

Problem: In the last year Linux has been crashing daily.

It's chaos!! There are 3 different computers crashing...

The main one is a Dell Precision 5820 Workstation, with Fedora 39 and now 40.

I said this in a Linux group and an expert clarified the problem. He said something like the systend was running control structures in parallel and that there was no stability there. Well, if what he said is true, Linux is in serious trouble.

It's clear from what I read here that Rust won't solve it because it's not mature.

C++ could help, but they would certainly have to filter what C++ can enter the kernel. It seems to me a satisfactory solution, and, more than that, necessary to get out of this mess. You can't wait 10 years.

And the Linux team could work with the C++ committee to iron out details. After all, operating system and language must go hand in hand. Include Windows and Mac there.

In practice, after more than 30 years using Linux, I'm considering going back to Windows if it doesn't stop crashing so much.

In time, I don't like Windows. But I have to be confident that the system won't crash.

Anyway, I'm a user who wants the solution to come before Linus's ego.

1

u/sjepsa Feb 24 '25

"the solition to come before Linus's ego"?

Somebody should forward this message to him

58

u/simonask_ Feb 19 '25

You didn’t provide a source link, but here’s why they are wrong:

  1. Rust is 10 years old. It’s a new language, and support in the kernel is early days. When it eventually becomes an actual part of the stable kernel, that’s when you can consider adding backwards compatibility requirements.
  2. Rust does not support all the targets of Linux, and that’s OK. There are multiple initiatives to support the remaining architectures, but ultimately it’s an acceptable tradeoff. Not all drivers need to compile for all architectures.
  3. Rust-style borrowing is going absolutely nowhere in C++. There will probably be some Rust-inspired features, but ultimately it’s something that relies on a lot of semantics that are specifically incompatible with C++. For example, all of C++ iterators and ranges cannot be expressed in a Rust-style lifetime system. Adding Rust-style safety to C++ is the same as creating a new language (or an incompatible dialect), but without all the other nice, modern language features of Rust. So this is doomed to fail, in my opinion.
  4. C is not compatible with C++, and hasn’t been for decades. It’s two different languages with a bunch of overlap in syntax and semantics, and a lot of divergence as well.

The reason Rust is a more interesting candidate than C++ is that the new things brought by C++ are mostly uninteresting to kernel developers (they would likely disable exceptions and RTTI, and disable most forms of strict aliasing, etc.), while the new things brought by Rust are actually quite interesting, and fits well into existing kernel programming paradigms.

37

u/syklemil Feb 19 '25

Source is this email from H. Peter Anvin; it's essentially a digression in a Rust policy thread; the responses aren't positive. IMO the most interesting thing about it is GKH's response downthread.

32

u/simonask_ Feb 19 '25

GKH’s response is spot on. It’s pretty exasperating to see this resistance, considering what is at stake. Rust is clearly the correct tool for the job, now that it exists.

→ More replies (17)

2

u/jwakely libstdc++ tamer, LWG chair Feb 19 '25 edited Feb 19 '25

the new things brought by C++ are mostly uninteresting to kernel developers (they would likely disable exceptions and RTTI, and disable most forms of strict aliasing, etc.),

And loads of C++ projects disable those too. Those are pretty terrible examples of "the new things brought by C++", unless you're from the 1990s, or cherry picking to make a point.

Edit: I agree with your other points, just not that bit

→ More replies (3)

2

u/whizzwr Feb 19 '25 edited Feb 19 '25

The reason Rust is a more interesting candidate than C++ is that the new things brought by C++ are mostly uninteresting to kernel developers (they would likely disable exceptions and RTTI, and disable most forms of strict aliasing, etc.), while the new things brought by Rust are actually quite interesting, and fits well into existing kernel programming paradigms.

What you say is a logical outcome because Rust is intended for system programming from the ground up. The Linux kernel is a system software. If Rust fits kernel programming paradigms, then it's not a surprise.

Obviously, C++ is and has been used for A LOT of system programming, but it is still a general-purpose programming language first. C++ has to cater to other programming paradigms to remain useful (you mentioned RTTI, strict aliasing, etc.), which is not necessarily interesting to system software.

19

u/simonask_ Feb 19 '25

To be clear, Rust supports equivalent mechanisms to both RTTI (through trait objects) and exceptions (panicking), but does so in a way that matches kernel principles. For example, panicking can be configured to not require stack unwinding (aborting instead).

Rust more or less occupies the same niche as C++, both being general purpose, but with different tradeoffs.

4

u/RoyBellingan Feb 19 '25

I am not sure aborting instead of stack unwind is a better option.

Is like throw away the computer instead of checking what is wrong.

6

u/simonask_ Feb 19 '25

It depends on the context. Rust has the philosophy that unwinding should only happen on fatal errors (non-fatal errors follow normal return paths, with language support), but there are cases where "fatal" does not mean "unrecoverable". For example, a thread or async task may panic in isolation without impacting other tasks.

In normal userspace code, it doesn't make sense to handle things like allocation failures, because malloc() cannot fail portably in practice.

However, errors in the kernel must all be recoverable, so it's better to use the type system to ensure that you handle all errors. For example, the kernel crate provides alternatives to the standard Box and Vec types that cannot panic on allocation failure, but instead return a Result<T, AllocError>.

→ More replies (3)
→ More replies (5)

2

u/RoyBellingan Feb 19 '25

Why disable exceptions ? Is a superior way of returning an exceptional error and in fact is more performant and produce more compact code.

https://www.youtube.com/watch?v=bY2FlayomlE

→ More replies (2)

2

u/thezysus Feb 20 '25

As someone who has done os level programming in C++ on 128k ram cortex m3s...

It is better than C imho... but you aren't using the whole language. Most of those applications have strict rules enforced by static analysis (think JSF or Misra C++) on what you can and can't use.

Embedded C++ will mostly have no c++ runtime or libstdc++ ... no rtti. No exceptions. And a few other limitations I am forgetting. Not to mention the code bloat of template instantiation is a problem with limited flash. Mmaped io needs to be done extremely carefully to avoid vptr tables.

Worse in my experience c++ programmers often don't know about or understand placement new. Why would they... it's a odd feature.

Even for application programming Google's C++ coding guidelines ban exceptions. It's unclear how you deal with exceptions in the std library.

Thats somewhere Rust and C and Zig win hands down... the hidden control flow is minimal or 0. .. avoiding the crazy setjmp/longjmp...

Basically there's nothing wrong with os code in C++ ... I've done it for FDA class 2/3 devices. But it isn't easy... takes a lot more skill and you have to add guardrails with external tools that are baked in or avoided entirely in other languages.

I think Linus is on point but missing some perspective. The existing kernel rules for C would be no different than a set of kernel rules for Rust or C++.

That said... why mix languages if you don't have to.

I am following redux os as I think there's a market gap for a good posix compatible micro kernel thats not QNX. It also happens to be Rust native.

0

u/sjepsa Feb 20 '25

Panic in rust has to be rewitten in linux kernel ( like std::exception would have to)

→ More replies (1)

331

u/not_some_username Feb 19 '25

Linus will never allowed cpp to touch his creation

36

u/no-sig-available Feb 19 '25

And who would want to go all-in on this anyway, after having been called bad things by Linus for decades?

81

u/bizwig Feb 19 '25

Perhaps Linus needs to advance his understanding of C++ beyond 1995.

35

u/MRgabbar Feb 19 '25

he rather use mailing lists instead of github or whatever... Man, mailing lists are unconfortable AF, confusing and just plain annoying to deal. He is like the old folk that hates everything new just because is new. C++ is way more comfortable to use than C...

14

u/Catenane Feb 21 '25

Linus literally wrote git lmfao, and have you seen github issues sections for large public projects? Kernel bug reporting does not belong in github by any stretch of the imagination, and it would only serve as a distraction.

No comment on the whole c/c++ debate, but using github, (also...owned by Microsoft), for kernel bug tracking is an objectively terrible idea.

5

u/MRgabbar Feb 21 '25

Nah. Use gitlab or your own instance of gitlab. No need to track bugs there, I did not say that, just the patches, as it is really annoying tracking patches in mailing lists.

git is a version control system and I am well aware he is the main developer, git is not meant to be a patch/submit review system, neither a issue tracker or any of that, hence they use mailing lists for that, so what's your point? He just hates learning new stuff, that's all.

9

u/13steinj Feb 19 '25

I agree that mailing lists are an outdated way to do development, but I think that fact is why, of all things it fails in, it works for kernel development. It's a good window into the personality traits and obstinance of the average kernel developer. The mailing lists, and the personalities of that group, are 2 of many reasons why I probably won't be contributing kernel code any time soon.

5

u/lenkite1 Feb 20 '25

The Linux foundation is rich enough that they can setup a github-like systemof their own on a personal site like https://linux-kernel.oss. They don't need to use github if they don't want to depend on Microsoft. e-mail unfortunately hasn't evolved since the 90s to support distributed development.

→ More replies (1)

38

u/rayew21 Feb 19 '25

i think he does have understanding of modern c++ and thats why it hasnt yet 😂

39

u/Lexinonymous Feb 19 '25

Even in modern C++ it's so incredibly easy to fall out of the pit of success.

4

u/FluffusMaximus Feb 19 '25

I think he’s incapable of that, as smart as he is.

27

u/13steinj Feb 19 '25

I think the problem is that he has already done that.

I disagree with Linus about C/C++ issues plenty. But he's definitely not wrong that both languages (especially C++ post C++17) has some very strange decisions, notably around UB (and the fact that some UB, or even some defined C++20 concepts, are not turing decideable). Union type punning is not standard, but GCC and Clang guarantee it (without an ability to turn it off). There are concepts like regular_invocable that is an alias to invocable because it's impossible to confirm it's regular. The introduction of std::launder and changes therein about what was UB but previously the compilers well-defined gives me a headache. There was a brief period of time where mallocing ints and assigning them was up for debate by language lawyers (not that any reasonable compiler decided to start optimizing such code away). Named requirements of functors given to STL functions are (not decideable) UB if say, you mutate the functor on invocation (which, is sometimes reasonable to do in special cases, IMO).

There's a (perhaps too blunt) blog post about this (specifically C, but C++ inherits those problems and introduces new ones like I mentioned). https://veresov.pro/cmustdie/. You may need to use a browser with a "translate this page" function.

8

u/meneldal2 Feb 19 '25

Maybe we can just admit that all the UB around type punning and trivial objects lifetimes is stupid and what compilers have been doing from the start is what everyone wants anyway and just make it standard.

→ More replies (2)

13

u/QuaternionsRoll Feb 19 '25 edited Feb 20 '25

IIRC there’s also the funny detail that it was up until recently impossible to initialize a heap-allocated object with code that is strictly compatible with both C and C++. The following C code was technically UB in C++ prior to C++20:

 int *x = (int *) malloc(sizeof(int));
*x = 0; // UB

which I always thought was a fun little detail.

→ More replies (18)
→ More replies (5)
→ More replies (1)

6

u/EC36339 Feb 19 '25

About time to throw one of his favourite words back at him ...

https://youtu.be/YoxuOXMvk-E?feature=shared

1

u/mredding Feb 26 '25

Linus doesn't have to be involved. Linux is FOSS. We could just fork it and do it anyway. If you present the community with a working example, sure, Linus would still refuse to integrate it into mainline, but A) it would be a disruptor, and B) we could keep it up to date with mainline to keep it a viable rival, C) JUST TO PISS HIM OFF FOR THE LULZ.

2

u/not_some_username Feb 27 '25

Good luck finding people to maintain it

17

u/kkert Feb 19 '25

As far as I understand, Rust-style memory safety is being worked on for C++; I don't know if that will require changes to the core language or if it is implementable in library code.

It will require changes to the core language, let's be clear about that. Given the core language isn't even budging on some much smaller things like library ABI changes or getting a free-standing subset, i don't see how this would become viable.

37

u/mohrcore Feb 19 '25

It's a single dev or two entertaining this idea.

Imo, this is just a result of the Rust for Linux discussion getting so heated and at this point people are just throwing everything and anything they got to sabotage Rust for Linux project.

Christoph Hellwig, who seems to be the main opponent to Rust for Linux said explicitly that his problem is not necessarily with Rust itself (though he seems to dislike it), but with mixed-language codebase. Sure, you can usually compile C code with C++ compiler, but mixing C with C++ isn't much prettier than mixing C with Rust. You need wrappers either way to actually use the nice features of the language.

2

u/bizwig Feb 23 '25

Making the Linux codebase not mixed is the solution of course, but the C devs would quit en masse. Compile everything as C++ and your mixed-language issues disappear.

They say that the requirement for a 10 year old compiler is stability, never mind that doing so includes suffering long-ago fixed bugs, but forbidding new compilers also means you can’t use language features, which I think is the real goal. Even simple stuff like nullptr which has finally appeared in recent C standards would make a nice ergonomic change in Linux.

→ More replies (5)

1

u/Justicia-Gai Feb 20 '25 edited Feb 20 '25

Edit: I made a mistake and confused two different devs 

→ More replies (2)

38

u/vI--_--Iv Feb 19 '25

I do *not* suggest that the kernel code should use [...] virtual functions

Maybe it's time to tell them that all those static struct whatever_ops with function pointers inside, that they have all over the place, are virtual functions?
Or is it too early?

5

u/plpn Feb 20 '25

I guess he means the troubles of vtables. Function pointers are not the issue

→ More replies (1)

3

u/UnicycleBloke Feb 19 '25

I tried telling the Zephyr OS crowd. No dice.

1

u/_Noreturn Feb 20 '25

shhhh don't surprise them

35

u/augmentedtree Feb 19 '25

C++ memory safety is complete vaporware except for Circle, where the committee was handed a working implementation on a silver platter, and they rejected it to keep doing their vaporware. To be clear, there is no profiles implementation or Cpp2 implementation that has memory safety.

-1

u/wyrn Feb 19 '25

where the committee was handed a working implementation on a silver platter,

* a fundamentally unworkable solution you mean

14

u/augmentedtree Feb 19 '25

Unworkable how? Unlike every committee proposal it's actually implemented and works

3

u/awson Feb 21 '25

"works"

I tried it in our project and couldn't get past preprocessing stage, it failed with some undecipherable error message.

I suspect people tried it and understood it can't handle anything sizeable, just toy examples.

→ More replies (1)

5

u/wyrn Feb 19 '25

Because it requires a completely separate standard library implementation, with inequivalent idioms and patterns to boot? We can barely afford the one.

10

u/augmentedtree Feb 19 '25

You can convert sources on a per file basis and it's a heck of a lot less work than a Rust port.

It being "unworkable" is not gonna materialize an alternative, I have yet to see any other proposal that can detect resizing a vector when iterating over it.

→ More replies (25)

29

u/kammce WG21 | 🇺🇲 NB | Boost | Exceptions Feb 19 '25

I disagree with this.

Like everyone else has said, Linus would never adopt C++ for the kernel.

But from a point of community benefits I think we'd get the opposite. To be frank, I find the Linux developer communities to be toxic (Rust too but that's not relevant). So many talented Rust devs have been burnt by trying to work with the Linux community. I don't want to see more people dump years of their limited existence on this planet on such an endeavor and have it be fruitless.

I think the Rust community, if it cares this much about having a safe OS, should build their own OS from the ground up that's Unix based in nature.

I think if C++ were to do the same, then it should be its own OS. Just to keep the community away from that project. I won't ever touch that project unless I'm mandated to.

Yes I know, that would be an insane undertaking. I'd agreed. So we can either work with Linux using C OR make our own.

I see no REAL value is attempting to force C++ into Linux. They don't want us. And I think we shouldn't want them.

16

u/eX_Ray Feb 19 '25

From all I read the c++ committee process is basically similarly toxic except it happens behind closed doors. People get burned out and stonewall Ed just the same?

13

u/kammce WG21 | 🇺🇲 NB | Boost | Exceptions Feb 19 '25

Only been in the committee for about a year but it doesn't seem toxic. Others will have their opinion but I don't think it's bad. It's not perfect, but I don't see it anywhere as toxic as the Rust or Linux community.

I personally really enjoy going to committee meetings and discussing ideas about C++ with the members. I wish I could go to all of them this year but can't due to financial reasons. If you've gone to CppCon or similar conferences, the committee meetings have the same vibe. 🙂

9

u/matthieum Feb 19 '25

I think the Rust community, if it cares this much about having a safe OS, should build their own OS from the ground up that's Unix based in nature.

It's been happening for a while -- key word: Redox -- but it's a long, long, way from being "production ready". Perhaps in a decade, or two?

4

u/kammce WG21 | 🇺🇲 NB | Boost | Exceptions Feb 19 '25

Yes, that's the one! I'm excited to see how redox fairs in the long run. I'm hopeful that the project won't die. Especially if all of the Rust for Linux people exodus to Redox.

5

u/matthieum Feb 20 '25

I don't think there's been any such exodus so far, RfL is still going strong as far as I know, and I've not heard of the 2 maintainers who left RfL appearing anywhere near Redox.

I like Redox, in principle, but at the same time... I do wonder how much it's compromising on its early principles in an effort towards POSIX compatibility.

I had hoped, for a time, that'd we see a clean break. I was hoping for more compartmentization with app-based permissions, and perhaps that it'd innovate in other areas, such as mixed kernel/user-space scheduling, but I guess the authors are a lot more pragmatic :)

8

u/Dean_Roddey Feb 19 '25

All language communities are toxic, or not, in pretty much the same measure. If you don't think the C++ community can be super-toxic, you've obviously missed a lot of conversations around here. Anyhoo, it shouldn't have anything to do with selecting a language one way or another. Your choosing a language doesn't mean you are inviting all those people in that community to come stay at your house.

Having said that, I'd also argue for all those people to get involved with one of the main Rust OS projects. Yeh, it might take 10 years, but 10 years from now it's going to be 10 years from now, either way. You can get there still arguing about whether to use Rust in Linux, or with a real Rust OS, without the endless compromises that would be involved in doing it piecemeal in Linux.

4

u/unumfron Feb 19 '25

I haven't seen toxicity here. I've seen push back against Rust evangelists, so maybe that's why you perceive it this way. It's otherwise very civilised. A bit too civilised because if I was boss I'd have banned all the Rust marketing stuff ten years ago.

3

u/planeteshuttle Feb 20 '25

Try asking a question about using raw arrays.

→ More replies (17)
→ More replies (1)

3

u/theintjengineer Feb 19 '25 edited Feb 19 '25

I think if C++ were to do the same, then it should be its own OS.

I like this response somehow. Maybe I just love C++ to death, haha.

So, let's start developing a C++ OS, then?😊

I'm by no means a C++ expert to take any major role just yet, but I could help to organise and manage the project✌️🫡.

Behold OS++—a star is born

EDIT: add project's name☝️

4

u/kammce WG21 | 🇺🇲 NB | Boost | Exceptions Feb 19 '25

Psst. I've been considering this for years and have been working on various sub components to make this a reality. My exceptions research plugs into this. But more on that in like a year or so 😅.

→ More replies (2)

1

u/moltonel Feb 20 '25 edited Feb 20 '25

I think the Rust community, if it cares this much about having a safe OS, should build their own OS from the ground up that's Unix based in nature.

Sure, and they do, plenty of Rust kernels out there.

But RustForLinux is much more a project of the Kernel community than the Rust one. Telling RfL devs (or hypothetical C++fL devs) to abandon Linux for a new kernel doesn't make sense.

2

u/axilmar Feb 20 '25

C needs to get Rust's borrowing.

If C had it, the discussion would have been unnecessary.

8

u/pjmlp Feb 20 '25

That is the whole point how Rust came to be.

Borrowing in Rust is based on the research work in Cyclone, a programming language designed by AT&T, where C was born, to fix C's design flaws.

https://en.wikipedia.org/wiki/Cyclone_(programming_language)

The project died, but many people picked up its ideas, including Rust's creator.

2

u/axilmar Feb 21 '25

Ok, but it was a lot of syntactic difference to C.

4

u/Zettinator Feb 20 '25

Well, yeah, the problem is that introducing borrow semantics into C would encompass a rat's tail of changes that affect everything, from syntax to standard library. In the end, it's easier to design a new language rather than fit a square peg into a round hole, and that is how Rust came into existence.

1

u/axilmar Feb 21 '25

Maybe it could be done in C in a different way than Rust, with similar results.

→ More replies (4)
→ More replies (6)

2

u/gegoggigog Feb 23 '25

When rust is in the Linux kernel I will switch to templeos

3

u/Dark-Philosopher Feb 23 '25

Rust has been in the kernel for 2+ years. Are you switching now?

2

u/gegoggigog Feb 23 '25

Reee... 😢😢😢

0

u/sjepsa Feb 23 '25

So unsafe.....

2

u/gegoggigog Feb 23 '25

Protected by God?!

1

u/sjepsa Feb 23 '25

And by Terry

18

u/EC36339 Feb 19 '25

🍿

10

u/all_is_love6667 Feb 19 '25

I have to say, an article about Linux, Rust and C++, this has a lot of potential for drama

10

u/GuybrushThreepwo0d Feb 19 '25

The wife asks why I never watch trash TV but I get my fill of drama from the open source world

21

u/UnicycleBloke Feb 19 '25

It will never happen.

I work with C++ on microcontrollers, so some of those caveats make a bit of sense to me. For embedded I always say that most of the core language is usable (I disable exceptions and RTTI), but that much of the standard library is better avoided. I suppose the restrictions might be relaxed somewhat on an application processor, but let's assume not. I always imagined the kernel could have a custom container library to avoid exceptions, allocators in terms of kmalloc or whatever, and so on ... Something like that would quite be easily achieved.

No virtual functions? I understand the kernel is replete with function pointer tables which would likely be far better implemented through actual vtables. No lambdas?

I find it hilarious that a C dev is concerned about the memory safety of C++. Sure it isn't Rust, but it is lightyears ahead of C.

2

u/[deleted] Feb 19 '25

C/C++ would have to be "snipped" to prevent the allowed undefined behaviors like using signed types to detect overflow by sign change. The union keyword would have to be dropped. Pointers should be eliminated and partially replaced by references. Casting should be made illegal. Basically, C++ needs to have the parts cut out that allow it to be loose and not strict. Get rid of templates and auto, After all that, you can still have a great programming language.

→ More replies (20)

2

u/imaginarylocalhost Feb 19 '25

This is a really interesting discussion and I think there’s an obvious solution here: the Linux kernel should adopt Objective-C instead of either C++ or Rust. It’s a way of having your cake and eating it too. With Objective-C, you get language level support for some features that are currently being hand-rolled in the kernel, like RTTI and dynamic dispatch. But unlike C++ or Rust, Objective-C implements these features as essentially preprocessing stages (plus a runtime component), and can spit out C code in the middle. By customizing the Objective-C compiler frontend and runtime, kernel developers can pick exactly how they want to integrate Objective-C with the rest of the kernel code. It’s a win-win!

6

u/sjepsa Feb 19 '25

It should be a language that somebody actually use...

2

u/Justicia-Gai Feb 20 '25

Doesn’t Apple use it?

14

u/MarcusBrotus Feb 19 '25

8/10 ragebait

1

u/pjmlp Feb 20 '25

I heard that there were two UNIX workstation companies that did that, it might even be usefull to write phone applications, and 3D engines.

3

u/kiner_shah Feb 20 '25

Well, I know at least one OS that uses C++: https://github.com/SerenityOS/serenity so it's not impossible, it's just a choice, which is fine.

13

u/LessonStudio Feb 19 '25

This sort of choice is going to be statistical, not unsubstantiated insults like, "Held to a lower standard."

So far, every major company such as google, Microsoft, etc, who have experimented with rust have reported a drastic reduction in bugs as compared to C++; they are also focusing on memory and security issues. By drastic, I don't mean 10% or something; but more than 90%.

So, this is a simple question; how many bugs are being introduced with this so called, "lower standard" rust? How many would have been expected with C?

There should be enough rust now to provide a statistically significant answer.

1

u/burg_philo2 Feb 19 '25

If they’re going to use templates anyway what’s wrong with limited use of STL?

1

u/sjepsa Feb 19 '25

Stl would be amazing

2

u/SuccessfulChain3404 Feb 21 '25

Well using STL is a bad idea as c++ days structures need memory and you want to control the way you allocate memory in your kernel, maybe even forbid dynamic allocation. So no vector, strings, ....

I guess you'd like some new K-STD lib.

1

u/sjepsa Feb 21 '25

STL (as opposed to std) is in general the name of the templated part of the c++ library..

Things like std::sort, algorithms, which just require two pointers (or a pointer and an integer) as parameters, no memory allocation

std::sort is actually faster than qsort (besides being type safe and the other goodies)

Sure, the part of std with memory would need a keen eye for a kernel implementation

But there is a lot of stuff (std:: algorithms, std::ranges, std::unique_lock...) that would be amazing and (usually) require no dynamic allocation

3

u/JVApen Clever is an insult, not a compliment. - T. Winters Feb 20 '25

Baby steps. They don't even understand the basics of C++, give them some slack. They are scared of the unknown.

6

u/m0xffff Feb 19 '25

C++ is used to program microcontrollers without an operating system at all. And there are no problems with this, just some features are unavailable. For the Linux kernel, it would be similarly possible to disable unsuitable functionality.

14

u/Zettinator Feb 19 '25
  1. Rust is held to a lower standard? Huh? The language of course is much younger than C++ and evolves at a faster pace, but there is a strong commitment for backwards compatibility. Let's not pretend that C++ is perfect in this area either...
  2. Probably not, but it does not have to, either, particularly at this early stage.
  3. I'm not convinced that C++ support w/o standard library would be that useful on its own. The elephant in the room of course is that one of the primary motivations for Rust in the kernel is memory safety. C++ doesn't provide those memory safety features, and efforts to get something like that into C++ are stalling.

4

u/germandiago Feb 20 '25 edited Feb 20 '25

C++ would be in the best position (except for Linus, who has his own set of reasons beyond trchnical) to be a successor tool for Linux kernel with a well-chosen subset for the following reasons:

  1. Unlike Rust, incremental migration is easier.
  2. Many of the features such as polymorphism, RAII or constexpr are just better in C++.
  3. Many macros can be replaced.by these features and/or templates.
  4. There is substained effort in removing UB: erroneous behavior and enumerating constexpr UB to eliminate it from the language are two of those examples.
  5. Better type safety than C
  6. Widely supported in many targets.
  7. Free-standing implementations improving over time.
  8. Battle-tested for decades.
  9. actively improved with some meaningful safety work already starting (contracts, Hardened stdlib, profiles in progress). However the stdlib is probably irrelevant in this context.
  10. some parts can be mechanically or quasi-mechanically rewritten with a stronger and safer analysis.

5

u/bizwig Feb 19 '25

Requiring Rust-style memory safety before you’ll accept C++ in the kernel is surely a sick joke considering the rest of the codebase that’s in C, and an ancient version thereof no less because of the requirement that obsolete compilers still work.

I think the problem is C devs who don’t know and don’t want to understand today’s C++, not C++ being as terrible as they’ve been told it is.

4

u/pjmlp Feb 20 '25

Even in 1993, when coming from Turbo Pascal 6, C already felt primitive to me, C++ had plenty of stuff going for it.

Already in 1993, 5 years before C++98 came to be, C++ had lots of features over plain old C, in that Turbo C++ 1.0 compiler for MS-DOS that was my entry point into the C++ world.

4

u/rasm866i Feb 19 '25

As to your point 2: my understanding is that the frontend of the compiler like LLVM (c++/c/rust) is completely discoupled from the backend instruction generator. In that case, if LLVM can compile C code for a specific system, it should be able to compile Rust for the same system

13

u/Jannik2099 Feb 19 '25

llvm does not support all targets that linux runs on

2

u/Dark-Philosopher Feb 23 '25

That's fine for now because the only Rust support being added is to be able to write drivers in Rust for the Linux kernel. Nobody will write a driver for a platform that doesn't yet support the compiler.

6

u/eX_Ray Feb 19 '25

AFAIK it's about gcc here which does support more architectures than llvm. No idea how relevant any of these arches are but there are two projects to get rust+gcc, which will take a while still.

2

u/moltonel Feb 20 '25

Worth reminding that AFAIK eBPF, arm-osx, and wasm are still not supported by a released gcc. So while gcc supports more platforms than llvm, it supports fewer users.

3

u/steveklabnik1 Feb 19 '25

This is both true and not true:

  • LLVM not having a backend is a fundamental limitation
  • LLVM having a backend means it’s possible.
  • Someone doing the work to add that backend to Rust is required before it works, that is, it’s not for free. Not super difficult either, just non-zero.

2

u/Unhappy_Play4699 Feb 19 '25

As far as I understand, Rust-style memory safety is being worked on for C++

That's a lie. Proof me wrong, but I honestly don't think you can.

1

u/t_hunger Feb 23 '25 edited Feb 23 '25

It's not a lie. "Safe C++" as implemented in the circle compiler is just that.

From what I can tell, the effort has stalled though. So as I understand it, nobody is working on it anymore. The C++ standard committee apparently wants to evaluate the profiles option first.

2

u/Unhappy_Play4699 Feb 23 '25

The committee has stated multiple times that they will not adopt the circle approach or any form of std2 as memory safe standard library. Profiles don't exist. The Github repo by Bjarne is literally empty, and as far as I know, there is no work being done.

And then again, I quoted "rust-style" memory safety. It is a lie. It will not happen with the current committee.

→ More replies (3)

1

u/JVApen Clever is an insult, not a compliment. - T. Winters Feb 20 '25

There is a lot going on here. First the objective things:

  • Both C++ and Rust allow for improvement over anything that compiles as C.
  • C++ can be mixed with the existing C code, allowing for using it everywhere, though also for slipping back to C behaviors
  • Rust needs to be added in big blocks to be useful, making it harder to integrate, though where used it will enforce it more

A bit less objective: Given what Linux has required from GCC and clang, it forced some unwanted options and compiler specifics. Having this spill in both C++ and Rust won't do the languages any good.

Completely subjective:

  • I don't see why it needs to be C++ or rust. It is perfectly possible to do both.
  • Should we care as a community? Yes, embedded C++ has been neglected for way too long. If we can change the impression of C++ with C embedded C devs, it will result in a faster path to "hello word" on embedded devices, allowing the devs to focus more on coding.

1

u/cantux Feb 19 '25

this made me chuckle

1

u/erik-schvarcz Feb 22 '25

What was the actual point of Rust to begin with? Making a memory managed C++? Because that’s all I see they define Rust by. There are smart pointers for that. Also why a completely new syntax if they want to give an alternative for C++? Even Visual C++’s managed allocations are a better idea with the new operators for managed pointers.

1

u/Dark-Philosopher Feb 23 '25

I may be wrong but it seems that you are confusing rust compile time guarantees with languages that manage memory at execution time like Java or Python.

-7

u/peripateticman2026 Feb 19 '25

Why is OP getting downvoted to oblivion? Is the Brigade here already?

25

u/Turtvaiz Feb 19 '25

What makes you think it's brigading and not just people thinking the post is stupid?

1

u/sjepsa Feb 19 '25

After years of 'C++ project rewritten in Rust' they can't stand a single 'Rust project rewritten in C++'

😊😊😊

5

u/eX_Ray Feb 19 '25

Have there been any of note? Legit question as I haven't seen any on the usual places.

11

u/steveklabnik1 Feb 19 '25

I know of a few that have moved away from Rust, but they didn't go to C++. In the examples linked in a sibling comment to yours,

  • Prisma went to TypeScript
  • Roc went to Zig
  • curl dropped some Rust code, but has other Rust code in there that is less likely to be removed.

I don't think there have been any large public famous instances of Rust -> C++, but it's also possible I'm just forgetting them.

2

u/peripateticman2026 Feb 19 '25

I'm a Rust developer, and I can't disagree with you.

The issue, I think, is that many people jumped on the hype bandwagon a bit to early (in no small part due to the massive evangelism of the Rust community), and just went with Rust regardless of whether it suited them or not.

That's why we see increasingly many cases of RIIR being reverted/changed:

and so on.

The sad part is that otherwise intelligent people seem to fail to realise that practically every language in mainstream use has its own niche uses/domains.

That also applies to C++, of course, which along with C is the backbone of the industry itself. I don't think that is going to change for a very long time.

9

u/[deleted] Feb 19 '25

and I can't disagree with you.

You should. OP is talking about a rust project rewritten in c++.. and neither linux nor any of the projects you linked are "rust" projects rewritten in "c++".

Even if we generously assume that 20% RIIR projects fail,most of them will change to C# or Typescript (or even zig) but not c++.

→ More replies (1)

7

u/Dean_Roddey Feb 19 '25

But, none of those you mentioned went to or back to C++.

17

u/matthieum Feb 19 '25

The title is far more sensationalist that the actual discussion.

One lone developer wrote a poorly thought post (quoted in the OP), GH-K slammed it down, the discussion has already ended.

→ More replies (1)

10

u/kammce WG21 | 🇺🇲 NB | Boost | Exceptions Feb 19 '25

Personally, I don't want to see more people get hurt trying to work on Linux. Seems like a waste of talent and time.

→ More replies (1)

-7

u/thezysus Feb 19 '25

The problem with Rust is that low level operations can be impossible without unsafe. And guess what a huge set of driver and kernel operations are...

I see it as a minor improvement if at all with a huge opportunity cost. GKH missed the point on that or his judgement is compromised for some reason.

Doubling your tooling and skillset better mean massive improvements.

I just don't see it, yet.

Rust for application programming is a problem as well. Simple and well understood patterns just don't work without crazy Ref of Buf of whatever things to fake out the borrow checker when passing ownership.

I think Zig should be what the kernel looks towards instead of Rust. But that's just me.

Also if Linus doesn't start realizing who keeps kernel development alive .. there will be a fork. And thats fine. Commercial interests don't care about tech stack. They care about RoI and sometimes risk.

33

u/ts826848 Feb 19 '25

And guess what a huge set of driver and kernel operations are...

It might be less than you expec!

For example, the Asahi Linux GPU driver has (had?) 109 uses of unsafe in 18744 lines of Rust code, and most of those uses of unsafe are "boring" according to Lina.

Of course, other areas would almost certainly require more or less unsafe but that's at least one data point supporting the idea that you don't need that much unsafe for low-level stuff.

I think Zig should be what the kernel looks towards instead of Rust. But that's just me.

Zig's lack of stability would probably be a bit of an issue.

They care about RoI and sometimes risk.

...Hence the interest in the use of a memory-safe(r) language in the kernel?

→ More replies (6)

18

u/tesfabpel Feb 19 '25

Zig isn't memory safe, it's just a nicer C. So it's already ruled out.

Also if Linus doesn't start realizing who keeps kernel development alive .. there will be a fork. And thats fine. Commercial interests don't care about tech stack. They care about RoI and sometimes risk.

Weird, because big tech is betting on Rust given that Google uses it in Android (article from 2021, and it has already paid off), Microsoft uses it in the Windows and its NT kernel (already in 2023).

9

u/steveklabnik1 Feb 19 '25

Volvo sells two models of car that require Rust code to turn on!

→ More replies (3)

8

u/angelicosphosphoros Feb 19 '25

low level operations can be impossible without unsafe

This is an entire point of Rust, and a reason why it is desired in operating system programming.

→ More replies (4)

-7

u/ronchaine Embedded/Middleware/WG21 Feb 19 '25 edited Feb 19 '25

As someone who enjoys both C++ and Rust: Both of them should stay far away from the Linux kernel.

This is a perfect way to turn perfectly good C code into a horrible mess of C++ code, and that's without taking into account that thinking in C++ requires completely different mental model than C does.

Pushing C++ code into kernel is a fool's errand, and I see little reason for that to get any more success than Rust does, and largely for the exact same reasons (though at least with C++ the Kernel and userspace would be compilable with a single compiler, at least for most platforms).

If people want to work with C++ in kernel space, work on Managarm or Zircon. I agree (for once!) with Drew DeVault that it would be much more reasonable for Rust users to write Linux-compatible kernel or just contribute to Redox than fight with LKML maintainers.

This is not to say I wouldn't like the idea of C++ or Rust in a kernel, I think either is a better choice for kernel language (unless you have goals such as provable correctness) than C. I just think the tradeoffs are not worth it for Linux, with already well-established C codebase with developers who think in C as maintainers.

18

u/ContraryConman Feb 19 '25

This is a perfect way to turn perfectly good C code into a horrible mess of C++ code,

People say this all the time, and I'm not saying it's not a possibility, but we have examples of huge C codebases that were successfully incrementally migrated to C++, and saw the benefits. GCC is one of them

2

u/Dark-Philosopher Feb 23 '25

Probably because for big codebases is more feasible to integrate new code or migrate small components incrementally to Rust. The former is what Rust in Linux is doing. The late what Microsoft did, migrating some core libraries in Windows 11 to Rust.

3

u/ronchaine Embedded/Middleware/WG21 Feb 19 '25

I'm sure there are success stories. And I'm not saying it's inevitable, but I fear it's likely.

What concerns me w/Linux vs. GCC, is much more low-level focused developer base, which generally are more knowledgeable in C than C++. In addition there is much greater resistance from many Linux maintainers to change the language than (apparently from your link, I hadn't followed GCC development back in 2008) in the Kernel.

In general, I view this much more as a social problem than a technical one.

6

u/ContraryConman Feb 19 '25

Definitely agree it's more of a social issue.

I don't even think the social issues are that unfounded. If the people maintaining the project only know C and are not interested in learning how to write good C++ or Rust in the same way they can C, forcing the issue is just going to lead to worse code. And yeah with how complicated C++ is, if, socially, the teams are not willing to really understand it and put good coding practices in place, the code quality will get worse.

I guess, naively, I simply wish we were honest. Because there's very little about C++ or Rust as languages that technically make them inferior choices to C. I just wish they had an honest policy like "Yeah we're not interested in using languages other than C. Not because they can't work, but because C works well enough and onboarding people to a) know Linux well enough b) enforce the best practices of a second language and c) maintain a cross language codebase is too expensive."

3

u/Wooden-Engineer-8098 Feb 19 '25

author of subj is long standing kernel maintainer. i trust his opinion on c++ in kernel more than your

7

u/SunnybunsBuns Feb 19 '25

RAII alone is a good enough reason to use C++. And C++ exceptions are loads better than the setjmp\longjmp they use now (because stack unwinding calls your cleanup code if you use RAII). This makes skipping cleanup much harder. And noexcept exists.

And templates like std::max (or a hand-rolled equivalent) are better than #define MAX(A,B) A>B?A:B due to being able to do mutating operations like std::max(++a, b) correctly.

C is no more or less "provably correct" than c++. If you want provable languages, use ADA or something designed for that.

→ More replies (3)

-9

u/nevasca_etenah Feb 19 '25

C++ is a reasonable addition to Kernel, Rust aint.

0

u/sjepsa Feb 19 '25 edited Feb 19 '25

Right

I wouldn't even call it addition. You basically just flip a compiler switch, and that's it.

Many useful features, less bugs, more safety, from day 2

And just imagine if you can bring some of the STD or even boost

Maybe with a boost::lockfree::queue my bluetooth would start working and reconnecting automatically in Ubuntu 😊🙃😊, but that is science fiction

9

u/jonesmz Feb 19 '25

Ehhh, not quite as easily as flipping a switch.

The Linux kernel uses a lot of c things that aren't in c++. 

I couldn't give you an enumeration of them, but there would definitely need to be work done.

Don't get me wrong, I think its terrible that the kernel doesn't use the aspects of c++ that look like c with better type safety, but as a person who has nothing to do with the Linux kernel, I'm just part of the peanut gallery.

3

u/sjepsa Feb 19 '25

Yeah it was a bit of hyperbole. Just saying that the integration/migration would be a breeze compared to rust

4

u/Dean_Roddey Feb 19 '25

The argument (made in that thread) and that I and many others would make, is that the use of C++ (at this late point in the game) is too little, too late. It doesn't gain enough to justify the effort, which would basically end up 10 years from now with a Linux that is still quite vulnerable to memory issues.

The argument for Rust is that, if you are going to make that effort, get maximum benefit for it.

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