С++ in kernel

The Linux kernel is entirely in C with a smattering of assembler. There is no C++ at all, not for any technical reason, but because Linus Torvalds is personally allergic to C++. It is a particularly idiomatic C, nearly free of comments, and they use macros to simulate the kinds of data structures that are easy in C++.

@Tim_Roberts said:
The Linux kernel is entirely in C with a smattering of assembler. There is no C++ at all, not for any technical reason, but because Linus Torvalds is personally allergic to C++. It is a particularly idiomatic C, nearly free of comments, and they use macros to simulate the kinds of data structures that are easy in C++.

I am not a linux dev myself, but my colleague told me that one of the reasons why Linux Kernel is C only is that some platforms simply don’t have c++ compiler implemented for them (I think he was speaking about embedded systems)

The Linux kernel is tightly bound to gcc. Once there is a port to a processor, that means you automatically get C and C++ (and Fortran and Pascal, for that matter).

@Tim_Roberts said:
The Linux kernel is tightly bound to gcc. Once there is a port to a processor, that means you automatically get C and C++ (and Fortran and Pascal, for that matter).

Does It mean that I can actually write drivers for linux in c++ as long as I don’t care about integrating my driver in official kernel sources ?

Does It mean that I can actually write drivers for linux in c++

It’s been done. Google is your friend.

Peter

@Tim_Roberts said:
… but because Linus Torvalds is personally allergic to C++.

To C++ in its state when Linux was founded. That’s C++ 98 or older, and it was then not a clear winner over C (with extra tools).

and they use macros to simulate the kinds of data structures that are easy in C++.
But the C++ data structures are in its standard library, and this library is written in assembly or C.
This library is part of the kernel, it needs to be build for kernel environment, reviewed and maintained.
There’s no miracles. It is made of extra memory and CPU cycles. Every time one uses a C++ thing in kernel, they cannot avoid thinking: will it do a trick under the covers: allocate something? execute something? could it be easier and safer to just use plain C with macros?

By contrast, structures in python or js are magical, one can use them without importing anything and even knowing what’s the name of or {}.
Of course this magic is expensive and doesn’t fit in the kernel. But every time I write something in python - after years of C - I smile (and thank you, Mr, Roberts again for hinting me to learn python!)

– pa

Does It mean that I can actually write drivers for linux in c++ as long as I don’t care about integrating my driver in official kernel sources ?

Well, technically there is nothing that stands in your way, although you have to take care of quite a few issues. To begin with, you have to implement your own versions of new() and delete() operators . Furthermore, making C++ work with Linux kernel headers does not really seem to be the easiest job in existence, so that you will probably have to provide your own wrappers for the kernel functions that you call. You must always keep in mind that there is no C++ runtime in the Linux kernel so that you have to avoid certain C++ language features( like , for example, exceptions),et,etc, etc…

When it comes to deciding upon the practical usefulness of this approach…well, this is already a different story that happens to be well beyond the scope of this discussion

Anton Bassov

What you’re describing is no different from the situation in Windows.

> @“Peter_Viscarola_(OSR)” said: > (Quote) > It’s been done. Google is your friend. > > Peter I asked this question exactly because I used google to figure out Linux kernel + c++ viability. And my impression was that you will have to fight really hard with build system to make it work. However mr Robert’s message sounded to me like you basically need just write c++ code in cpp files - pretty much the same way as I do in drivers for windows. Maybe I just misunderstood.

no different from the situation in Windows

Except (of course) you’ll have no problem with checking something in to Windows that’s written in C++, even into MinKernel.

ETA:

making C++ work with Linux kernel headers does not really seem to be the easiest job

And, of course, the Windows kernel headers have long been C++ compatible.

Peter

In the past I’ve seen C++ code (file filter drivers ), with OO (
class etc). Quite hard to debug, at least for me, when the designers
failed to understand what is/are going on …

Then move on to BSD, then Apple mach based kernel —, almost all is C
code ( except some asm )… Get open source, map correctly ( or almost
), debug thru kernel ( not what I want to do or enjoy ) but debugging
is bit easier, well just the debugger infrastructure is not as solid
as Windbg…

Given that, I always ask one question to any senior new hire — What
is the best code ? I would not answer the question, just in case …
And if I see a simple reasonable answer with some pseudo-codes that
guy is hired, period…

The trend I see, is that lately more candidates learn C++ ( Google ,
FB, Amazon etc., wants C++), so it is natural people want to use that
knowledge in kernel mode…

Now, what is the year when Linux got started ( i.e. porting Xinu or
something after wholesale changes )??? Perhaps early 90s in the lab,
then around 94 or 96 it is out there !!!.. By then lot of people
using C++/ Java is or already coming … So why Linus did not conform
to it… Whatever …

I hear people love to code in Swift/Obj-C/C++, so outside kernel
modules I create interfaces ( like in low level daemons / services )
and open up the bridges, so one can use swift or anything else. Inside
kernel, I use C ( and some asm for tickery).

I see some benefits of using C++, other than that I would suggest (
just like Dejon ) look at the archive, see the concerns, and come up
with solutions ( if you can ) — and enlighten us.

-Pro

OK. Let’s be clear: Coding in C++ these days can mean many things. This is particularly true when we’re talking about coding to Windows kernel-mode C Language interfaces, and under the constraints imposed by the Windows OS environment.

I see primarily three different “levels” of approaches to using C++ in Windows driver development:

  1. C++ as a Better C: In this approach, one typically uses C Language conventions, but with the addition of specific Modern C++ features. This also typically means directly using the OS-supplied C Language interfaces. Most devs who program in C would be happy with the code, and they’d see very few differences. You might see the occasional RAII pattern here, but only rarely (where you can really benefit from some complex custom destructor, for example). This is typically the approach we use in kernel-mode code for Windows at OSR. There’ll be an article in the next issue of The NT Insider about this.

  2. C++ Wrappers: This approach expands the approach above with the addition of C++ classes/wrappers to do a lot of the driver’s work and around some of the more common C Language OS interfaces. This approach is typically where devs bite-off overriding “new” and “delete.” The approach makes the use of RAII patterns for common OS interface tasks like acquiring and automatically releasing locks. This can be done well, but it needs to be done with a lot of restraint. In my experience, it’s quite easy for devs using this approach to “slip into darkness” and accidentally create an impenetrable mess that fall into category 3 below.

  3. Full-On OO C++: This approach is what I think most C Language folks envision when they think of “drivers in C++” … and it makes them shudder. I don’t commonly see this approach anymore, except from folks who are on dev teams where OO is a way of life and they really hate thinking in C Language interface terms. Having seen, and tried to understand and debug, fully class-based, object oriented approaches to writing Windows drivers I can personally attest to how very painful this can be.

C was a terrific language for OS development when compared to assembly language, back in the late 20th Century. It is a shit language for OS development for the 21st Century. What’s better is still an open question, and what we can actually use that’s better… while we’re still using an OS that was designed in the late 1980’s… is a bigger question still.

I think Modern C++ helps.

Peter

Thanks Peter_Viscarola, as always…

Yea, looking forward to reading your NT article(s) on C++ in kernel mode !

I would very much appreciate it if I see what are the things in C++
that can be used with ease ( EASE ) without bending one’s head to
believe in the rituals :slight_smile:

For example — std::, algorithms etc. including others …

Pro

-Pro

BTW, the reason I have interest in this topic —

Two years ago, we were embarking on a project that would be C++ based
cross platform ( Windows, MacOS, Linux being main ones ). Quite a few
kernel modules ( for each platform 5 to 7 ). And lots of codes in
umode.

Back then C++17 is making its place, and I was trying to see how I can
get a message passing module – used BOOST and saw there are quite a
bit of interesting features there ( quite a few of them are now in
C++17 ). Had to move back for some kernel hacks, but there are lot
more works in that … Looks like I would be back next year to take a
shot at it…

Intellectual property protection is what we do, or at least try to do :slight_smile:

So it would help a lot when I see some articles from horses mouth :slight_smile:

-Pro

In my shop, we do C and C# in equal measure. Use the right tool for the right job. In at least the last 20 years, no one has presented any compelling argument to me why any part of C++ represents ‘super C’ or anything except a regression that has all the ways to hang oneself tat the old way has, but provides multitudes more as well.

To be sure C# has its own set of pitfalls as well

Now, what is the year when Linux got started ( i.e. porting Xinu or something after wholesale changes )???

What he actually did was providing his own implementation of UNIX (namely, its SVR2 version as described in Maurice Bach’s
“UNIX Operating System”), and used the MINIX source code in his project. He released it in 1991. You can check it if you wish.
It is available from kernel.org (IIRC , as version 0.01)

Perhaps early 90s in the lab, then around 94 or 96 it is out there !!!.. By then lot of people using C++/ Java is or already coming …
so why Linus did not conform to it… Whatever …

Actually, according to him, he tried to use C++ at some point.

[begin quote]

In fact, in Linux we did try C++ once already, back in 1992. It sucks. Trust me - writing kernel code in C++ is a BLOODY STUPID IDEA. The fact is, C++ compilers are not trustworthy. They were even worse in 1992, but some fundamental facts haven’t changed:

    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++.

In general, I'd say that anybody who designs his kernel modules for C++ is either

    looking for problems
    C++ bigot that can't see what he is writing is really just C anyway
    was given an assignment in CS class to do so.

Feel free to make up (d).

Linus

[end quote]

Anton Bassov

I read this somewhere before, thanks for putting it up here, Anton …
Perhaps things changed in Modern C++, waiting to read the upcoming NT
insider articles to see…
Pretty much everything is tied to std::<excpetion_handling>. And it is
still there, so runtime still think it can generate exceptions…

Exceptional C++, and More exceptional C++ ( little outdated) but a
good reference to understand what could go wrong, how to handle those
situations.

Back in those days, we were writing NDIS based drivers on Windows 98,
we were using all C memory mgmt API. Then RTL*() came and it was a
real joy, seriously. For C++ there are a lot of features that I would
love to use, if they take the excption_handler out or a way to disable
it all together :slight_smile:

-Pro</excpetion_handling>

Mr @MBond2 wrote:

no one has presented any compelling argument to me why any part of C++ represents ‘super C’ or anything except a regression

Really? So, you’re going to argue that strong type checking is a regression? Likewise, #define is better than constexpr? That having to code the number of elements in an array, and keep that consistent, is better than range-based for?

I’d love to hear that.

Peter

Shouldn’t the question be “Rust in kernel”?
We are in the 21st century.

In any case, I agree with Peter on:
“3. Full-On OO C++: This approach is what I think most C Language folks envision when they think of “drivers in C++” … and it makes them shudder. I don’t commonly see this approach anymore, except from folks who are on dev teams where OO is a way of life and they really hate thinking in C Language interface terms. Having seen, and tried to understand and debug, fully class-based, object oriented approaches to writing Windows drivers I can personally attest to how very painful this can be.”
It is great until you need to add more members to the team or pass your code to someone else.
But 1 and 2, make a lot of sense, in my opinion.

Best regards,
Yan.

Shouldn’t the question be “Rust in kernel”?

Well, we _could _have that discussion, but probably in a separate thread.

FYI, it’s been done. Even I managed to write some mess in Rust and got DriverEntry to be called and DbgPrint to output stuff. But it’s a super-big mess right now. And you wind-up with a lot of “unsafe” code.

Peter