Basic memory management and error handling, for example, are radically easier and less error prone in C++ than in C. Less reliance on macros and goto's should be pretty obvious wins.
There's really very little reason to ever use C over C++ with modern toolchains.
Microkernels don't need memory management. Dynamic memory management in a kernel is a denial of service attack vector. Fuschia is built on a microkernel, so I expect they will follow the property of every microkernel since the mid 90s: no dynamic memory allocation in the kernel, all memory needed is allocated at boot.
Furthermore, you don't want exceptions in kernel code. That carries huge and surprising runtime execution and space costs.
Simply put, there is no reason to choose C++ for a microkernel, and many, many reasons not to.
Of course they do. It takes memory to hold metadata about a process. It takes memory to hold resources about other services. It takes memory to pass data between them.
Just because that memory is reserved at boot doesn't mean it suddenly has no lifecycle of any kind.
> Furthermore, you don't want exceptions in kernel code.
Nobody said anything about C++ throw/catch exceptions.
> Simply put, there is no reason to choose C++ for a microkernel, and many, many reasons not to.
If you want to avoid C++ that's great, but to argue for C over it is insanity rooted in nostalgia.
Yes it does. The "lifecycle" is: allocate at boot, machine halts.
All of the memory you describe for other purposes is allocated at user level and booked to processes. This is how you make a kernel immune to DoS.
> Nobody said anything about C++ throw/catch exceptions.
That's the only meaningful difference in error handling between C and C++. Since you mentioned error handling as a reason to choose C++, what else could you possibly mean?
> If you want to avoid C++ that's great, but to argue for C over it is insanity rooted in nostalgia.
Sure, you keep believing that. It's clear you're not familiar with microkernel design. The advantages C++ has for application-level programming are useless in this domain.
I believe he means RAII. It makes it almost impossible to forget to release resources or rollback transaction.
No. For that you need a better type system. Linear types show great promise for this.
[1] http://homepages.inf.ed.ac.uk/wadler/papers/linearuse/linear...
{
Resource foo(path);
if … {
return -ENOMEM
}
return 0;
}
Than to get this right: {
Resource* foo = acquire(path);
if … {
release(foo);
return -ENOMEM
}
release(foo);
return 0;
}
Even if you do the goto-style: {
Resource* foo = acquire(path);
int rc = 0;
if … {
rc = -ENOMEM
goto out;
}
out:
release(foo);
return rc;
}There are also library types that enforce checking for errors, something currently impossible in C.
Also thanks to its stronger type system, it is possible to do type driven programming thus preventing many errors to happen at all, which is also not possible in plain C.
Finally everyone is moving to C++, C for OS development is stuck on UNIX and embedded devs that wouldn't use anything else even at point gun.
This is a weak form of checking for a kernel. L4 Hazelnut was written in C++ for this reason, but they didn't use it much, mirroring Shapiro's experience with EROS. And when they had to revise the kernel design to plug security holes and they wanted to formally verify its properties, they switched to C because C++ was too complex and left too much behaviour unspecified, and thus we got verified seL4 written in C.
OpenCL lost to CUDA because it did not natively supported C++, only when it was too late.
NVidia has designed Volta specifically to run CUDA C++ code.
There is no C left on game consoles SDKs or major middleware engines.
All major C compilers are written in C++.
Microsoft has replaced their C runtime library by one written in C++, exposing the entry points as extern "C".
Beyond the Linux kernel, all native parts on Android are written in C++.
The majority of deep learning APIs being used from Python, R and friends are written in C++.
Darwin uses a C++ subset on IO Kit, and Metal shaders are C++14.
AUTOSAR has updated their guidelines to use C++14 instead of C.
All major modern research OSes are being done in C++, like Genode.
Arduino Wiring and ARM mbed are written in C++.
As for Rust, while I do like it a lot, it still cannot compete with C++ in many key areas, like amount of supported hardware, GUI frameworks and available tooling.
Really? Interesting thing. You mean for "standard/legacy" autosar, or for the new "dynamic" variant?
When I was back in automotive, the autosar design(s) where probably the ones software people were mostly complaining about.
I am no expert there, learned it from their presentation at FOSDEM last year.
https://archive.fosdem.org/2017/schedule/event/succes_failur...
Page 12 on the second slideset.
They are surely a vocal minority, otherwise Metal shaders wouldn't be C++14.
This kind of pattern doesn't exist in a microkernel. I agree it might be useful in a monolothic kernel, but that's not the context here.
No, they aren't. A microkernel is responsibe for basic thread management and IPC. Both of which are highly dynamic in nature.
You seem to be confusing the system that decides when to make a scheduling decision (userspace process - although still part of the microkernel project, so still included in all this anyway), with the system that actually executes that decision (the microkernel itself). And in the case of systems like QNX the kernel will even do its own decisions independent of the scheduler service, such as switching the active thread on MsgSend.
But whether or not it's in ring0 or ring3 is independent of whether or not it's part of a microkernel. A microkernel delegates responsibility to ring3 processes, but those processes are part of the microkernel system - they are in fact a very critical aspect of any microkernel project, as without them you end up building a bootloader with aspirations of something bigger than a kernel.
I disagree. Certainly you won't get a usable system without some core services, but the fact that you can replace these services with your own as long as you satisfy the protocol means there's a strong isolation boundary separating them from the kernel. Certainly they are essential components of the OS, just not the kernel.
As for the alleged dynamism of thread management and IPC, I don't see how it's relevant. There exist asynchronous/non-blocking IPC microkernel designs like VSTa and Minix in which the kernel allocates and manages storage for asynchronous message sends, but it's long since proven that such designs are hopelessly insecure. At the very least, it's trivial to DoS such a system.
Only bounded message sends with send/receive buffers provided by processes can you avoid this inevitability. If the idea with Fuchsia is to reimagine consumer operating systems, avoiding the same old mistakes seems like a good idea.
As for scheduling, that's typically part of the kernel logic, not a user space process. Yes, message sends can donate time slices/migrate threads, but there are priority inversion problems if you don't do this right, as L4 found out and avoided in the seL4 redesign. I honestly don't know why Google just didn't use or acquire seL4 for Fuchsia.
ESR was recently making some generalized observations in this direction: http://esr.ibiblio.org/?p=7804
Can you please name a project that you have worked on where you have run into problems because everything was in a single namespace? What was the problem, how did you run into it, and how did you resolve it?
There are a lot of advantages to namespaces. I used to believe that single-namespace languages would cause problems for large software, but working with Emacs (huge single namespace with all the libraries loaded into memory at once, so much worse than C, where you only link a subset of libraries), this problem has not surfaced. I mean literally the only difference is that ".", or whatever the language-enforced namespace accessor is, goes from being special syntactically, to being a convention. When you start to think about namespaces as trees, this makes more sense. Namespaces just push naming conflicts to the parent node. There is no magic that is going to solve conflicts or structure things well or give things clear names. All that is up to the programmer.
https://isocpp.org/blog/2012/11/universal-references-in-c11-...
In my view C++ is a very complex language that only few people can write safely and productively.
When you say "I understand my code" I have to believe you. The problem is that understanding other people's C++ code takes ages, even if they don't abuse the language. Trusting their code is another story entirely.
C++ is a very flexible language in that it puts few restrictions on redefining the meaning of any particular syntactic expression.
That's great, but it also means that there is a lot of non-local information that you have to be aware of in order to understand what any particular piece of code actually does.
I'm not surprised that C++ is both loved and hated and perhaps even more often simply accepted as the only practical choice.
There aren't many widely used languages around that allow us to optimize our code almost without limit and at the same time provide powerful abstraction facilities.
At the same time, there aren't many widely used languages around that make reading other people's code as difficult as C++ (even well written code) and come with a comparably long tail of accumulated historical baggage.
The language is dealing with some tricky concepts. To hide them or try to gloss over them would lead to writing virtual machines and bloated memory usage etc. in the style of C# / Java.
How else would you deal with movement of variables and when an rvalue becomes an lvalue inside a function?
Even Java and C# are slowly getting down that path.
Languages get those features because they make sense and solve real production problems.
> Any language can be used to write indecipherable bad code. You are blaming the wrong thing. Some languages allow stupid things. Some even encourage it. So, no, languages can and should be blamed.
Bjarne created C++ exactly because he didn't want to repeat the experience he had, when he lost his Simula productivity to BCPL.
Of course the C designers thought otherwise of their own baby.
So if you're going to argue in favour of C++ with the caveat of good developer practices then you must also make the same caveat of C (ie you cannot play the "goto spaghetti" card) otherwise you're just intentially skewing your comparison to win a pointless internet argument.
There's no goto spaghetti in C -- it's only used for local error handling, not for jumping around, at least since the 70s...
All 10 of them?
Enterprises also write native code, it is not everything Java, .NET and SAP stuff.
The rest of it could hide any number of dragons (and be written in any kind of legacy, nightmarish, and/or proprietary tools and languages), so it's not much of a proof of widespread bad C "goto" abuse.
Let's make a better criterion: how many of the top 200 C projects in GitHub suffer from "spaghetti goto" abuse? How many of all the C projects in GitHub?
For example, iOS applications, portable code between Android and iOS, distribution tracking, factory automation, life science devices, big data, graphics are all a small list of examples where C and C++ get used a lot.
Sometimes it says C++ on the tin, but when one opens it, it is actually the flavour I call "C with C++ compiler".
Github is not representative of enterprise code quality.
Did you know that code in C++ can run outside of main()?
I used to be a C++ believer, and advocated for C++ over our companies use of Java.
One day, they decided they wanted to "optimize" the build, by compiling and linking objects in alphabetical order. The compile and link worked great, the program crashed when it ran. I was brought in to figure it out.
It turned out to be the C++ "static order initialization fiasco":
https://yosefk.com/c++fqa/ctors.html#fqa-10.12
If you've ever seen it, C++ crashes before main(). Why? Because ctors are getting run before main(), but before other dependent statics have been constructed.
Changing the linking order of the binary objects fixed it. Remember nothing else failed. No compiler or linker errors/warnings at the time, no nothing. But one was a valid C++ program and one was not.
You might think that is inflammatory, but I considered that behavior insane, because main() hadn't yet even run, and the program cored leaving me with trying to figure out what went wrong.
>> Furthermore, you don't want exceptions in kernel code.
>Nobody said anything about C++ throw/catch exceptions.
I'd like to add that if you're finding yourself restricting primary language features (e.g. templates, statics ctors, operator overloading, etc.) because the implementation of those features are bad, maybe using that language is the wrong choice for the project you're working on.
After I read the C++ FAQ lite [1] and the C++ FQA [2], I realized the determinism that C provides is kind of a beautiful thing. And yes. For a kernel, I'd argue C over C++ for that reason.
[1] C++ FAQ Lite: http://www.dietmar-kuehl.de/mirror/c++-faq/
[2] C++ Frequently Questioned Answers: https://yosefk.com/c++fqa/
I think that there are stronger arguments against C++: the continued presence of the complete C preprocessor restricting the effectiveness of automatic refactoring, the sometimes extremely cumbersome template syntax, SFINAE as a feature, no modules (yet!)...
Still, C++ hits a sweet spot between allowing nasty hardware-related programming hacks and useful abstractions in the program design.
So parsing your sentence. I'm right, and you're blaming me for not knowing a language as expertly as you. I can live with that.
Edited to add:
I admit it's a little snarky perhaps, but the c++ standard is 1300 pages long. It took my browser in 2018 1 minute to open it.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n379...
I really do not have time to read a document like that to figure out whether or not that behavior is spelled out in the standard. So yes, I'll let you be the expert on this.
There are worse pitfalls than unstable order with static initializers specifically. If you dynamically load shared libraries at runtme on Linux, you risk static initializers being run multiple times for the same library. This is platform specific behavior that is AFAIK present on other UNIX systems as well and I'm certain that you won't find that in the standard.
Water under the bridge.
While I did say I was brought in to fix it, what I didn't say was that the group's management thought that Java coders could code in C++. D'oh.
void _start(){ / bla bla / exit(main(argc, argv)); }
The better I get at C++, the less of it I actually use.
It is funny how many issues people blame on C++ that are usually inherited from C semantics compatibility, or existing C extensions at the time C++ started to get adopted.
Let's try to write the equivalent of this error in C:
int myfunc() {
return 5;
}
static int x;
static int y = 4;
static int z = myfunc();
int main()
{};
Compiling that in gcc gives me: main.c:8:16: error: initializer element is not constant
static int z = myfunc();
^~~~~~
And it makes sense, C just wants to do a memcpy() to initialize the static variables. In C++, the only way the class is initialized is if the ctor is run. And that means running the ctor before main().Edited to add:
You're correct that 5.1.2 does not specify memcpy() as a form of initialization. But see my reply below about C11 and static storage classes.
Also add common C extensions into the soup like constructor function attributes.
Finally ISO/IEC 9899:2011, section 5.1.2.
"All objects with static storage duration shall be initialized (set to their initial values) before program startup. The manner and timing of such initialization are otherwise unspecified. Program termination returns control to the execution environment."
Don't mix what your compiler does, with what the standard requires.
Doing so only leads to unportable programs and misunderstandings.
Read section 6.7.9, constraint 4:
All the expressions in an initializer for an object that
has static or thread storage duration shall be constant
expressions or string literals.
It's syntax, not initialization.And that makes sense. However the memory is initialized before runtime could be via memcpy() it could be loaded as part of the executable and then mapped dynamically at runtime. That's what 5.1.2 is saying.
What 6.7.9 constraint 4 is saying, is that static variables can only be constant expressions.
C++ has to run code before main if a ctor is in a class that's static. There's no other way to initialize that static object.
C prevents this by requiring static storage to be initialized with constants.
namespace {
int myfunc() {
return 5;
}
int x;
int y = 4;
int z = myfunc();
};
int main()
{}
In my opinion, his point is still valid.That's why it gives you a compiler warning, and why your IDE marks it in yellow.
The same issue occurs in any language with static constructors, including Java.
#include <stdio.h>
static volatile int* x; static int y = 42;
void __attribute__((constructor)) foo() { printf("[foo] x = %p\n", x); }
int main() { x = &y; printf("[main] x = %p\n", x); return 0; }
And before you complain about that being a compiler extension yes, it is, but it's also not rare, either, and you're probably using C libraries that do this.
e.g. All Linux kernel modules use this for initialising static structs for interfacing with the kernel.
[1]: https://www.geeksforgeeks.org/__attribute__constructor-__att...
For example, the dreaded singleton using a static variable inside a function:
Singleton& get_singleton() {
static Singleton instance;
return instance;
}
Having a couple of those referenced in static initializers is a recipe for disaster. It’s a bad practice, but people unfortunately do it all the time. Those that do this are equally unequipped to realize why their program suddenly started crashing after an innocuous change.That applies to both C and C++ though.
In my opinion, it's better to not rely on static constructors for anything non-trivial (singleton or not). They can be such a pain in the ass to debug.
* Donald Knuth: http://tex.loria.fr/litte/knuth-interview
* Linus Torvalds: http://harmful.cat-v.org/software/c++/linus
* Martin Sústrik: http://250bpm.com/blog:4
I don't really like C++ and I haven't been forced to use it (with C and C++ you are basically forced to use them, few people use them for greenfield projects willingly, same for JavaScript; this of course doesn't apply for people who are already C/C++/JavaScript programmers), but from everything I've seen about modern C++ they are moving to a more consistent programming style.
Criticizing C++ in 2018 with arguments from back in 1993 feels dishonest.
"The problem that I have with them today is that... C++ is too complicated. At the moment, it's impossible for me to write portable code that I believe would work on lots of different systems, unless I avoid all exotic features. Whenever the C++ language designers had two competing ideas as to how they should solve some problem, they said "OK, we'll do them both". So the language is too baroque for my taste. But each user of C++ has a favorite subset, and that's fine."
In fact, they do so even better than they did back then. E.g. I eagerly anticipated C++11, but virtually every codebase that's older than three or four years and not a hobby project is now a mixture of modules that use C++11 features like unique_ptr and modules that don't. Debugging code without smart pointer semantics sucked, but debugging code that has both smart pointer semantics and raw pointers sucks even harder.
There's a huge chasm between how a language is standardized and how it's used in real life, in non-trivial projects that have to be maintained for years, or even decades.
Debugging pointers seems a poor reason to criticize an entire language!
C++ may be complicated but the English language is also complicated; just because people tend to use a smaller vocabulary than others doesn't make the language irrelevant or worthless.
Looking at how English has been used to create a raft of rich and diverse poetry, plays, prose and literature in general, the same should be applied to C++ because the unique use of it in a variety of varying circumstances surely is its beauty.
I don't think this is a valid argument, though. Natural languages have to be rich. Programming languages should be terse and concise because we have to keep most of them in our heads at one time and our brain capacity is limited. You don't need to know all of English/French/Romanian but you kind of need to know all of C++/Python/Javascript to do your job well when developing C++/Python/Javascript.
I think the C++ designers lately kind of agree with me but the backward compatibility requirements are really stringent and they can't just deprecate a lot of the older features.
Legalese uses a ton of latin ididoms, arcane rights and philosophies. This is comparable to the cruft of C or C++ standards. For a microkernel of some thousand LOC you shouldn't need a multi-paradigm language.
seL4 did it in Haskel, which is a step in the right direction. Then it was ported to a provably safe subset of C.
"At the moment, it's impossible for me to write portable code that I believe would work on lots of different systems, unless I avoid all exotic features."
Is just not remotely true anymore. Modern toolchains entirely obsoleted that. Modern C++ compilers are nothing like what Knuth used in 1993.
If anything it's easier to write portable C++ than it is portable C due to C++'s STL increasingly covering much of the POSIX space these days.
That statement itself seems intellectually dishonest. What has changed that invalidates his arguments? After all, C++17 is still backwards compatible to the C++ of 1993.
Pardon me for finding this humorous, but stating that I can’t use a Donald Knuth quote in a computer science topic because it’s an old is like saying I can’t quote Sun Tzu when talking about modern events because the Art of War is an old book.
https://en.m.wikipedia.org/wiki/The_Art_of_Computer_Programm...
So to change your analogy, it would be like quoting Sun Tzu about the disadvantages of modern main battle tanks, using the Art of War. Sure, the principles in the Art of War are solid, but are we sure that they really apply to a discussion about Leopard 2 vs M1 Abrams?
That said, I'm not a fan of C++ either. I think its problems are intractable because they'd have to break backwards compatibility to clean the language and I'm not sure they can do that, unless they want to "Perl 6"-it (aka kill the language).
In any event, Knuth specifically made statements dismissive of C++ 25 years ago that I believe are still valid today. I must have missed reading Sun Tzu's missive on mechanized warfare from the 6th century BC. ;)
Indeed, we can both agree on the backwards compatibility problem. I'm waiting on a C++ build as I type this. Also, I really like the new language features like std::unique_ptr std::function and lambdas.
I'd still rather do my true low-level programming in C bound with a garbage-collected higher-level language for less hardware-focused or performance-critical work instead of bolting those features on to C by committee over the span of decades. For example, C shared libraries with Lua bindings or LuaJIT FFI are bliss in my humble opinion.
He then criticises exceptions thrown in constructors and favors a init-function style. I never had any problem with this because I follow the rule that there shouldn't be much code in the constructor. The one and only task of a constructor is to establish the object's invariant. If that is not possible, then the object is not usable and the caller needs to react and shall not use the object.
In the second series, he first compares apples (intrusive containers) and oranges (non-intrusive containers), and then argues that the language forces him to design his software that way. Basically he argues that encapsulation makes it impossible in his case to write efficient code, and that you have to sacrifice it for performance.
However, with C++, you can extract the property of being an object in an intrusive list into a re-usable component, e.g. a mix-in, and then use your intrusive list with all other types. I can't do this in C in a type-safe manner, or I have to modify the structs to contain pointers, but why should they have anything to do with a container at all?
Besides that, I think that Martin is a greate programmer who did an amazing job with ZeroMQ. But I have the impression that he is wrong in this case.
If I were to start a project today, I'd rely heavily on optional and result types and use exceptions only for serious errors, when it makes sense to unwind ans start from a clean slate.
The trick to use C++, is to use less of it. C with classes and namespaces. Oh and smart pointers.
- "In general case code should be readable to anyone who is familiar with C language". Why should it? C++ is a different language than C. I speak german, but I cannot read e.g. French unless I learned it even though they are related.
- "Don't use exceptions". Why? There is no performance penalty in the non-except case, and the exception case should be rare because it is exceptional. I can see arguments for real-time systems, and for embedded systems were code size matters. The alternative is C-style return codes and output parameters. Exceptions are better in that case because you cannot just go on after an error condition, and functions with output parameters are harder to reason about because they loose referential transparancy. Of course, in modern C++ one could use optional or expected types.
- "Don't use RTTI". I never needed RTTI in my professional life.
- "Don't use C++ runtime wrapper for C runtime includes". C++ wrappers have some benefits over the C headers. They put everything in namespace std, so you don't need to use stupid prefixes to prevent name clases, and they define overloads for some of the C functions, e.g. std::abs(int) and std::abs(long) instead of abs(int) and labs(long).
- "Don't use stream, use printf style functions instead". If this means to use a type-safe printf variant I could agree to some point, although custom operator(<<|>>) for custom types are sometimes nice. If it means to use C printf etc I would strongly object.
- "Don't use anything from STL that allocates memory, unless you don't care about memory management". You can use allocators to use e.g. pre-allocated storage. The STL also contains more than containers, why would you not use e.g. the algorithms and implement them yourself?
Surely there’s a reason. Why?
Are they aware of them? That's not so clear. There's a lot of literature in microkernel design. Lots of things have been tried which sound good but haven't worked out, and some things didn't work out well before would work well now. As usual, security also rarely gets the attention it deserves and it's doubly important at the kernel level.
This does not seem incredibly complicated.
Except this was tried. More than once for different kernels (EROS and L4 at least), and they regretted it and then switched back to C. Both projects made many excellent arguments against C++ in a microkernel that haven't suddenly disappeared in modern C++.
So I think I am being charitable in this case because the weight of evidence suggests otherwise. It's charitable to assume that the developers are well meaning but aren't familiar with the history. This isn't staggering ignorance, just ordinary run of the mill ignorance.
For L4, there's brief mention here of the VFiasco project which attempted a verified L4 using C++, which failed despite considerable effort [2].
[3] is perhaps a better review of what worked and what didn't work in L4 research, and they explicitly discuss the issues, such as the fact that C++ conveyed no real advantages over C, the extra complexity of C++ made verification intractable (even for a subset), and practically, the availability of good C++ compilers for embedded systems was limited.
[1] http://webcache.googleusercontent.com/search?q=cache:PQMCrw4...
[2] http://web5.cs.columbia.edu/~junfeng/09fa-e6998/papers/sel4....
[3] https://ts.data61.csiro.au/publications/nicta_full_text/8988...
Systemd uses it: https://github.com/systemd/systemd/blob/5809f340fd7e5e6c76e2...
Some people rather use official language features.
... i suppose this project is locked into G-standard C++ and with lots of good reasons (e.g. toolchain). although i'm an anti-C++ person, i suppose the sorts of tools available internal to Alphabet make it much more manageable.
anyway, for an example of the original premise: i'm slowly learning some things about plan 9 C via 9front.. there are some departures from ANSI C, including additional features like (completely undocumented, except for the relatively compact source) operator overloading. equally important for the type of person that finds C++ too busy, some features (e.g. certain preprocessor features) are removed.
It makes managing any resource with acquire/release semantics very easy. It also prevents errors when the code is modified later because you cannot forget to call cleanup code as it is done automatically. I have no experience with kernel programming, but acquire/release seems to be something that is done in the kernel.
Agreed. But microkernels generally don't acquire or release resources. Most people arguing against this point seem to have a monolithic kernel mindset, but microkernels are a whole different beast.
If a kernel owns any kind of resources, that leaves the whole system vulnerable to denial of service attacks. Therefore, microkernels have long since adopted designs where the kernel does not own or allocate anything, and all resources belong to processes (which incidentally makes identifying misbehaving processes easy, something not easy on UNIX kernels).
Any data the kernel requires for its operation is allocated at boot time and lives until the system halts.
- most C code compiles magnitudes faster than most C++ code (unless you don't use templates or the C++ stdlib)
- you need C headers anyway for the public API, because the C++ ABI is not standardized (and a mess), trying to do shared libraries with C++ would result in such abominations like COM
- about half of features that C++ adds on top of C only make sense if you do OOP and encourage bad practices
- C is a much simpler and "complete" language, there's less room for debating about coding style, what C++ subset to use etc... (that's one thing that Go got right).
Also, Eric S.Raymond's "informed rant" on C++ is relevant: http://esr.ibiblio.org/?p=7724
I'd really like to see a simple language which fixes C's (very few) flaws succeed, but C++ ain't that.
Most of the problems C++ has are coming from being backward-compatible with outdated language features, explicitly the C-subset. Even the problems with the toolchain are more less inherited from the C compile-link model and its use of the preprocessor as a "module" system.
If you use the language as intended, e.g. in the C++ core guidelines, you will se very nice language emerging which enables to write very efficient and elegant code, sometimes doing things that C cannot do, such as expression templates.
JavaScript is also an ongoing effort to extract and evolve a good working language out of a mass of features. It's obviously doable, but not easy, and there are a lot of problems in practice.
Formal verification is one reason. There is still no formal model of C++ and C formal tools are light years ahead.
You wouldn't be doing much memory management in such a kernel. And where you would, you wouldn't let it to C++.
I'd never heard the terms "Confused Deputy" or "ambient authority" before, but it sent me on a pleasant and informative internet security tangent.
https://www.youtube.com/watch?v=TQhmua7Z2cY&index=5&list=PLU...
It is a good course.
Is there a way that these could mediated by a capability without having to incur syscall overhead? One of the reasons that these are bare functions is likely that they are in the vDSO, and are just simple function calls which can access some shared memory which contains the clock time. I suppose you could simply not give some processes access to that memory, and have the functions in the vDSO just return an error in that case.
I know that there was a time when the Linux kernel changed how their vDSO handling worked, so older glibcs would have to fall back to making an actual syscall for gettimeofday, and that seriously affected performance on some servers that updated the kernel without updating glibc. These functions are called quite often on servers for logging purposes, so adding overhead to make them go through a syscall can be a big performance hit.
> I'm hesitant to endorse any system calls with ambient authority, even if it's scoped by context like these. It's far too easy to introduce subtle vulnerabilities. For instance, these calls seem to permit a Confused Deputy attack as long as two processes are running in the same Job.
Yeah, this is a bit odd. In fact, it's not just these syscalls which have ambient authority, there's a whole list in https://fuchsia.googlesource.com/zircon/+/master/docs/syscal... and it includes VMOs, ports, sockets, and so on.
It does seem somewhat odd to have this capability system, but then ignore it for a number of actions which can only be limited at the job level.
Good point. I was going to say that in general the vDSO is just rdtsc + an offset applied. However they insert a barrier before it usually. That maybe or many not be helpful so I would probably still use rdtsc by itself.
Is that even warranted? What applications can you imagine would make so many clock calls so as to incur noticeable overhead?
Your example of logging costs might work, but I'm very skeptical that user/kernel transition costs for a clock call would drown out the costs of writing the log entry to disk.
But to answer your question directly, the ability to access the clock in a shared memory segment can itself be reified as a handle that's granted to a process. The process would then issue a map operation and provide an address at which to map the clock (or you could just always map it at the same address too if that's preferable for some reason).
Low latency processing or realtime-ish applications. If you have a budget of a few milliseconds only, lots of gettimeofday can start to add up. Now true that nowadays they are mostly vDSO so it doesn't matter as much. I remember before they were we saw a decent speedup when we upgraded to vDSO kernel version.
> But to answer your question directly, the ability to access the clock in a shared memory segment can itself be reified as a handle that's granted to a process.
rdtsc is not shared memory but more like a register read. Though it is a virtualized instruction so on proper VMs (not a container) it is possible to control what the guest sees as the value.
The point being, a handle should be involved at some point in order to make the access control explicit and not implicit and ambient.
I will grant that this case is an outlier, but this customer use-case is real enough to drive development dollars. It may not be the norm, but precision timing access appears to be very useful in some hard real-time contexts given current hw/sw realities.
Mixing safety criticality levels is hard.
And besides logging, there are things like nanosleep or spinlocks which may briefly spin while querying the time before yielding.
I know of at least one CDN which was measurably impacted by the gettimeofday issue.
And yes, you could have the access to the address itself be something you are given access to via a capability/handle, but then the system call itself (which is actually a vDSO call) wouldn't have to actually take a handle as a parameter.
Another poster said something similar, but using the clock for this seems strange to me. Yielding a time slice for a certain number of ticks doesn't need access to the current time. I have less objection to an ambient yield since that's really an operation on your own schedule capability.
If you're after some kind of exponential backoff for a spinlock, that again doesn't seem to need the current time so much as a growing counter of the number of ticks to sleep.
> And yes, you could have the access to the address itself be something you are given access to via a capability/handle, but then the system call itself (which is actually a vDSO call) wouldn't have to actually take a handle as a parameter.
Correct, you'd use the handle to install an ambient clock in your environment. This leaves open the possibility that you can easily virtualize the clock by proxying the clock handle, ie. instead of the kernel updating your shared memory segment, it's another process.
The point being that reifying everything as a handle makes arbitrary virtualization patterns possible, but having ambient authorities all the way down to root makes it much more difficult.
Does it matter if it seems strange to you? The GP gave real world examples of where this is an impact. I'm not sure why you are arguing against the design.
Because the design is questionable, and so the example is questionable. Isn't that obvious? Why else would I bring it up?
You might be shielded from this depending on what level you're working at, but there's a reason that vDSO exists basically solely for clock_gettime, too.
Yes it allows for timing attacks, but you can't really avoid that, either, not without utterly crippling your platform.
That seems strange to me. Why would you use the clock/gettime call for that instead of a work counter of some sort?
Something like sleep() is an operation on your own schedule, not an operation on a global system clock. That's not nearly as problematic.
Consider if you wanted to virtualize a process, say to deterministically replay it to trigger a fault or something. sleep(100 ticks) doesn't require additional kernel support for virtualization, but an ambient clock requires a lot of extra kernel support.
If the clock were only accessible via a handle, then you could proxy invocations on the handle without any extra support in the kernel. See my other comment for more details: https://news.ycombinator.com/item?id=16817462
Otherwise what actually happens when you do a postDelayed(func, delay) is it immediately is translated into a postAt(func, clock_gettime() + delay). Then as messages are consumed the work queue consistently knows how long it should wait to wake back up, no matter how many delayed tasks are in flight.
Are you instead talking about some kind of event loop? If so, then clock_gettime seems like it's merely convenient, not essential. You could just as easily keep a ticket incremented on successful operations or successive loops (or some other metric), and exponential backoff is a wait operation on a ticket number.
Unless you're suggesting the delay must be based on real time for some reason?
Congrats, you've re-invented clock_gettime(CLOCK_MONOTONIC) :)
You're right that it's not essential to have, but if you can re-implement it then you've also just re-introduced the timing attack that the removal of clock_gettime was trying to prevent.
The trivial-ness with which a clock suitable for timing attacks is able to be created is literally why SharedArrayBuffer was panic-removed from all major browsers. Because that's all you need, shared memory & a worker. Congrats, you have a high-precision timer with zero OS support.
So as soon as you allow any form of threading or shared memory to occur you've given apps a high precision timer, so you might as well just give them an actual timer, too.
I'm not convinced. The clock is global, shared among all processes, the ticket I suggested is local to a process, and so can't be used to signal between processes. Unless I'm again missing some context for what you mean.
That still requires a piece shared state, like I said. That vulnerability results from running untrusted code in the same process as trusted code. The whole point of a process is to establish a protection boundary around potentially unsafe code, hence why I keep mentioning processes, and this is the whole point of microkernels and IPC. Within a process, all bets are off.
My earlier point was that a shared clock between processes amplifies this problem so that timing attacks cross even the process protection boundary. So when you started talking about job scheduling, I assumed the following:
1. we're in a microkernel context, where we partition trusted and untrusted code using processes.
2. the job scheduling system you mentioned either
a) is a process running its own code that it trusts and so in-process timing attacks don't matter, but timing attacks with another process might matter and so you don't want to grant a clock capability if it isn't needed, or
b) is a process scheduling system ala cron, where the job scheduler is trusted but the jobs being run are untrusted, and so they run in separate processes.
In case (a), the ticket system seems sufficient if you don't want/need to grant access to the clock consistent with least privilege, and for (b) the job scheduler may or may not have the clock installed or not, doesn't really matter, since job scheduling happens via IPC so there's no shared read, ie. delay(100 ticks, self) sends the relative delay which the cron-like scheduler adds to its own clock.
Hopefully that clarifies my context, and you can then describe what assumptions your scenario violates.
It doesn't, though. Your point fundamentally misunderstands the nature of a timing attack for ex-filtration. It doesn't cross process boundaries. It doesn't use any process crossing state of any kind for timing. It simply times how long it takes to access cache lines, which is perfectly local & isolated. It does not involve time correletation or association across processes of any kind. It doesn't care about real time at all. All it needs is a stopwatch that can measure the difference between 0.5-2ns & 80-120ns.
The meltdown attack via SharedArrayBuffer did not use any untrusted code in the same process. It read kernel memory at will using 2 threads and an atomic int.
There's a few more related articles on his blog if you search, and I've read of it being implicated elsewhere, that's not to say the software calling that much was doing the right thing, just that it had impact.
This can happen because RDTSC is not synchronized between physical CPU sockets (NUMA regions).
Orthogonality doesn’t obviate the need for metaprogramming though. For example, there are lots of places you might need a linked list structure, where the nodes store different types. You might use templates over intrusive structures to gain some type safety without duplicating code for each contained type.
Sure, but linked lists have solutions already using simple macros [1]. There aren't many sophisticated kernel data structures, mainly tables for indexing and linked lists, all of which have simple expressions as macros. Templates perhaps make this a little easier, but are overkill.
[1] http://www.roman10.net/2011/07/28/linux-kernel-programmingli...
aPerson = list_entry(node, struct Person, list);
while the templated way is.Sure they do, unless your type checker is formally verified. Are you suggesting there exists a formally verified C++ compiler?
> Running the compiler is also a lot cheaper than having someone inspect every line of code carefully.
Except that's not what I suggested. You only need to audit lines that perform potentially undefined behaviour. The C type checker ensures the rest are fine. I think it's clear this problem is worse in C++ given all of the additional abstractions that interact in surprising ways.
Furthermore, C++ has no formal verification tools, so if you wanted real guarantees, you'd use something like Frama-C or a theorem prover like they did with seL4. Microkernels in C++ have been tried, and in every case they switched back to C for very good reasons.
If I care so much about system correctness that I do the insane amount of work that is formal verification (just look at how many man years sel4 consumed!), I don't write C or C++ at all, I use Spark. There is a reason why you can count the number of formally verified kernels on the fingers of one hand, and it's not because everybody tries to use C++ instead of C.
Nope, but your unqualified statement was simply false, and in any case, your point isn't really relevant. This single line of code we're discussing is easily verifiable by manual inspection and automated testing. We're not talking about huge swaths of code here, we're talking about a few unsafe primitives, because this kind of reuse isn't typical of a microkernel.
The type safety of a single operation expressed as a template is relatively insignificant compared to the added complexity of C++, particularly considering the "reuse" benefits are non-existent for microkernels, and if all you're left with is some elusive "type safety" for a linked list, that's simply not enough.
This is obvious when you know the history of multiple C++ kernel verification efforts, all of which failed, no matter how simple of a C++ subset was chosen. Many C verification efforts have succeeded, and tools for lightweight formal methods, like Frama-C, make the transition to verification possible with C. C++ is a dead end for this purpose, and the various L4 groups that created L4 kernels in C++ and then rewrote them in C all agree.
I haven't worked with Go personally, but "no generics" is probably the most commonly vocal complaint I hear about it, so clearly some people do care.
Multiply that by 10 if you have several junior team members who have been told, and read, that concurrency and parallelism is easy in go.
Advanced users might want to use advanced data structures that are not built-in in the langage, and templates can be convenient to do that.
Not my observation at all.
"leaves the system open" are strong words. If you allow only threads you have got high precision clocks as a bonus in practice. Still it could be useful to have environments so restricted that even restricting clock services could be useful, but I would certainly not call the lack of capability there a very big issue. Plus designing those would be hard anyway: does not having this capa would mandatorily prevent from even creating threads (or pretty much all kind of objects which can be retargeted to infer time, which means tons of them, and maybe it being the case or not will depend on the implementation)?
Maybe it is better to not pretend that a capability exists for getting the time if you will probably be able to get it without said capability?
The point being, any abilities that aren't reified as explicit handles are ambient in the environment, and so make isolation and virtualization harder. Consider how you would virtualize the clock now that it's part of the process's implicit environment instead of an invocation made via a handle.
An OS could help by making the virtualisable clock the default API. Still there will be applications that want a high-precision or low overhead clock. But those applications should buy into the trade-off explicitly.
Huh? NT has done this for 25 years.
I believe the NT kernel still checks permissions against ACLs for handles. This violates capability security, but you can build a capability OS on top of ACLs: http://www.webstart.com/jed/papers/Managing-Domains/
And the Spectre and Meltdown vulnerabilities have shown that it doesn't matter. Taking access to a clock or sleep mechanism away doesn't stop the bad guys but makes common programmers lives much more difficult.
You don't take it away, you reify the clock as a capability/handle. This has two benefits:
1. Those vulnerabilities have shown that you can mount timing attacks even without a clock, but a clock amplifies the timing attacks you can mount. For instance, there remain attacks with a clock even if Spectre and Meltdown and related vulnerabilities are fixed.
2. There are software engineering benefits. For instance, in principle you can replace the clock handle with a proxy that you can use to provide your own times. This helps considerably with testing, deterministic replay, etc.
> Calls which have no limitations, of which there are only a very few, for example zx_clock_get() and zx_nanosleep() may be called by any thread.
Having the clock be an ambient authority leaves the system open to easy timing attacks via implicit covert channels. I'm glad these kinds of timing attacks have gotten more attention with Spectre and Meltdown. Capability security folks have been pointing these out for decades.
> Calls which create new Objects but do not take a Handle, such as zx_event_create() and zx_channel_create(). Access to these (and limitations upon them) is controlled by the Job in which the calling Process is contained.
I'm hesitant to endorse any system calls with ambient authority, even if it's scoped by context like these. It's far too easy to introduce subtle vulnerabilities. For instance, these calls seem to permit a Confused Deputy attack as long as two processes are running in the same Job.
Other notes on the kernel:
* The focus on handles overall is good though. Some capability security lessons have finally seeped into common knowledge!
* I'm not sure why they went with C++. You shouldn't need dispatching or template metaprogramming in a microkernel, as code reuse is minimal since all primitives are supposed to be orthogonal to each other. That's the whole point of a microkernel. Shapiro learned this from building the the early versions of EROS in C++, then switching to C. C also has modelling and formal analysis tools, like Frama-C.
* I don't see any reification of scheduling as a handle or an object. Perhaps they haven't gotten that far.
Looks like they'll also support private namespacing ala Plan 9, which is great. I hope we can get a robust OS to replace existing antiquated systems with Google's resources. This looks like a good start.