Slashdot Mirror


C++ In The Linux kernel

An anonymous reader submits "A researcher at Reykjavik University Network Laboratory (netlab.ru.is) has just released a Linux patch allowing for complete kernel-level run-time support for C++ in the Linux kernel, including exceptions, dynamic type checking and global objects (with constructors and destructors) The implementation is based on the C++ ABI in GNU g++, but contains various kernel level optimizations, that reduces the cost of throwing exceptions by an order of magnitude, thus making C++ exceptions viable in several scenarios. Furthermore, the Linux module loader is extended to handle weak symbols in C++, so that dynamic type checking is reduced to a pointer comparison, in contrast to string comparison."

168 of 850 comments (clear)

  1. nice by Anonymous Coward · · Score: 5, Funny

    how long until c# is supported?

    1. Re:nice by 12357bd · · Score: 3, Insightful

      The core of Windows in C++? Maybe I am wrong, but If my memory serves me well, it was C and asm.

      --
      What's in a sig?
    2. Re:nice by myg · · Score: 4, Informative

      The core of Windows is written mostly in C. The GDI was written in C++ and the chief Kernel architect of WinNT (David Cutler) continually jabbed the Graphics group on their choice of C++.

      I don't suspect you will be finding C++ in NTOSKRNL any time soon. I think Cutler would beat up anybody who tried.

    3. Re:nice by character_assassin · · Score: 2, Funny

      If the GDI was written in C++, why isn't the API a C++ interface - or why doesn't it at least support one? That's screwy... but then again, we are talking about MICROS~1.

      --

      If you mod me down, I shall become more powerful than you can possibly imagine.
    4. Re:nice by Scherf · · Score: 4, Interesting

      Probably because a C++ interface is a pain to access from any other language than C++. Or perhaps because the Win32 API is a C library and cluttering it by adding C++ interface would be much more screwy.

      Actually most APIs that need to be used by alot of people have a C interface, no matter in what language they where written in. Has nothing to do with them being "MICROS~1"...

    5. Re:nice by Corngood · · Score: 3, Interesting

      Actually GDI+ has an extremely clean C++ interface. I was actually shocked when I saw it:

      http://msdn.microsoft.com/library/default.asp?url= /library/en-us/gdicpp/GDIPlus/GDIPlusreference.asp ?frame=true

    6. Re:nice by myg · · Score: 3, Interesting
      Because in the late 80's and early 90's (when NT was written) C++ was quite new and the toolchains didn't have stable ABI's (not that we have a stable ABI today). So things like virtual function tables and such had no standard.

      Also, a C++ API is difficult to use if you are programming in C (or Pascal or FORTRAN, etc) where some languages don't have objects. Sure it can be faked, but thats exactly what the GDI API was, a front end for the C++ code underneath.

      So even though the underlaying implementations of pens, regions, patterns and such is in C++ you still deal with them via handles. In fact, technical issues aside a C++ GDI API at the time made no sense for another reason: Windows (16-bit) compatability.

      There was a big push by Microsoft to make the Win16 to Win32 converstion as much of a recompile as possible. Why else would we still have global and local memory? Such horrid things should have been dispatched to the land of the arcane years ago.

  2. More Confusion by OverlordQ · · Score: 4, Funny

    So what will we say the kernel is written in . . C? C+? CKernelRun?

    --
    Your hair look like poop, Bob! - Wanker.
    1. Re:More Confusion by M51DPS · · Score: 5, Funny

      The kernel will be written in Java for more cross-platform compatibility.

    2. Re:More Confusion by Tumbleweed · · Score: 4, Funny

      CKernelRun?

      a) CKernelCrash
      b) CKernelPatchNotGetAcceptedByLinus

      One or the other, I'm sure.

    3. Re:More Confusion by aled · · Score: 3, Funny

      that's an exception:

      throw new ExceptionPatchNotAccepted("Linus");

      --

      "I think this line is mostly filler"
    4. Re:More Confusion by pyrrho · · Score: 2, Informative

      there can't be a distinction, C++ owes itself to an "improved C" mentality. C people can dissown C++ (except the parts that made it into ANSI C) but C++ people can't dissown C... and don't want to.

      --

      -pyrrho

    5. Re:More Confusion by pyrrho · · Score: 3, Insightful

      using C++ as a better C is the first step to enlightenment.

      Note: if you use ALL the techniques of C++ in your programs at the same time, then you are not a good programmer, period.

      --

      -pyrrho

    6. Re:More Confusion by torstenvl · · Score: 3, Insightful

      I struggled really hard with the choice to reply to your post or to use my mod points on this article.

      If your company refuses to hire people who refer to C/C++, then your company must not know what C++ is. If it did, it would a) Know that C++ is essentially a superset of C and therefore it is intelligent to make statements that apply to the dual entity referred to generally as "C/C++"; and b) You would have some kind of concept of class inclusion, and be able to understand that C and C++ are part of the same 'language family' -- it is therefore just as allowable to talk about C/C++ as it is to talk about 'Germanic' or 'Slavic' or 'Romance' or even 'Indo-European'.

      Such an overgeneralizing, bigoted, and asenine criterion is beyond all stupidity.

    7. Re:More Confusion by Anonymous Coward · · Score: 2, Insightful

      I must say, that's a really lame argument. std::string is part of the std library not the language (it is written in C++, not part of it). You appear to be confusing symantics with syntax, convention with legal.

    8. Re:More Confusion by tomstdenis · · Score: 2, Informative

      Well the major difference between C and C++ being that C++ supports "native" classes while in C you emulate them with arrays of stuctures.

      A class is a way of organizing "objects" in a hiarchical manner. You could almost say an OOP manner. The fact you can do more with C++ doesn't take away the fact that oop is the major difference. In fact I can't think of any other reason to use C++ over C aside from classes and the various forms of inheritance.

      The point is C didn't borrow what C++ had to offer not because the ISO C committee is lazy or incompetent but that C solves DIFFERENT problems.

      --
      Someday, I'll have a real sig.
    9. Re:More Confusion by I_Love_Pocky! · · Score: 5, Insightful
      In fact I can't think of any other reason to use C++ over C aside from classes and the various forms of inheritance.
      • Exception Handling
      • Function Overloading
      • Operator Overloading
      • New/Delete
      • Inline Comments
      • References (and pass by reference)
      • Others I'm sure
      C solves DIFFERENT problems.

      No, C solves problems differently.
    10. Re:More Confusion by I_Love_Pocky! · · Score: 3, Informative

      Your first three are part of OOP [hint: Java has them too]

      Sorry to break it to you pal, but you don't have to have classes to use these constructs, they work perfectly well with primitives and structs. Obviously they become much more useful in an OOP world, but they aren't part of OOP.

      pass-by-reference is not a programming methodlogy either... it's just a function of C++.

      No one said anything about programing methodologies. Your original post said:
      In fact I can't think of any other reasons to use C++ over C aside from classes and the various forms of inheritance.

      I just stated some language features available in C++ that aren't in C that are potential reason to use C++ over C (that aren't related to classes and inheritance).

    11. Re:More Confusion by frostfreek · · Score: 5, Funny

      And why not???

      With the GNU Compiler Collection able to generate machine code for Java, we'd be able to leverage all the things that Java excells at!
      Such as:



      umm....


      well,
      Oh forget it then.

    12. Re:More Confusion by cout · · Score: 4, Insightful

      C++ is not a superset of C. C++, C89, and C99 all share a common subset.

    13. Re:More Confusion by Viol8 · · Score: 4, Insightful

      Ah yes , but you can emulate most of that in C:

      "Exception Handling"

      setjmp(), longjmp()

      "Function Overloading"

      Function pointers

      "Operator overloading"

      Ok , you can't do this in C.

      "New/Delete"

      Its easy to create simple malloc()/free() wrapper functions.

      "Inline Comments"

      Eh? Whats stopping you doing /* waffle */ ?

      "References"

      These are hardly a selling point of C++ in my opinion. Implicit pass by address symantics should NEVER have been put in a modern language. Besides , after compilation they produce the same code as that using pointers.

      "Others I'm sure"

      Inheritance, templates etc. It just depends on how much you way syntatic clarity (C) against functional clarity (C++). Personally I think anyone who sticks religiously to either C or C++ without every using the other probably isn't a very competant programmer.

    14. Re:More Confusion by wtd · · Score: 2, Insightful

      Yes, you've aptly proved that it's possible to do many of the same things in C that you can in C++.

      However, the C++ way generally is more convenient, and I would go so far as to say that convenience, in the right measure, makes for better code. Rather than inventing your own wrappers for freeing memory, for instance, with "delete" all of that gets put into a destructor which can be easily found in any class that implements one.

      Obviously you can go overboard on syntax, but clearly if something becomes fundamental to the language, then there's a strong argument for adding syntax to support it, if only to prevent people from reinventing the wheel.

    15. Re:More Confusion by glyph42 · · Score: 4, Insightful

      "References"
      These are hardly a selling point of C++ in my opinion. Implicit pass by address symantics should NEVER have been put in a modern language.

      Are you joking? References are the ultimate syntactic way to say "don't mess with the pointer, just use the object". The fact that you can't do arithmetic on references, or delete references, or assign references, without casting them in various ways is exactly the kind of friendly reminder that helps prevent a large class of common pointer-related programmer errors.

      Besides, after compilation they produce the same code as that using pointers.

      So does asm.

      Anyhow, C has got issues. C++ added constructs to automate many aspects of modern programming, the point being to help reduce bugs by giving friendly syntactical shortcuts and reminders, and writing some of the code for you. It's not an issue of what can and cannot be done; it's more of a likelihood of programmer error thing. C++ has issues too, mostly because of various odd syntactic decisions that were made, several of which stem from trying to make it backwards-compatible. Some of it is plain ugly :) But it sure as heck puts bread on my table without stressing my brain too much.

      Now I find myself evaluating the new Java, and C#, which both add even more features and little reminders to programmers to avoid common programmer errors. D is not looking too shabby, though it doesn't have anything like the market strength of either new Java or C#. Personally I think they are all getting bloated, adding too many keywords and not simplifying and unifying things enough. Back in my university days me and a buddy started designing a language we called D-, but we stopped after we realized how much time it would take to actually make it happen. I still dabble with the design on my spare cycles. Maybe some day... just maybe...

      --
      Music speeds up when you yawn, but does not change pitch.
    16. Re:More Confusion by freqres · · Score: 2, Funny

      But the real question is, are any of those methods better than GOSUB ?

      --
      Rampant Ninja related crimes these days...Whitehouse is not the exception
    17. Re:More Confusion by joggle · · Score: 2, Interesting
      consts are especially helpful in reading complex C++ code (so long as there are no const_cast functions or too many mutable variables). It is a nice way of telling whether a parameter is strictly an 'in' or an 'inout/out' using CORBA parlance. Nearly all of the code I've ever seen has far too few comments so syntatic sugar like this can greatly speed up comprehension of what the code is doing. It also makes it easier to port the code (well, interface anyway) to more strictly defined languages (like CORBA IDL). How can it possibly obfuscate the code? (with the premise that const_cast and mutable variables aren't used in abundance, which is bad programming practice anyway)

      It can be a pain in the ass to consistently use consts (because member functions called on const parameters must be const functions which in turn must only call const member functions) but I've never heard any complaints about reading the code.

  3. C++? by Anonymous Coward · · Score: 5, Funny

    Good now I can fire up my good old visual basic and hack the kernal with COM.

    1. Re:C++? by npietraniec · · Score: 3, Funny

      and I was just thinking... I wonder how long until someone makes a "I want to use visual basic" comment. That didn't take long. hilarious.

    2. Re:C++? by FecesFlingingRhesus · · Score: 2, Funny

      No no one would ever want VB, now C# or java on the other hand.

    3. Re:C++? by Electroly · · Score: 2, Interesting

      Interestingly, the driver interface in Mac OS X actually is COM. With QueryInterface() and everything.

    4. Re:C++? by Kethinov · · Score: 2, Funny
      Imagine the enormity of newbie kernel hackers if such a thing were beieved to be possible...

      I can imagine a post to usenet now...
      Subject: this damn thing wont compile

      omg why are none of my win32 api calls working this sucks this will never be better than windows
      And the ensuing reply...
      Subject: Re: this damn thing won't compile

      Uh huh. Well. It won't compile because your api calls are, uhm, frozen. Yeah. You need to unfreeze them. There should be a blue liquid in the trunk of your car called antifreeze. If you drink it all, and I do mean all of it, you'll be able to unfreeze your api calls.

      Have fun.
      --
      You're right, I wouldn't steal a car. But if it were possible, I sure as hell would download one!
    5. Re:C++? by arkanes · · Score: 2, Interesting

      COM is a documented standard and as object models go it's not bad. Better than CORBA, anyway.

  4. Alright!! by 21chrisp · · Score: 5, Funny


    I'm sure the kernel developers will LOVE the idea of putting C++ in the kernel.

    1. Re:Alright!! by Bloater · · Score: 5, Insightful

      Why ever not? C++ allows for much better code, you just need a compiler that's up to the task, and runtime ABI that is predictable. Granted, standard C++ may not be appropriate, but with some features disallowed, it is ideal (better than C).

      All you need is policy that covers use of various features, just like the Linux kernel requires policy on use of C.

      multiple platform support becomes template specialisation, locking rules can actually be enforced by the language (ie, to get member functions to access an object, you can require that you call a member function to return a mutex object which has the members, and when that mutex is destroyed naturally, the lock is freed. fast, safe, secure.

      The question is how customisable is the compiler for how virtual functions, etc, are implemented. Those are the only issues to be concerned about because C++ is plain better than C.

    2. Re:Alright!! by metalogic · · Score: 5, Funny

      I see your ID isn't a coincidence.

    3. Re:Alright!! by Bloater · · Score: 4, Informative

      I think that deserved +1 Funny.

      Although the idea that C++ compiled object code is bloated is incorrect. It's normally either due to inexperience with the language or due to a poor compiler implementation. Part of the problem is that on old compilers, template instatiations were actually included once for every object file that refered to one. More recent compilers can identify and remove duplicates at link time, or can save templates in a separate file and link it in at the end of the build. (For some templates, though, you can actually be better off with one in each file if each file uses inline member functions, and each uses a different one).

      Sure C++ has it's faults, but bloatedness is not one of them - although a standard library may be bloated, but that's not an issue for the kernel.

    4. Re:Alright!! by Bloater · · Score: 3, Insightful

      That's why you have policy. Seriously, what if the locking order for a set of variables changes in C code? Non-deterministic behaviour.

      Any language only goes so far, the thing that determines whether a software development project succeeds or not is policy and attitude.

      For example, you can prevent changes in the apparent behaviour of the language by prohibiting operator overloading, template specialisation, and implicit constructors. Oh yeah, banning macros, which you also have the problem with in C.

      And you don't have to worry about unexpected exceptions, because even if you didn't try-catch, the compiler cleans up *all* your objects in *every* case and tells the function that called you that you failed, and "here's why". The only reason you need to know about exceptions being thrown is to clean up resources and data-structures - and that is done in the destructors for auto class variables, so no problem there.

    5. Re:Alright!! by strider44 · · Score: 2, Funny

      mmm, C++ is way too bloated - the binary code that it produces is horrible. In fact, when you think about it, not even C gives the best possible optimised code - you're wasting a whole 0.001% optimization! They should go backwards, not forwards! They should go for the best possible optimization - Assembly all the way! Just think about the extra microseconds saved - it's a linux hacker's wet dream!

    6. Re:Alright!! by orst_sw_engr · · Score: 2, Interesting

      Have you ever debugged at the kernel (protected) level?

      C++ is best avoided at the kernel because of implicate nature of the language. Bugs are harder to find in C++. When an exception occurs, the whole machine must rebooted.

      If you want try this for yourself, just take any amount of code you are working with and every time an exception occurs restart your computer and wait. See how much work you get done.

      Also, while at the kernel mode you must be aware of the whole machine's state including IRQ level, virtual memory, entry context, what IRQs can preempt, and a slough of other details. In user mode you can rely of the state of the machine being fairly stable. However, I would agree that large multi-tiered have many network states that make user mode programming complicated. I have worked in these environments as well.

      Further, you still can write object-orientated code in C if necessary. It just requires the C programmer to manually manipulate the v-table which they create themselves. I have done this. You can do it in ASM too with structs of jump tables.

      Someday C++ will make it into kernel programming, but I think it would be start in a micro-kernel, which is easier to debug.

    7. Re:Alright!! by orst_sw_engr · · Score: 2, Insightful

      I don't mean to be too hard, but I feel I have to bring a different prospective.

      Macros in C are used for readability and easily debugged. All you have to do is grep for the #define.

      The locking order in C code? THERE IS NO LOCKING ORDER. You have to explicitly mange these aspects in C and anyone can immediately determine it from looking at the code.

      Your explanation of memory management within the kernel is at best naive. What if the code is called within a context that is higher (or the same) IRQ level as the VM pager? There is no heap! There is only a small amount of non-paged memory that had to allocated ahead of time and the very limited kernel stack.

      And your notion of what an exception is (in both user mode and kernel mode) is beyond naive. Exceptions can happen for any number of reasons. Simply catching them and cleaning up may not be sufficient. Maintaining an understood state for the rest of the system is the proper course of action. In a network application it may require invalidating a cache to avoid data corruption, or in a kernel routine setting up an I/O request to be handled at a lower IRQ level. Do you propose having all this in the destructor?

      Sure you can randomly clean up everything you can think of, return to the caller, and hope everything works, but in the kernel an unknown exception results in an inevitable reboot. And on a clustered network -- data loss.

    8. Re:Alright!! by Bloater · · Score: 3, Interesting

      Yes, I have debugged at the kernel level, written a boot loader, switched to protected mode inluding operating the GDT, IDT, page tables, vga registers. written a VGA terminal, etc... I am familiar with x86 assembler, C and C++.

      When an exception occurs, it must be caught and handled correctly (or propagated if that is appropriate) - just the same as a C error code returned from a function, so no loss there. As an advantage, an exception follows a distinct error path back up the stack frames so an error code is *never* treated like a value - which can spell a horrible death for both your uptime and data.

      Within a syscall in process context, an uncaught exception will propagate up and up and up until it reaches a catchall at the syscall entrypoint, which can return an error to user-space without *any* harm to the kernel (provided the code is structured not to leave inconsistent state - but you have precisely the same issue in C, and C++ exceptions actually make it *easy* to clean up the state as you fall back through the stack frames).

      Within a hardirq handler, the interrupt vector points to a similar catchall - the issue here is that timer interrupts (until the scheduler becomes tickless) and interrupts notifying of readiness by hardware can be missed, but only if you haven't handed off to a softirq or queued data for processing by a kernel thread. The C symptom of incorrect code is again different - the code carries on with incorrect data and balls' everything up in C, in C++ it gives up and leaves everything in a good state - unless the hardware *requires* servicing, but then your code simply has to be correct whatever language it is.

      Within a kernel thread, the entry function will have a catchall that kills the thread and a monitor waiting for it's death can see it, log it and restart. Or you can write the code correctly as you have to with the C version (because if you write incorrect C code, the code carries on with bad data and balls' everything up).

      So C++ can actually make the system *more* robust, not less. In particular - the raising of an exception does not kill the system except for rare cases where the calling function *also* doesn't bother to catch errors - and then some bug in a destructor prevents returning the state to how it was ! Which will kill your system in C too (or worse - corrupt data which is *far* less likely with exceptions).

      C code has the added policy issue of clearing up resources on error. Since you often have at least two return paths, resource release code *must* be put into each and synchronised. This is precisely what exceptions do best - automatically nonetheless.

    9. Re:Alright!! by maxwell+demon · · Score: 3, Insightful
      Because C++ makes your program less deterministic.
      C++ programs are as deterministic as any other computer program. Unless you have undefined behaviour (line uninitialized variables or dereferencing dead pointers), a C++ program always produces the same output for the same input.
      By looking at a piece of code, you can't say what happens where if you use C++.
      Yes, you can. Of course you must know the definitions of the entities used in your code, but that is true in C as well. Example:
      foo (*bar) (baz);
      Now, does this line
      • define bar to be a pointer to function taking type baz and returning type foo, or
      • call function foo on the value you get by dereferencing pointer bar, and then call the function to which the pointer to function returned by foo points on the value baz, or maybe
      • expand the macro foo (*bar), which results in a construct which followed by (baz); gives some valid C code which could do just anything?
      Note that even without macros, there are already two possibilities. Now, C++ adds mode possibilities, but that's only a quantitative change, not a qualitative one.
      During every single instruction, an (unexpected?) exception might take place,
      Nonsense. Exceptions can only take place at well defined places (the only way to get an exception is to write "throw xy", either directly or through called code). And if that exception is unexpected, then either the used library is buggy, or badly documented, or you just didn't read the documentation.
      and every single instruction might be changed from what the author has intended (and tested) when somebody changed the definitions of what those methods were inherited from.

      That's wrong, too. There is no way you can change the meaning of e.g. int i=3+4; in C++. Of course there are things where you can change the meaning, but that's no different to the following statement about C: "every function call might be changed from what the author has intended (and tested) when somebody changed the definitions of what that function calls."

      Clearly if anything you inherit from changes semantics, then this is a break of interface, just as changing semantics of a function is a break of interface. You shouldn't be surprised that if you use a library which does not conform to the specification your program expects then your program breaks. That's independent from language, coding style, programming paradigm, it's even independent from programming (e.g. if you think "moron" is something positive, then telling someone a moron will surely not have the effect you expected).

      --
      The Tao of math: The numbers you can count are not the real numbers.
    10. Re:Alright!! by Bloater · · Score: 4, Interesting

      Macros are not always easily debugged, identifiers can be replaced wholesale by #defining it, but not *before* the define, so the header that defines a static variable parses fine, then you include a header from another part of the kernel, then you use the identifer. In the next version of the kernel somebody #defines the identifier you are using within the second header.

      This breaks, and is very hard to debug by code inspection or by kdb. It is resolved by policy ensuring that the namespace for symbols/types/structs doesn't meet with the namespace for preprocessor macro's except for possibly a few agreed core macro's.

      And it is similar policy that keeps C++ code safe.

      Regarding your comment on the locking order. You make my point very well, in C, you have to manage locking order *at*every*call*point*, in C++ you can manage it where the locks are defined. So you make rules like lock A cannot be taken if lock B is already held. In C you have to make this just policy, in C++ you can do some neat code for these cases )though I'm not going to think it through now) that, depending on situation will BUG at runtime or even flat out refuse to compile. And to the user at the call point, it's just a lock.

      As to memory management, I didn't explain memory management in the kernel, so I don't understand how I could have explained it naively. There is not just a small amount of non-paged memory allocated ahead of time. Anytime you need to be able to handle an error, you ensure (before the error can occur) that you have memory in which you can store intermediate data in the process of handling the error - otherwise you are dead in the water. Other than that, memory can be allocated within the kernel via a number of means, including kmalloc and the slab allocator. As to IRQ levels, I have an old first year OS and hardware architecture design textbook that discusses them (by a different name - so I could be misunderstanding what you mean), but that is in non-monolithic designs. I am not familiar with whether allocation is permitted in hard IRQ context in Linux or, if it is, by which of the available mechanisms, but if it is not permitted the hardirq *must* have the memory available to handle the error - whether it is C or C++. Throwing an exception in C++ does not require using any memory: in throw SomeException(blah), sizeof SomeException can be 0, and it can store it's information in the preallocated memory for that instance of the IRQ handler (which can of course be an object). If the C++ implementation doesn't allocate memory that it needs for trundling up the stack ahead of time then that is a Quality of Implementation issue, and different exception handling code is required but C++ is still acceptable.

      And my notion of an exception is not naive at all. In well written code, when an exception is caught all objects in the try block are destroyed, and the data they represent goes with them so the destructor *does* whatever else is required for the state and change of state that it stands for. In C you have no choice but to try to remember everything in each error case (or use goto's to the one place - but then that's just like a low-feature exception with no compiler support for enforcing policy). Maintaining an understood state for the system is done by encapsulating things in objects and using destructors to handle keeping everything consistent.

      All cleanup due to error occurs in one or both of two places: The destructors and the catch blocks. Mostly in the destructors. And you don't *randomly* clean up everything you can think of in C++, that's what you do in C. In C++ you rigourously clean up everything, whether you could think of it or not, because the compiler knows it's there. In the kernel an unknown error )whether by exception in C++, or error code in C) *must* be understood or passed on up the call stack until either something knows what to do, or the whole operation is abandoned for better or worse. In C, that is a lot of work and checking everything, in C++ it's virtually guaranteed.

    11. Re:Alright!! by orst_sw_engr · · Score: 2, Interesting

      Well I made two posts and I appreciate your well-written, civil replies. Sorry for using the word naive.

      True, looking at your original post I am not sure where memory management came into play so I will not harp on it too much. I will point out that the pager works at a low interrupt (which makes sense because disk i/o is required and if it was higher it could preempt threads that don't expect memory moved on them). If a higher interrupt is being serviced it will not have access to virtual memory. Memory simply cannot be created at this level. You are right about the guarantee - for exceptions, the stack is easiest to use. You also right about throwing a primitive in C++ -- it uses no memory.

      I agree that SEH (Structured Exception Handling) has its place in the kernel. As a matter of fact, NT has always had this built into its C compiler. (I actually already made reference to this in a post below.) It even has a finally block for cleanup like you are describing (kind of like a destructor). I have found this feature indispensable. So we both agree this is a good feature.

      BUT! I take issue with most other C++ features which I *love* in user mode, but would be a pain to debug in kernel mode. Interestingly I have done some from polymorphism in the kernel by building my own objects with a variant function table. I find this easier to debug while working in the kernel, but in user mode I would never dream of wasting my time doing this myself.

      As far as defines... I guess I have gotten so use to them; they don't bother me. I can track down the symbol.

      When it comes to C++ for me, it is not the system itself. It is the time it takes to debug it. User mode has much better tools for debug C++. Maybe that is the problem.

      You can have the last word. I am done with this subject.

      Oh, I would like to add one thing the system wide catch on NT is the BSOD.

    12. Re:Alright!! by a_hofmann · · Score: 2, Interesting

      You are absolutely correct that the main problems with compiled C++ lie in the current implementations. But this is a pretty theoretical thing to say, as I don't see this getting much better in near future. C++ compilers have only recently reached a level of full standard compliance, and optimization is surely not yet on par with the things possible for C compilers. C++ is a more complicated language which means it is more difficult to optimize for the compiler, and it is probably not ever possible to optimize to a level that can be reached for C or simpler languages.

      As an example, Windows has a modified microkernel architecture and is a (non-pure) object oriented operating system, so by design it would be logical to implement this in an object oriented language. Still it is no coincidence that most parts of it are written in assembler and C - you just cannot afford to waste percentages of performance for critical kernel sections because of the choice of language, which is not avoidable either, no matter how well you use C++ or optimize with the compiler. And unfortunately most kernel sections are pretty performance critical...

      Btw note that I talk about problems occuring when using the full range of C++ features that make it the beautiful language it is... I ofter hear people talking about C++ matching C performance, but when you look under the hood they are basically using C with some syntactic sugar. This is not of much use, as such designs can be (and are) mostly implemented in C in the same fashion either, as e.g. the object orientism of the Windows kernel I spoke of.

  5. Re:so... by yecrom2 · · Score: 2, Insightful

    for us non-developers, this means what?

    Not a dang thing.

  6. Yay! by stonecypher · · Score: 3, Insightful

    It's about fucking time. Now maybe we're on the path to a bullet for killing those shallow arguments about C++ somehow being majorly slower than C, as opposed to people just not knowing the costs of C++ features.

    --
    StoneCypher is Full of BS
    1. Re:Yay! by apankrat · · Score: 5, Informative

      It's not the slowliness, it's the obscuirty and the lack of control over the binary code size it introduces. Something as simple as 'a == b' may easily add few KB to the kernel.

      If you think it's OK, you obviously haven't been involved in kernel or embedded development. If you say one should be careful what features of C++ he uses and not to use this and that, I say one should learn proper C skills instead.

      --
      3.243F6A8885A308D313
    2. Re:Yay! by Lally+Singh · · Score: 5, Insightful

      Embedded dev is now often C++ based. It's all about making sure you have devs who have a clue.

      Anyone writing a == b should notice that a & b aren't primitive types.

      --
      Care about electronic freedom? Consider donating to the EFF!
    3. Re:Yay! by SpaceLifeForm · · Score: 2, Insightful
      It doesn't matter if the developers have a clue. Linus has repeatedly said no.

      Go fork your own kernel then. Good luck.

      --
      You are being MICROattacked, from various angles, in a SOFT manner.
    4. Re:Yay! by Frizzle+Fry · · Score: 3, Insightful
      Something as simple as 'a == b' may easily add few KB to the kernel.

      Only if you've overloaded operator==. But in that case, this is just a function call. A function call in C could just as easily add a few KB. The only difference between the languages here is that C++ gives you the "syntactic sugar" option of creating functions with the same names as operators. You can choose not to do that if you perfer and just use a regular function name, as in C. In no way does the ability to create a function named "==" instead of "Equals" show any more "lack of control" over code size than in C (exceptions might have been a better example).
      --
      I'd rather be lucky than good.
    5. Re:Yay! by apankrat · · Score: 2, Funny

      Assuming you are looking at integer_t type, is it primitive ?
      Made you look in header :-p

      Agreed about developers though, however the number of
      those who have a clue is drastically lower than those
      who think they have a clue. Everyone's a freaking C++
      senior these days.

      --
      3.243F6A8885A308D313
    6. Re:Yay! by myg · · Score: 5, Informative

      I'm an embedded developer. I've done some projects as C only and some as C++. With proper discipline C++ can actually generate smaller, more compact code than straight C. But getting the infrastructure done is a bit harder.

      In fact, eCos, a very nice (GPL) embedded operating system has its kernel written in C++. eCos performs well and is cleaner than a competing straight C RTOS which has to build its object system by hand (VxWorks' WIND kernel).

      The real difficulty in using C++ for embedded development comes from the toolchains themselvs. Frequently new processor architectures don't have very functional C++ back ends but C is somewhat stable.

      In fact, I worked on porting some C++ TV middleware to a specialized "media DSP processor." The GCC back-end for C was rock solid but C++ constructs would give me constant ICEs.

      C++ does fix some dumb things in C, but when it comes to shooting yourself in the foot, C++ is like an AK-47 while C is more like a .38 special.

    7. Re:Yay! by Martin+Blank · · Score: 2, Funny

      C++ does fix some dumb things in C, but when it comes to shooting yourself in the foot, C++ is like an AK-47 while C is more like a .38 special.

      This should be good news to the NRA's development division...

      --
      You can never go home again... but I guess you can shop there.
    8. Re:Yay! by bobv-pillars-net · · Score: 4, Insightful
      Go fork your own kernel then. Good luck.

      Unless I misunderstood when I RTFA, that is exactly what the authors intend to do. And I, too, would like to wish them "Good luck." Linus obviously believes that C++ in the kernel is undesirable, but we'll never find out for sure until somebody like these people have the guts to actually try it, and the persistence to maintain a current patchset (or fork) long enough for the idea to catch on.

      --
      The Web is like Usenet, but
      the elephants are untrained.
  7. Exceptions are suddenly viable? by gbjbaanb · · Score: 2, Insightful

    oh dear, again someone who doesnt; understand that exceptiosn are designed never to be thrown. If they were everyday occurrences, then they wouldn't be, well, exceptional.

    Unlike some languages who use exceptions for events that you expect (like End-of-file) and poor programmers who think that because they're there, they must be used all the time, for everything, exceptions are a defensive programming measure to ensure that the things that should never, ever happen, are handled gracefully if they do.

    1. Re:Exceptions are suddenly viable? by Lally+Singh · · Score: 2, Informative

      exceptions are a great way to structure your error handling.
      they're an in-language mechanism similar to signals, only that they don't have the brain-deadedness of them.

      Hell, just having smart pointers whose destructors are properly called on the stack unwind is enough.

      --
      Care about electronic freedom? Consider donating to the EFF!
    2. Re:Exceptions are suddenly viable? by BCoates · · Score: 2, Informative

      I think that's a bit backwards; ordinary user applications can just terminate ungracefully, and the kernel will clean up after them (close all open files, free memory, etc) if a section of kernel code runs into a problem, it has to roll back everything to a sane state before returning to the caller if there's going to be any hope for the entire kernel to keep going (without leaking). I believe right now the linux kernel mostly does this with an elaborate system of gotos and return value checking that's pretty much exactly what C++ stack-unwinding does, just by hand.

    3. Re:Exceptions are suddenly viable? by Lally+Singh · · Score: 4, Informative

      Nope. It's a condition that the throwing code couldn't handle. Someone else can handle it.

      Classic example: a method calls another that calls another that calls openfile() for a temp file, which fails. the lower two methods don't care, and the toplevel one can give the user a proper error message and clean up.

      People wonder why software is so hard to test, does so poorly on error handling, yet complain whenever we add mechanisms to languages to help.

      --
      Care about electronic freedom? Consider donating to the EFF!
    4. Re:Exceptions are suddenly viable? by cout · · Score: 4, Informative

      Oh dear. Another person who thinks that exceptions should never be thrown.

      If exceptions were never meant to be thrown, they wouldn't be in the language. Exceptions are an abstraction for dealing with exceptional conditions -- conditions that do not normally occur, but can occur. At the expense of some additional complexity, they make error checking a little simpler and less bug-prone. When (not if -- assuming you are a believer in Murphy's law) those exceptional conditions occur, your program better be able to handle them correctly.

      You are right that some people do use exceptions when not appropriate. Exceptions are (generally) not appropriate for exiting loops, for example. But they are more than appropriate for out of memory conditions, out of disk space conditions, etc.

      The reason they are not viable performance-wise is not because they are too expensive to throw; it is because they are too expensive when they are never thrown at all. There's generally a 5-10% performance hit just from having code that might possibly throw an exception, depending on your compiler's implementation. The numbers on the netlab page are for throwing exceptions, unfortunately; I would be interested in seeing if they got a performance benefit when exceptions are not thrown. Guess I'll have to dig to find a copy of the paper.

    5. Re:Exceptions are suddenly viable? by slashdot.org · · Score: 2, Interesting

      oh dear, again someone who doesnt; understand that exceptiosn are designed never to be thrown.

      It's ridiculous that this comment is modded up to +5 Insightful.

      Would you care to back up this claim with something tangible?

      Of course the word 'never' is totally inappropriate since by definition exceptions _are_ designed to be thrown.

      The only valid thing in your comment is that certain programmers over-use exceptions. Then again, certain programmers also do stuff like #define forever for(;;). That to me is over-using #define. So should we rip the pre-processor out of the compiler because certain programmers use #define in a way that you don't fancy?

      Exceptions are extremely useful to write clean code with proper error handling. The truth is that because handing error conditions with return values is cumbersome and ugly, people often just don't implement error handling. Great.

      If they were everyday occurrences, then they wouldn't be, well, exceptional.

      I think it's perfectly normal and acceptable to have an exception be an everyday occurrence. There's nothing magical about exceptions that would justify saying that they should never be used. Sure, throwing an exception is a lot of overhead. So TF what? If you only do it in exceptional situations...

      To me the word 'exception' means to me, anything that happens that's not in the normal code path. The standard software flow should not use exceptions, but anything else is, well, exceptional.

    6. Re:Exceptions are suddenly viable? by Lally+Singh · · Score: 2, Informative

      if it matters which part of the code had the error, then use separate try blocks for each part. In real life, most exception handling code DOESN'T care which function called it, or can tell from the exception type. As we've got more expressiveness than the value for ERRNO, we can do that here.

      --
      Care about electronic freedom? Consider donating to the EFF!
    7. Re:Exceptions are suddenly viable? by Anonymous+Brave+Guy · · Score: 3, Interesting
      There's generally a 5-10% performance hit just from having code that might possibly throw an exception, depending on your compiler's implementation.

      FWIW, I believe modern compilers now approach the zero-overhead ideal for exceptions when they aren't thrown, and have done for a little time now. Several people directly involved have posted to this effect on the major C++ newsgroups in the past.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    8. Re:Exceptions are suddenly viable? by BCoates · · Score: 3, Insightful
      try
      do_foo()
      do_next_foo()
      do_foo3()//continue on here for 10 lines
      catch a //handle a
      catch b //handle b ...
      Why are you doing this, if you want to handle errors where they happen? Why not:
      try
      do_foo()
      catch a
      // handle a right when it happens
      if (unfixable)
      throw; // rethrow (or throw something else with throw x;)
      try
      do_next_foo()
      catch b
      // handle b right when it happens
      // etc...
      The equivalent of your error-return based code. Of course, in the real world, most exceptions don't need to be caught explictly as the only error-handling code is resource cleanup or rolling-back half-complete operations, for which you aught to be using destructors. That's where exceptions are more useful than just an arcane alternate syntax for doing the same thing.

      You can senselessly dump all your error handling code in the middle of nowhere using return-value error codes, too, if you really want to.
    9. Re:Exceptions are suddenly viable? by Beatlebum · · Score: 2, Informative

      You're confusing exceptions with assertions. Exceptions can be used to elegantly handle boundary conditions. Assertions flag events that should never happen *if* the code logic is correct. Exceptions stay in both debug and release builds, assertions are not usually compiled into release binaries.

    10. Re:Exceptions are suddenly viable? by arkanes · · Score: 3, Insightful
      It also doesn't help the following case- you read in 4 bytes from a file, then read in a variable number of bytes based on the last read. You get a read exception. Which read failed?

      The whole point of exceptions is that you don't care. If you care about each specific read, you wrap each read in it's own block (the same as error conditions, except that you'd use an if block).

      Whats the state of all your objects?

      This is why object-oriented C++ is so wonderful and Java is so bad - your objects are automagically in the correct state because you allocate and clean up resources in thier destructors. If an object is in scope, it's in a clean state. If it's not in scope, it's not. You can write some really concise, clean, reliable code using this concept - it's where the true power of objects comes into play. In C, you have to manually check EVERY call and clean up EVERY resource - it's very susceptible to programmer error, especially in deeply nested call chains with gotos and whatnot all over the place (like the Linux kernel, for example). In Java, which doesn't have destructors, it's even worse because you've got exceptions with no automatic cleanup, which means you've got to have all sorts of ugly nested try/catch/finally and state management.

      Exceptions are a nice way of dealing with problems, especially nested calls. But combined with destructors, they're a magnificent way of keeping error handling safe.

      People use goto in C because they want a nice exit point in the case of failure. People use exceptions for exactly the same reason - it simplifies error handling. It's true that it's physically seperate from the code, but on the other hand it's within the same block so you've got a visual/indendation indication at least. If you think exceptions are a maintainers nightmare, then you've never tried to fix an error in a function with 40 different exit points, with almost identical cleanup code at every point. A C programmer would use a goto so that there's not so much duplicate code and it's easier to maintain. A C++ programmer would use exceptions and automatic objects to do exactly the same thing, in roughly the same lines of code, with with even less (quite possible 0) duplicate code and greater modularity.

    11. Re:Exceptions are suddenly viable? by arkanes · · Score: 2, Informative

      Exactly. Here's an example of poor use of exceptions:

      try {
      while (1) {
      read_from_file();
      }
      } catch (EOFException) {
      clean_up_file();
      }

      This is bad because you're using an exception to manage normal program flow. Here's a better use of exceptions:

      try {
      File f("myfile"); //file object manages state
      while (!f.eof()) {
      f.read();
      }
      } catch (FileOpenException) {
      //file object is cleaned up by it's
      //destructor, only thing we need to do is
      //alert user
      }

      This is a simplistic case, because you can just easily do this by checking error codes. It shows it's worth when you have, say, a dozen different files to open. You save a lot of if-checks, a lot of duplicate error handling (alerting the user and returning), and you don't have to worry about manually closing all the files which might be open, preventing resource leaks. If your exception system is properly designed, you don't lose any information, because stuff like the file you were trying to open is preserved with the exception information.

    12. Re:Exceptions are suddenly viable? by dgatwood · · Score: 4, Insightful
      Exceptions have no place in the kernel. Mac OS X uses C++ in its kernel. Two things are notably omitted: multiple inheritance and exceptions. A lot of thought went into that decisiion, and I didn't come in until shortly thereafter, so I mostly know the fallout of that decision, but... it was defininitely the right decision.

      Exceptions in the kernel are inherently a bad idea. An uncaught exception is a kernel panic. By contrast, an unknown error return is still an error, and usually the right thing happens. The risk of allowing exceptions in the kernel far outweighs any possible benefit. That's why nearly every kernel that has ever used C++ at any level has explicitly excluded exceptions. (That and the very nature of exceptions inherently results in worse performance than using error returns. In the kernel, performance is far more important than facilitating programmer laziness. :-)

      It would be wise for the Linux community to learn from other OSes that have tried to do kernel exceptions. Even the Windows kernel developers rejected them as a bad idea. Don't do it. Don't accept any patch that allows it.

      --

      Check out my sci-fi/humor trilogy at PatriotsBooks.

    13. Re:Exceptions are suddenly viable? by Tony+Hoyle · · Score: 2, Insightful

      I first came across the widespread use of exceptions in COM with ADO code. They really pissed me off - something deep within ADO (usually nothing to do with me) would throw an exception and a random other part of my program would fall over with *no* indication of where the error came from (it didn't help that this was in the VC6 days and the exception handling was nonfunctional - it trashed the stack so you could never recover.. you had just enough time to put up a dialog before your program was doomed).

      I ended up having to rewrite the com_error object so it traced out a message with the location of the actual error... much later on I worked out how to stop it being thrown in the first place & to return the documented error codes.

      That's the real problem with them - unless you have a catch() after nearly every statement it's basically impossible to work out what went wrong - 'File Not Found' - which file? which function? Why, exactly?

      I totally disagree that you mostly don't care where the error was thrown. I *do* care, because I have to fix it. Maybe the end user doesn't care, but even then I want the code to generate an error report that tells me where to look.

    14. Re:Exceptions are suddenly viable? by multipartmixed · · Score: 3, Insightful

      > So why can't openfile() simply return NULL?
      > Obviously an unsuccessful operation.

      Well, you want to communicate back to the higher level code *why* the call failed.

      Oh, wait, no problem!

      Well set a global variable called errno.

      Oh yes, and scratch our heads for a seeming eternity while we figure out exactly how to virtualize different errnos for each thread.

      And hope to hell that no failing system calls get called between when we failed and when the user checks errno.

      Rock on!

      --

      Do daemons dream of electric sleep()?
    15. Re:Exceptions are suddenly viable? by shadowmatter · · Score: 3, Funny

      Even the Windows kernel developers rejected them as a bad idea.

      MS Developer #1: I was thinking we could put exceptions in the kernel.
      MS Developer #2: Are you insane? Why on earth would you want to do that? I don't think I've heard a stupider suggestion for a kernel addition.
      MS Developer #1: Really? Well uhh... how about we put an Internet browser in the kernel?
      MS Developer #2: FREAKIN BRILLIANT, let me call Bill.

      - sm

    16. Re:Exceptions are suddenly viable? by cout · · Score: 2, Insightful

      An uncaught exception is a kernel panic. By contrast, an unknown error return is still an error, and usually the right thing happens.

      An uncaught exception results in a call to unexpected(), which by default calls std::terminate(). This behavior can be overridden using std::set_unexpected() to, for example, return an unknown error to the caller of the currently executing system call.

    17. Re:Exceptions are suddenly viable? by Lord+of+the+Fries · · Score: 2, Interesting

      This is very interesting to me. I'm reading this as a novice kernel programmer, but an adept application level programmer with a variety of OO languages used (Smalltalk, C++, OCAML, Objective-C, CLOS). I have to say... C++ is by far the worst realization of the ideals behind OO that I am aware of. That's beside the point though, what I guess I find interesting, is why didn't Apple choose to inject some Objective-C into the kernel (a much better C-OO hybrid). I was not aware they used C++ in the kernel before your post.

      --
      One man's pink plane is another man's blue plane.
    18. Re:Exceptions are suddenly viable? by Old+Wolf · · Score: 2, Interesting

      Firstly let me say that I'm not a kernel programmer, and I respect the fact that you have decided against using exceptions. However I'd like to attack your arguments anyway, based on my (limited) point of view, so if you could correct me then that would be good.

      The article said that they had modified exception handling to make it efficient time-wise, so the complaint that it's slower than using error returns no longer applies. (Recall that exceptions only should be thrown in exceptional circumstances, not as an expected part of processing; and exceptional circumstances will usually include some handling such as printk() which they noted takes an order of magnitude more time to run than the process of propagating an exception).

      So let's return to your main point: the risk of an uncaught exception causing a kernel panic is too high.
      (BTW how is this different to the risk of a divide by zero causing a kernel panic in C ? )

      I'd like to make a 'case study': accessing the elements of a std::vector. If you're unfamiliar, then writing:
      v[n]
      is equivalent to using that syntax on an array of ints. However, writing:
      v.at(n)
      is equivalent to writing in C:
      if (n > v_size)
      return some_error_code;
      v[n]
      and then having handling in the caller function for the possibility of that error. Much more concise, don't you think? Especially if you have
      several of these accesses in one expression.

      (Presumably the 'n' would come from some external source that is expected to be in bounds but occasionally may not be. )

      So you have reduced code complexity by not having to do a manual bounds check everywhere. You have no added runtime overhead in the case of the value being in range.
      Also, the case of the uncaught exception is just as bad as the case of an out-of-range array access -- maybe even worse, as it will take longer to find the bug.
      And perhaps the most important: you have the flexibility of being able to put the error handling code at a higher level than just the parent function. In the cause of the completely uncaught exception, at least you have the exception error message to indicate exactly what went wrong. If the kernel crashes from an out-of-range array access you may have no idea what went wrong, especially if it is in a tricky bit to use a debugger.

    19. Re:Exceptions are suddenly viable? by drawfour · · Score: 2, Interesting

      That's what pointers are for. Instead of:
      FILE *fp = fopen("foo.txt");

      why not use something like a return code for errors and out parameters of the functions. No globals, no worries about catching exceptions, you just return an HRESULT.

      HRESULT hr = S_OK;
      FILE *fp = NULL;
      hr = FileOpen("foo.txt", &fp);
      if (FAILED(hr)) ...

      This is NOT that hard. Plus HRESULTs can be easily propagated down, and ANYONE can act on a failure if he desires with or without knowing what the failure is.

      If you use exception handling the way it's supposed to be, you catch OBJECTS and not the wonderful catch-all of "...". The problem with using the catch-all of "..." is that truly BAD events like stack overflows are caught. And if you do not know how to recover from a stack overflow, you better abort the program immediately.

      But if you DON'T use the "..." form, and you don't know of ALL types of exceptions that can be thrown... well, one will slip by you and a regular "exception" will just kill your process since it's not handled. I MUCH prefer HRESULTs to handle known and unknown errors. Let a truly bad exception kill my program, and let me handle return codes.

    20. Re:Exceptions are suddenly viable? by Carewolf · · Score: 2, Informative

      What he is saying is that exceptions should only be used as runtime assertions.

  8. Stillborn. Seriously by apankrat · · Score: 3, Funny

    Java on other hand ...

    Or better yet - Brainf*ck, my personal favourite :)

    --
    3.243F6A8885A308D313
  9. Great news, I hop by Anonymous Coward · · Score: 4, Interesting

    That's really awesome news, but I just can't imagine it being accepted in the mainline branch. Many figureheads in the linux kernel group are anti-C++ enough to probably veto this effort. (If "anti" is too strong, then at least I'll safely claim they're not "pro C++".)

    It'd sure be nice though...

  10. full article text, just in case by Anonymous Coward · · Score: 2, Informative

    C++ in the Linux Kernel

    We have implemented a complete kernel level run-time support for C++ in the Linux kernel. In particular our run-time support enables the full use of C++ exceptions in the Linux kernel, but notably also includes support for global constructors and destructors, and dynamic type checking. Our kernel level support is based on open source commodity components, specifically the GNU gcc/g++ compiler and its exception implementation, the C++ ABI version independent standard interface.
    C++ runtime support for 2.6.6 (Last update 27 october 2004)
    C++ runtime support for 2.6.9 (Last update 27 october 2004)

    Using the C++ runtime support for Linux
    Installing the C++ runtime support for Linux

    The code is installed by applying a patch to the Linux kernel and enables the full use of C++ using the GNU g++ compiler. Programmers that have used C++ in Linux kernel modules have primarily been using classes and virtual functions, but not global constructors. dynamic type checking and exceptions. Using even this small part of C++ requires each programmer to write some supporting routines. Using the rest of C++ includes porting the C++ ABI that accompanies GNU g++ to the Linux kernel, and to enable global constructors and destructors.

    The implementation of the C++ ABI is based on the implementation provided with the source of the GNU g++ compiler. We modified it to run in kernel space, and performed optimizations that reduces the cost of exceptions and dynamic cast considerably. Our paper contains thorough explanations of these optimizations. The cost of throwing an exception one level on a 990 MHz Intel Pentium is around 12-13 micro seconds in the plain GNU g++ implementation, which we reduced to 2.1 micro seconds by modifying the runtime library, including unwinding the stack in one phase, and caching information on exception paths. In contrast the cost of a trivial printk operation -- printk("Error\n") -- is 18 micro seconds.

    In addition, we modified the linux kernel module loader to handle C++ weak symbols correctly. GNU g++ associates with each class a type information object that encodes the type of the class as a mangled string and puts a pointer to this object in the virtual table for the class. GNU g++ uses weak symbols to reduce the dynamic type checking to a pointer comparison, thus avoiding the more expensive string comparison. Each time a class, containing virtual functions, is used in a source file, GNU g++ generates the virtual table, type information object and type name string as weak symbols and the user space linker ensures that there is only one copy of this object, which renders the simple pointer comparison sufficient. However, the kernel module loader, which in the 2.6 versions of the kernel is exclusively in kernel space, does not handle these weak symbols correctly and always relocates references to weak symbols to the weak definition within each object file that is being loaded. Therefore multiple type information objects may exist for the same class and pointer comparison becomes insufficient when doing dynamic type check across kernel modules. To avoid this overhead we have modified the kernel module loader to handle these weak symbols; the first time a weak symbol is encountered it is added to the symbol map, and on subsequent encounters the relocation is done to the first symbol.

    Paper:
    Exceptional Kernel: Using C++ exceptions in the Linux kernel
    Halldor Isak Gylfason, Gisli Hjalmtysson
    Submitted for publication October 2004 abstract

    Please direct bug reports, questions and comments to {halldorisak at ru dot is}

  11. RMS by zoeith · · Score: 5, Funny

    RMS is probably turning over in his grave... oH! wait he's not dead!

    --
    Zoeith
    1. Re:RMS by IntergalacticWalrus · · Score: 3, Funny

      ...yet.

  12. Progress by caseih · · Score: 4, Interesting

    Say what you will about C++ being slower and more bloated than C, but I think this is a huge leap forward. I doubt Linus will accept it anytime soon as an official patch, though. If they have succeeded in making exceptions quick, I think C++ has a real place in the kernel. C++ offers the ability to have better type safety and more modular apis and interfaces to the kernel. For example being able to develop a new device driver inheriting from a nice base class is a good idea.

    Anyway, this is a neat hack and I look forward to seeing what comes of it.

    1. Re:Progress by alienw · · Score: 4, Informative

      Nothing will come out of it, for the simple reason that C++ does not belong in any kernel. In a kernel, all the code needs to be transparent, and you definitely don't want to hide implementation and the usual abstractions.

      The simple reason for that is that otherwise the kernel would be unpredictable. Let's say the error logging function used the string class (which likes to allocate memory behind your back). If the memory allocation function fails and tries to print an error message... you got yourself a kernel crash. This is why the kernel is significantly more difficult to program than, say, a word processor.

    2. Re:Progress by fitten · · Score: 5, Insightful

      In a kernel, all the code needs to be transparent, and you definitely don't want to hide implementation and the usual abstractions.

      Yeah, who wants a common driver API for video, network, or sound cards...

      Not to mention that drivers are all about abstracting the hardware and interface implementation from the OS itself anyway...

      The simple reason for that is that otherwise the kernel would be unpredictable. Let's say the error logging function used the string class (which likes to allocate memory behind your back). If the memory allocation function fails and tries to print an error message... you got yourself a kernel crash. This is why the kernel is significantly more difficult to program than, say, a word processor.

      Yes, a kernel is more difficult than a word processor, but that doesn't mean that implementors must implement stupid C++ code. You can do some pretty neat things in C++ if you know what you are doing. If you don't know what you are doing, you can do some pretty crappy things.

    3. Re:Progress by IceAgeComing · · Score: 4, Insightful

      In a kernel, all the code needs to be transparent,

      That got a chuckle from me. I know what you meant, but after looking at the following (randomly chosen :) block from the device driver grip.c, I wonder just how "transparent" it is:

      if ((((u ^ v) & (v ^ w)) >> 1) & ~(u | v | w) & 1) {
      if (i == 20) {
      crc = buf ^ (buf >> 7) ^ (buf >> 14);
      if (!((crc ^ (0x25cb9e70 >> ((crc >> 2) & 0x1c))) & 0xf)) {
      data[buf >> 18] = buf >> 4;
      status |= 1 > 18);
      }


      The simple reason for that is that otherwise the kernel would be unpredictable.


      Point taken, but I hope you're open to the idea that C++ classes can be written that avoid these problems. In particular, it's relatively easy to define your own memory management scheme. This could be confusing to some (redefinition of new and delete would not be obvious in other parts of the code), but C++ has some nice features that facilitate scalability. I'm sure you'll agree that maintaining such a complicated thing as a cross-platform kernel can use some more sophisticated tools for software development than what C provides.

    4. Re:Progress by 12357bd · · Score: 2, Informative

      Yes, a kernel is more difficult than a word processor, but that doesn't mean that implementors must implement stupid C++ code.

      No, the problem is not if it's difficult or not, is the fact that C++ implies the existence of an intrinsic memory management behaviour (new/delete), that is not really compatible with the strict memory management a kernel must implement.

      --
      What's in a sig?
    5. Re:Progress by geg81 · · Score: 5, Insightful

      The simple reason for that is that otherwise the kernel would be unpredictable.

      Complex code becomes predictable by building layered abstractions with well-defined interfaces. C++ supports that better than C.

      Let's say the error logging function used the string class (which likes to allocate memory behind your back).

      The kernel almost certainly wouldn't be using "the" string class, but its own string class, adapted specifically to the needs of the kernel. Right now, the C-based kernel doesn't use the user mode C library either, after all.

      If the memory allocation function fails and tries to print an error message... you got yourself a kernel crash.

      Quite to the contrary. Not only would the kernel not crash, with a properly designed string class, out of memory conditions would actually be guaranteed to be handled correctly in all string operations everywhere in the kernel. No more case-by-case checking and handling of whether the memory allocation happened to succeed this time or not. In this particular case, the string class would throw an out-of-memory exception in the error handler and the stack would unwind up to the point where there is a handler.

      Furthermore, the error logging function can decide to intercept such exceptions and print an emergency error message on the console, and it can do so reliably without ever having to worry about checking a single status or return value.

      Altogether, this is a big improvement over C-based handling of such situations. But if you want to keep this situation from occurring in the first place, there is no more reason for the error logging function to allocate memory in C++ than there is for it to do so in C.

    6. Re:Progress by Salamander · · Score: 2, Insightful

      It's not so much that C++ itself is so bloated etc. but that some of the common C++ programming idioms - full of templates, overloading, deeply nested class hierarchies with virtual methods, etc. - can lead to bloat. It's never good to have what looks like a simple assignment statement turn into thousands or even tens of thousands of instructions, but it's particularly dangerous in the kernel. Templates are particularly bad because they get re-instantiated for every type they're used with and that can very rapidly cause executable sizes to balloon out of control. They're a non-solution to a problem that's more than adequately solved by treating types as first-class objects, or by lower-level methods such as explicit dispatch-table pointers.

      Sure, you can tell your developers to use a subset of C++ that doesn't have such problems, but what's the point? Why pay the runtime-support and tools cost and require greater vigilance in code reviews just for some syntactic sugar (which is all that would be left)? I'm not absolutely opposed to using C++ in a kernel where it's already supported, but there are costs that would have to be justified compared to just using C.

      --
      Slashdot - News for Herds. Stuff that Splatters.
    7. Re:Progress by fitten · · Score: 2, Insightful

      Yeah, who wants a common driver API for video, network, or sound cards...

      I don't understand why a common driver API is not possible to do in C... Would you care explaining?


      I didn't mention anything about choice of language. The OP didn't either.

      Not to mention that drivers are all about abstracting the hardware and interface implementation from the OS itself anyway...

      Does that mean we should give up on transparency?


      No, but I fail to see why the kernel would have to see into the details of how a device driver is implemented. As long as it conforms to a well defined interface, it shouldn't care at all how it is implemented.

      You can do some pretty neat things in C++ if you know what you are doing. If you don't know what you are doing, you can do some pretty crappy things.

      This (again) begs the question: what can you do in C++ that you can not do in C? Is it just because classes, objects, constructors, destructors, inheritance, and all that crappy OOP stuff is specificly declared that C++ is that superior? You can do pretty well the same in C! There is absolutely no consistent technical reason supporting the use of C++ in the Linux kernel!

      Quoting the FAQ [kernel.org] that you should indeed read since there are some Linus quotes there:




      I agree with that quote but it has nothing to do with the fact that Linus said it. (And it doesn't "beg the question" because that phrase means something else.)

      I've written OO code in C for the past 17 years or so as well as programmed in C++, Java, and C# (more recently) among other lesser known languages. I'm fully aware that I can do in C what C++ does, it just may take a bit more coding on my part to do some of the things. In fact, early C++ compilers were just manglers that output mangled C and compiled that for your program. With newer C++ standards, it isn't that easy anymore, though. Anyway, just as it was said in the quote that you posted, it isn't important what language you use, so what's with the beef against C++?

    8. Re:Progress by GenSolo · · Score: 2, Insightful

      On the other hand, if the above were C++ code, it could mean absolutely anything, depending on how operators were overloaded.
      Except that they can't be overloaded in that case as both operands are built-in types. You can't overload an operator unless at least one of the two operands is a user-defined type, which prevents people from making this do something unexpected. That is, you can't make operator^(int, int) play the star spangled banner, no matter how hard you try.

    9. Re:Progress by maxwell+demon · · Score: 2, Insightful
      Nothing will come out of it, for the simple reason that C++ does not belong in any kernel. In a kernel, all the code needs to be transparent, and you definitely don't want to hide implementation and the usual abstractions.

      The simple reason for that is that otherwise the kernel would be unpredictable. Let's say the error logging function used the string class (which likes to allocate memory behind your back). If the memory allocation function fails and tries to print an error message... you got yourself a kernel crash. This is why the kernel is significantly more difficult to program than, say, a word processor.

      Obviously, C does not belong in any kernel. In a kernel, all the code needs to be transparent, and you definitely don't want to hide implementation and the usual abstractions.

      The simple reason for that is that otherwise the kernel would be unpredictable. Let's say the error logging function used the printf function (which likes to allocate memory behind your back). If the memory allocation function fails and tries to print an error message... you got yourself a kernel crash. This is why the kernel is significantly more difficult to program than, say, a word processor.

      I hope you get the point.
      --
      The Tao of math: The numbers you can count are not the real numbers.
  13. Sorry to break it to you... by RAMMS+EIN · · Score: 2, Informative

    Linux doesn't want any C++, so as long as he's at the top, it likely won't get far. And I think that's good, given the state of C++ in gcc (hint: slow and memory-intensive compiles, generating subobtimal code).

    But I'll shut up. I've pretty much turned my back on C and C++ anyway.

    --
    Please correct me if I got my facts wrong.
    1. Re:Sorry to break it to you... by Anonymous Coward · · Score: 2, Funny

      Hello.

      My name is Linux Torvalds, and I pronounce "Linus" "Linus".

  14. Who cares? by Percy_Blakeney · · Score: 5, Informative
    I really don't see the use in porting these features to the Linux kernel -- they'll never be used in any mainstream kernel release. Linus has stated many times that he doesn't particularly care for C++ in the kernel:

    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

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

    Feel free to make up (d).

    1. Re:Who cares? by Kethinov · · Score: 2, Interesting

      I agree entirely. C++ in the Linux kernel is a largely bad idea.

      I am all for the kernel remaining C forever, but just for the sake of curiosity's fancies, I wonder how much better Objective-C would be as a high level yet still high performance solution as opposed to the messier C++?

      --
      You're right, I wouldn't steal a car. But if it were possible, I sure as hell would download one!
    2. Re:Who cares? by homebrewmike · · Score: 2

      Alternatively, someone could try the patch, and re-evaluate it.

      Computer Science isn't a religion, it's evolutionary. If the "C++ patch" works great, and makes things easier, so be it. If not, it gets tossed out.

      If it is good, and it is rejected, then what's the point of Open Source?

    3. Re:Who cares? by AuMatar · · Score: 5, Informative

      The first argument is easy- exceptions are a Bad Idea. Error codes are much cleaner and more logical. Even the few embedded projects I know that use C++ outlaw the use of exceptions in their code (generally templates as well, for emmory reasons).

      The second- C++ has hidden allocations all over. In C, its easy to find memory allocations. Grep for malloc (or kmalloc in the kernel). In C++, you have temporary objects being instantiated all over the place, automatic constructors/destructors being called, etc. Its nowhere near as open or easy to find (especially temporary object creation. If you don't think thats a problem- try putting a cout statement in a constructor, and write a function that takes an object as a parameter and returns that object. Count how many you see. Its more than 1.) Its not as clean. While this may be tolerated (although confusing) for an application, for a kernel its murder. Memory is tight, and mallocing will kill you performance wise if you need to grab a new free page. It may not even be possible to do if interrupts are locked. Its a hassle.

      In fact, a lot of embedded project don't even allow dynamic memory. I design printer firmware. We are not allowed to call malloc. All memory is tightly controlled by thesystem and is strictly deterministic to ensure we can always do a job. A large amount of object creation doesn't make sense in an embedded/kernel environment.

      Third- why not? There's places where its the best tool fro the job. Assembly gets a bad rap, really its a nice simple language. The real question is- what does C++ give you that C doesn't? Objects- C has them. Inheretance? Very rarely does it really benefit you, its usually used because "we're OO, we're supposed to use it". Templates? Ok, those can be useful for things like linked lists, although the STL goes way over the top with it. Exceptions? See above. The gains of C++ are minimal, the pain of it is large.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    4. Re:Who cares? by slashdot.org · · Score: 5, Insightful

      Boy oh boy, where do we start.

      Please people, I know Linus is God, and I have a lot of respect for the man. But I don't care who it is, if people make statements like this, I'd like to see some back up.

      It sucks. Trust me - writing kernel code in C++ is a BLOODY STUPID IDEA.

      When someone says 'trust me' it either means "I'm too lazy to explain" or "I haven't really got something to prove it".

      The fact is, C++ compilers are not trustworthy. They were even worse in 1992, but some fundamental facts haven't changed:

      Well, I don't want to start a flamewar here, but while this may be true for the GNU compiler, it certainly is NOT true for, for example, the Microsoft compiler. (I know, how dare I say that...) It has produced code from C++ source for a _very_ long time and even the optimizer works very well.

      * the whole C++ exception handling thing is fundamentally broken.

      Why?

      It's _especially_ broken for kernels.

      Why? Maybe for the Linux kernel, because it wasn't designed with C++ exceptions in mind. And I'm not even say that that's bad, but why is it in gerenal 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.

      Well, that's really implementation and as such is your choice, it's not the language. Furthermore, no-one forces you to use _all_ possible language features. I personally stay away from many C++ language features such as overloaded operators.

      * you can write object-oriented code (useful for filesystems etc) in C, _without_ the crap that is C++.

      But why would you if you can do it cleaner in C++ and have the compiler generate the same quality code? What is crap about C++?

      What Linus needs to do is go back to the old days where he looked at assembly output. I still do that and have compared C++ with C many times and I can't see why anyone would not use C++.

      You don't have to use all the bells and whistles, shit, you can write plain ANSI-C and still use a C++ compiler for it's superior type checking etc.

      Anyways, to each his own, I guess...

    5. Re:Who cares? by Foolhardy · · Score: 5, Insightful
      This may not be the original intent of the article, but C++ does have features that C doesn't that won't cause any of these problems. It is better to attack specific features that are likely to be problematic instead of the entire language.

      Don't like exceptions? Don't use them. C++ doesn't require you to. Personally, I don't use them unless I have to interface with other code that does. I usually compile with exception support off.

      Is allocating memory in a constructor likely to cause problems? Make it a standard code practice for your project to never cause non-explicit memory allocation. Destructors can be forced to run at a specific time with delete or by using forced scopes (use {} around the lifetime of the local var). Copying objects in a standard way is easy to do, espescially if you always pass classes (structs) as references or by pointer.
      Memory is tight, and mallocing will kill you performance wise if you need to grab a new free page. It may not even be possible to do if interrupts are locked. Its a hassle.
      Are you saying that C++ always uses more memory than C? That's silly. If you can't call memory allocation functions right now, then allocate things on the stack. Make sure that the objects you create and the functions you call don't alloc either. You would have to make sure the functions were safe in C too.
      In fact, a lot of embedded project don't even allow dynamic memory. I design printer firmware. We are not allowed to call malloc. All memory is tightly controlled by thesystem and is strictly deterministic to ensure we can always do a job. A large amount of object creation doesn't make sense in an embedded/kernel environment.
      Ok, so don't use the heap. There is no reason that C++ needs to use the heap; everything can be allocated on the stack. Just like C.
      Third- why not? There's places where its the best tool fro the job. Assembly gets a bad rap, really its a nice simple language. The real question is- what does C++ give you that C doesn't? Objects- C has them. Inheretance? Very rarely does it really benefit you, its usually used because "we're OO, we're supposed to use it". Templates? Ok, those can be useful for things like linked lists, although the STL goes way over the top with it. Exceptions? See above. The gains of C++ are minimal, the pain of it is large.
      Assembly isn't too nice if you care about portability. It also depends on the architecture about how nice and simple it is. Segmented memory in assembly can be a nightmare.

      Don't use the STL implementation of linked lists if you don't like it. Done properly, you could use templates for even more than that, like different index sizes for a filesystem; a 32 bit version for small volumes, a 64 for large volumes and a 128 for extremely large volumes. Since there is no primitive 128 bit type, C++ lets you override operators to create a new type that acts exactly like a primitive. This word size would be a template parameter of the filesystem class; a static version created for 32, 48, 64 and 128 bit or whatever. One code set, no redundancy. Remember the Sun story about a 128 bit filesystem? It could be as easy as recompilation!

      How about namespaces? These would be very useful in the kernel, IMHO.
      Member functions are nice for associating a function with an object.
      Private data members allow you to put data in a structure that outside code doesn't need to know about so you can change it later without breaking compatibility. Documentation can do it too, but this can enforce it.
      I bet there could be some good uses for smart pointers.

      The fact that a language has a feature does not obligate you to use it. You can use code standards in your project that set sane regulations for the code in the project. You need standards for any a sizable project in ANY language, including C. I'm sure that the Linux kernel already has rules as to naming conventions, header file control etc... More could be created to regulate good usage of C++ in a kernel environment.
    6. Re:Who cares? by AuMatar · · Score: 2, Insightful
      Yes, you can use C++ and outlaw features. The problem is getting everyone to agree not to use them. You then get people using them anyway and need to start rejecting patches. A few will manage to sneak in wthout noticing, and people will use that as an excuse to use it more. Been there, done that on a proprietary codebase. Its better just not to use C++.

      Are you saying that C++ always uses more memory than C? That's silly. If you can't call memory allocation functions right now, then allocate things on the stack. Make sure that the objects you create and the functions you call don't alloc either. You would have to make sure the functions were safe in C too.


      Read Meyer's "Effective C++" and "More Effective C++". There's a lot of hidden object creation that goes on. These take memory. If they malloc memory in constructors, they use LOTS of memory.

      How about namespaces? These would be very useful in the kernel, IMHO.


      Ok, syntactic sugar, but not a bad one. Of course, you could just have a naming convention, and you would likely get as much compliance there as you will with namespaces.

      Member functions are nice for associating a function with an object.


      We have that. Function pointers. Kernel uses them all over.

      Private data members allow you to put data in a structure that outside code doesn't need to know about so you can change it later without breaking compatibility.


      Static data variables do the same thing for single instance. For multi instance hold a pointer to a block of data, hold it in an integer, and call it a handle. Don't let the other guy see the implementation of the block.

      The problem goes back to the top- you're hoping that you can get hundreds of developers with no central control to follow a bunch of rules. They won't. They don't on propriatary projects when they're being paid to do so. On an open source project, it'll be worse. Its easier just not to use C++ than to say "Use C++ but not features x,y, and z".
      --
      I still have more fans than freaks. WTF is wrong with you people?
    7. Re:Who cares? by AuMatar · · Score: 2, Insightful
      Care to cite specific examples where C++ the language itself causes hidden memory allocation? I'm not talking about libraries, but the language. You can use libraries that don't do that. Libraries that do bad things behind the scenes are as big a risk in C as they are in C++.


      Temporary objects. Compilers create temporary objects, especiall arounjd function calls/returns. These call the constructor, which may call malloc. The number of situations temporary objects can be made is actually failry high and very complex. If the language is creating objects you don't explicitly ask for and calling malloc off that, I count that as the language using memory. Its the fault of the language for creating the object.

      I'm saying to use member functions for the orginazation they provide. You could get somthing similar with a good naming convention. This OTOH is supported by the language.

      Like I said- function pointers. Like this:

      struct foo{
      int (*bar)(int);
      }

      foo has a member bar, which is a pointer to a function that takes an integer and returns an integer. You assign it like: foo->bar=myfunc; This is exactly what a member function does- the only difference is that the this pointer won't exist, so the first parameter to any member function would have to be a pointer to itself. You can even call it this :)

      Handles are more difficult to implement than simple pointers. You can't go from a pointer system with all public vars to a handle system very easily, whereas you can add private members to an existing structure easily.


      No they aren't. Its 1 line of code per function. Its like this:

      struct outer{
      int handle;
      }

      struct inner{
      int x,y;
      }

      int some_privlidged_func(outer *o){
      inner *in= (inner*)o->handle; //now just reference inner->x and inner->y
      }

      Having developers that don't follow rules and write sloppy code is a much bigger problem than a change of language can fix. Bad developers will write bad code no matter the language. There are plenty of rules you can break to make bad code in C too. There are plenty of rules in kernel code that bad developers will break, too. I can't imagine that C++ would make that big a difference; there will still be programmers that disregard the rules.


      It gives them additional ways to break the rules. The more rules, the more people will want to break them, or just waste your time disagreeing with them. Its a social problem, not a technical one. And with larger teams, its a larger problem (with small teams the team probably made the rules themselves and hashed out differnces then). On a small 3-5 person project restricting features works. On large ones it just becomes a hassle. On very large ones with more than 1 gatekeeper to the code, it breaks down entirely (all you need is 1 lazy/disagreeing member with check in privlidges).

      --
      I still have more fans than freaks. WTF is wrong with you people?
    8. Re:Who cares? by Pseudonym · · Score: 2, Insightful
      Of course, if anyone feels like Linus is a total idiot, then they can try porting Linux to C++. I'm willing to bet that if someone could show substantial real benefits from a C++ Linux, Linus would happily eat his words.

      This, of course, the wrong end of the proverbial stick. The benefit of C++ is that it lets you do pretty much what the kernel does now, only in a way that's easier to understand and more maintainable.

      To get any substantial benefit for existing code, you'd need to translate the entire kernel into idiomatic C++, which is a huge task. For new code, OTOH, C++ compatability should be a win. Unfortunately, the only way to prove this is to a) support C++, b) implement the new code twice, once in C++ and once in C, and c) compare them.

      Given that almost nobody is willing to implement their new feature twice just to prove a point...

      --
      sub f{($f)=@_;print"$f(q{$f});";}f(q{sub f{($f)=@_;print"$f(q{$f});";}f});
    9. Re:Who cares? by s0lar · · Score: 2, Informative

      > (a) looking for problems
      This is a boolshit argument - you get problems with C too. Big problems with "evil macros", memory leaks, resource dead locks, pointer arithmetic, stack corruption etc. It's a matter of expertise, regardless of the language.

      Sure, the C way seems transparent and obvious, but complex problems require more involved solutions. Solutions that abstract building blocks in order to manage this complexity. Abstraction mecanisms are much better with C++. The same goes for encapsulation - OO way provides several useful mechanisms than "static".

      > (b) a C++ bigot that can't see what he is writing is really just C anyway
      The point Stroustrup makes is that one can use a subset of C++. It's a valid thing. However, OO concepts are native to the language, so no function pointer assignments are required to implement abstraction. No "just return a handle" hacks are required to have encapsulation. Why not use a language that natively supports and checks for polymorphism, abstraction and encapsulation?

      Now, all of this is described much better in a "Conversation with Bjarne Stroustrup" by Bill Venners here:
      Part 1: The C++ Style Sweet Spot http://www.artima.com/intv/goldilocks.html
      Part 2: Modern C++ Style http://www.artima.com/intv/modern.html
      Part 3: Abstraction and Efficiency http://www.artima.com/intv/abstreffi.html

    10. Re:Who cares? by dpuu · · Score: 2, Insightful

      C++ sucked 12 years ago, so attempting to support it now, 12 years later is a stupid idea.

      Sorry, that argument doesn't quite work for me.

      As I understand it, this patch would simply add runtime support to give a kernel-module-writer the option of experimenting with C++, if desired. Accepting it would not force anyone to use C++. It possibly that the patch itself could be written in C, not C++, so accepting it (or a similar patch) need not introduce C++ into the kernel.

      Once that support is there, you could leave it for a few years while experimenting. No one is forced to rewrite any code (unless they want to). In the meanwhile the kernel becomes increasing modular and, one day, one of the core subsystem might choose to use C++. For example, the VM subsystem could choose to use C++ without having any visible impact on other subsystems.

      Linux moves forward through evolution, not revolution. Add the support, and see if its useful. If it is, people will eventually use it as the old maintainers drift away.

      --
      Opinions my own, statements of fact may contain errors
    11. Re:Who cares? by Foolhardy · · Score: 2, Informative
      Temporary objects. Compilers create temporary objects, especiall arounjd function calls/returns. These call the constructor, which may call malloc. The number of situations temporary objects can be made is actually failry high and very complex. If the language is creating objects you don't explicitly ask for and calling malloc off that, I count that as the language using memory. Its the fault of the language for creating the object.
      Don't use classes that call malloc on copy. This would be the library in which the class belong's fault. Either that or always pass by reference or pointer; no copy required. Use const if you don't want the value changed. This can be a rule for the project.
      Like I said- function pointers. Like this:
      You're right. I wasn't thinking about that. Still, you can't inline across function pointers. That could lead to bigger code if the function body uses less instructions than a function call.
      struct outer{
      int handle;
      }

      struct inner{
      int x,y;
      }

      int some_privlidged_func(outer *o){
      inner *in= (inner*)o->handle; //now just reference inner->x and inner->y
      }
      Ick, this assumes that sizeof(int) == sizeof(void *); that is a bad assumption for portable code. Also, you have a one member structure. A better idea would be an empty structure for outer; cast a pointer to outer to get inner.
      I guess this would work pretty good, although you would have to maintain functions to access any data inside of inner whereas you could get to it directly with public. That was my point, that public/private is more convenient than handles. It lets you concentrate more on important things rather than wasting time writing glue functions, as you must to access any properties of a handle.
      It gives them additional ways to break the rules. The more rules, the more people will want to break them, or just waste your time disagreeing with them. Its a social problem, not a technical one. And with larger teams, its a larger problem (with small teams the team probably made the rules themselves and hashed out differnces then). On a small 3-5 person project restricting features works. On large ones it just becomes a hassle. On very large ones with more than 1 gatekeeper to the code, it breaks down entirely (all you need is 1 lazy/disagreeing member with check in privlidges).
      Kernel code already has a million ways to do bad things. Having a different language won't make it much worse. Done properly, C++ can help you write better code that is MORE resilient to idiocy, not less, using namespaces, new types by overloading, smart/safe pointers, templates, member protection...
    12. Re:Who cares? by Pseudonym · · Score: 2, Interesting

      Precisely, which is my main point: Writing the Linux kernel in C++ is a waste of time because right now, it's already written. Given that nobody wants to waste their time on this, we will never know if Linux is better written in C or C++.

      I can only speak from the point of view of maintainability and readability, but you make a good point that if Linus et al can't read C++, then even this isn't necessarily an advantage.

      It is truly ugly to have multiple acceptable coding paradigms in a large project [...]

      Actually, most large software projects are multi-paradigm. This is because most large software projects have a "soft layer" DSL/scripting component (e.g. Emacs lisp). An OS kernel is a bit special in this regard, in that most of it is low-level stuff held together with internal APIs. The "soft layer" of Linux is user space.

      --
      sub f{($f)=@_;print"$f(q{$f});";}f(q{sub f{($f)=@_;print"$f(q{$f});";}f});
    13. Re:Who cares? by ebbe11 · · Score: 2, Insightful
      Not quite... Consider this statement:
      char *ptr = malloc (3200);

      Except that in C++, you'd write:

      char *ptr = new char[3200];

      and not have any problems at all.

      --

      My opinion? See above.
    14. Re:Who cares? by tchernobog · · Score: 2, Insightful

      If you don't think thats a problem- try putting a cout statement in a constructor, and write a function that takes an object as a parameter and returns that object.

      Although I agree that c++ isn't a good choice for a kernel, here i've to say that you can in fact produce good code simply remembering to pass args to a function as constant references. You've a good control over when and why temporary objects are created, if you fully understand what your code does. More, modern compilers like g++ use optimizations to avoid creating non-wanted temp objects (like in "C* obj = new C(C(otherobj));") and thus eliding redundant constructors (that was a silly example, but there's plenty of situations).

      I believe that for a good c++ programmer memory management is simplier and cleaner than c's one, instead of loose and chaotic. This doesn't mean that malloc() sucks; it just means that new/delete aren't evil and help you if you know how to use them.

      Assembly gets a bad rap, really its a nice simple language.

      Simple doesn't mean portable.

      The gain of c++ over c is really substantial, BUT I don't think that c++ is a good choice for kernel development, mainly because it's too "tempting" to add millions of useless features. c is neat, easy and has a really small grammar: it's something you can learn in a week. c lets you to act to a more lower level, is faster to compile, and extremely portable (that's the main reason why Linus won't like c++). I believe that c lets programmers to concentrate more on the real algorithmic problems of the code (such as sorting, scheduling, threading...) than on inheritance/class (syntactic) related ones.

      --
      42.
  15. fantastic ... by Anonymous Coward · · Score: 4, Funny

    what an incredibly awesome idea!!!

    i can't wait to try and debug virtual functions, copy constructors, and polymorphism over JTAG or BDM!!!!

    man thats gonna be fun ... my hats definitely off to this academic you have definitely spent your time wisely!!!!

    i always found C causes to much clutter in the linux kernel ... a real language will do us all good ...

    keep an eye for this in 3.0 ...

    Jim

  16. .... so can we compile the kernel by TheRain · · Score: 2, Interesting

    using the kernel now? :)

    Joking aside, this is cool. Runtime compiling makes conceptual sense in an open source operating system running mainly open source software... though it will surely add to load times. It adds to the openess of open source by keeping the source editable straight up untill run-time and, so, encourages keeping source code and editing source code... being that it is immedietly executable, given it was coded correctly of course ;)

    --
    Please help! I'm stuck inside my virtual reality headset!
  17. C++ by bsd4me · · Score: 4, Interesting

    I'm not sure if many people remember, but there was a short time when the kernel source was compiled with g++, even though the source was plain C.

    IIRC (memeory very hazy, though), it lasted about a month in 1992 or 1993, and it had something to do with type-safe linking(?).

    --

    (S(SKK)(SKK))(S(SKK)(SKK))

    1. Re:C++ by Lally+Singh · · Score: 2, Funny

      C++ wasn't standardized until 1998. Should I talk trash about C99 by referring to the original K&R version?

      --
      Care about electronic freedom? Consider donating to the EFF!
  18. Here's what's coming up! by Le+Marteau · · Score: 3, Funny

    Support, within the kernel, for IE^H^HMozilla! It'll be perfectly safe! Trust us!

    --
    Mod down people who tell people how to mod in their sigs
  19. Exception-handling changes relevant for g++? by Monkius · · Score: 3, Interesting

    Kernel aside, I wonder if G++ developers out there have any comments on these guys' exception-handling changes?

    Would they be applicable to the user-space runtime?

    --
    Matt
    1. Re:Exception-handling changes relevant for g++? by halldorisak · · Score: 2, Informative

      These changes would definately be applicable to user space as well, and indeed we mention it in our paper. In kernel however they are more important as performance is normally of more concern.

      Ideally you should be able to turn on these optimizations by a switch. If any g++ developer is out there I'd be more than happy to explain what we did and they are free to use it.

      Some of the overhead in the g++ exception implementation arises from the fact that ease of debugging is considered important. However in kernel space that does not apply.

  20. interesting, but not very useful by cout · · Score: 4, Interesting

    Any kernel project that uses C++ is most likely doomed to be an experimental project and will most likely never be included in the kernel. IMO, there's good reason for that, too. The added complexity just doesn't outweigh the benefits of using C++ over C.

    In fact, there was a good post on kerneltrap not to long ago about C++ inside the linux kernel:

    http://kerneltrap.org/node/view/2067

    Worth a read if you've got a few minutes to burn.

    1. Re:interesting, but not very useful by Lally+Singh · · Score: 2, Informative

      essentially a quote of linus's comments from the 1992 test. boo hoo, he tested a pre-standard language and a pre-standard compiler (which was honestly crap on C++ until very very recently).

      --
      Care about electronic freedom? Consider donating to the EFF!
  21. great! by pyrrho · · Score: 2, Funny

    but don't use runtime type checking in the kernel please.

    or exceptions.

    --

    -pyrrho

    1. Re:great! by pyrrho · · Score: 2, Interesting

      I'm a bit out of date on RTTI implmentations but I did see that mentioned, which sounds great. A pointer to what though?

      Anyway, RTTI can be a great thing (and beats building your own dynamic typing system when you need one) but I'm with Stroustrup that the need for one shows improper design in the most general case.

      btw, I love C++. The point is that C++ has many available paradigms and idioms available, this gets it a lot of teasing... but it's a strength... a project is to choose the idiom it prefers and stick with it.

      --

      -pyrrho

  22. I take exception... by IceAgeComing · · Score: 4, Informative


    I've only written one linux driver, so I'm no expert, but I can think of situations where exceptions can be helpful for device drivers.

    Take, for example, a game controller or other hardware device that can become unplugged at any moment. It's useful to have an elegant way of handling this uncommon occurrence.

    Exceptions are a useful way to separate uncommon sanity checks from the rest of your code, so you're not forced to use ugly nested conditionals.

  23. Who cares? by Anonymous Coward · · Score: 3, Funny

    My VB kernel works just fine for me.

  24. The true nature of C++ :) by kompiluj · · Score: 5, Interesting

    C++ was designed to be the language of choice for modern operating systems, meant to replace C. This is main reason why every decision was made with efficiency in mind (no automatic virtual functions, no garbage collection, and, oh yes!, the infamous: pointers and goto). And of course C++ is fast. Maybe it loses by hair's breadth with C but surely wins with Java by great margin. And don't tell me about JIT, do some homework.
    I think trying to incorporate C++ into Linux kernel is a good decision, giving more vitality to Linux and allowing it to differentiate better from the traditional UNIX systems - but that's only my 0.02 Euro.

    --
    You can defy gravity... for a short time
    1. Re:The true nature of C++ :) by Anonymous Coward · · Score: 2, Interesting
      Decisions like this (C++ in the Linux kernel) are indicitive of the courses currently running in Computer Science departments world wide.

      Whilst at university I kept up with the compsci courses as well as those required for my physics degree and I have to say I was shocked. There was no C taught at all, and only one course on ASM - a basic first year introductory module which was very leaniently marked. All other "programming" classes were conducted in Java or html (funny given html is a markup language). There was an optional "AI" course which taught a little prolog, but less than could be covered by an average hobbist in 3 nights.

      The java aplications developed were - all in all - no better than what I would expect a decent highschool computer scientist to turn out - simple storage/record keeping apps. The first lesson the freshmen compscis had was how to turn a computer on. "This is the 'power button'". Three students had not used a computer before.

      It was a real eye opener, of the ~100 students enrolled I would have considered employing less 6 of them for a computer related role. There were only 2 I would have employed as programmers, both exception compared with the rest of their cohort.

      I should think that less than half of the graduting class knew what a kernel was let a lone why one shouldn't be written in C++ or Java.

      The Physicists on the other hand became adept at technical multiplatform C programming and were required to take an ASM course which covered the computer science material in a 3 hour afternoon session along with debugging of a 6 A4 page ASM print out for a chip we knew virtually nothing about. ~70% knew at least some unix and virtually all were better programmers than their comparable computer scientist friends, example programs written included a ray tracing app, a graphical simulation package for complex elecomagnetic fields, and galaxy formation simulations.

      The trend continues into postgrad life where one of the barely employable compscis is working towards a PhD in network traffic analysis, despite at our last interaction him not knowing anything about data networking, other than you push the cable with the funny shaped plug on the end into the wall and it goes to the hub.

  25. Re:A good hacking exercise, but... by fitten · · Score: 2, Insightful

    In other words, put the efforts where they're most needed.

    I thought F/OSS (and Linux) was all about innovation and exploration... Sure, there are lots of things that F/OSS projects need (not the least of which is some QA effort), but it also needs folks like these people who are out doing cool stuff, even if it isn't necessary practical (or even considered practical by the 'masses' or the 'powers that be').

  26. "The fact is..." he's out of touch by devphil · · Score: 3, Interesting


    Anyone who claims with a straight face in 2004 that "C++ compilers are untrustworthy" is trolling. Sorry, rabid penguin lovers.

    I love it when language bigots forestall any reasonable discussion by preemptively accusing anyone who disagrees with them of being a language bigot. Slashdot, of course, believe that Linus can do no wrong, so none of it ever applies to him...

    After having conversations with him myself, I can state my honest belief that Linus doesn't understand how to use C++, and will simply assert that "it's just C anyway" no matter how many times he's proven wrong. He's a smart guy, but he's got his blinders on in some respects.

    --
    You cannot apply a technological solution to a sociological problem. (Edwards' Law)
  27. But why should C++ be used in the Linux kernel? by master_p · · Score: 2, Interesting

    The article says that they managed to support C++ in the kernel. Well, that's sweet as an accomplishment. But what are the benefits? many parts of the kernel are already object-oriented, in the form of manually written vtable structs and object structs that have pointers to those vtables. I just don't see a reason for C++ in the kernel. Maybe someone that knows more on this can enlighten us.

  28. Re:Great news! by AuMatar · · Score: 3, Insightful

    Thats because you're used to C++. I know that code I produce in C is by far more sophisticated, and of a much greater quality than what I could produce in C++ in a similar time frame (unless I used the C subset of C++, which basicly means I was writing C).

    Now if you were to start a new kernel entirely in C++, that'd be fine. The use here would be to mix the two *shudder*. No thanks. You then have a problem where the C++ people can't understand the C code, and the C people don't understand the C++ code. Its a maintenance nightmare. Just wait til the first patch that requires changing C and C++ parts. It'll be ugly.

    Its much better to pick 1 language for a project and stick with it, or do a total rewrite. Mixing the two will just cause problems. Luckily, this patch has near 0 chance of being taken into the kernel.

    --
    I still have more fans than freaks. WTF is wrong with you people?
  29. You're going to kill Stallman by TheKubrix · · Score: 2, Funny

    Or at least drive him (more?) insane!

  30. Reviving a joke... by ari_j · · Score: 2, Funny

    The good news is that we have a new renewable power source. What you do is wrap Linux in wires and place him in a magnetic casket. Putting C++ in the kernel will cause him to roll fast enough to generate enough electricity to power North America.

  31. Oh god, WHY? by melted · · Score: 2, Interesting

    Haven't they read "Exceptional C++"? C++ is a fucking disaster. It kind of constantly conspires against you to shoot you in the foot in some kind of massive manner where you'd least expect. Sure, non-exception enabled code is ugly (check the return values all the time, etc), but any non-trivial exception-enabled code is nearly impossible to write if the requirement is that it works correctly in all situations (which is what the requirement is for the kernel).

    Don't get me wrong, C++ is an OK language, but I'd think twice before using its exceptions.

  32. C++ in the kernel? by OverflowingBitBucket · · Score: 4, Insightful

    Now I'm a big fan of C++ and all, being both my language of choice and my favoured (or at least, least detested) language. However, there is the matter of using the right tool for the right job. When I need a quick, disposable tool, I don't fire up a new C++ file and work it into my project. I slap together something in ruby, and use that. Now, C++ in the Linux kernel?

    The value of an OO language in larger projects is enormous. Basically there are simply too many things that could go wrong at any point, and the overhead associated with C++ (memory use, exception setup, excess copying, dynamic checking) is a small price to pay for the additional benefits it provides. As you get closer to the metal though, and you have to watch what you are doing more closely. You want to know exactly when memory is being allocated, when something may go wrong, and only want to set up to catch exceptional circumstances if you know they may occur. Resources in kernel-land are expensive. C allows this kind of control, C++ does not.

    My former boss would love to see me defending C over C++ like this. The irony.

    Having said that, the capability to run C++ code in the kernel would certainly be nice, provided it didn't impact the existing code. I'm not sure how this one could be pulled off though. There'd be too much code that would need to be made aware of exceptions, destructors, so forth.

  33. call/cc by Karma+Farmer · · Score: 2

    If we're going to add exceptions to the kernel, lets go all the way and add "call-with-current-continuation." Imagine how much cleaner the resulting code would be!

    1. Re:call/cc by Dr.+Photo · · Score: 4, Funny

      Clean, but not clean enough. For true conceptual purity, you need lexical closures, call-by-name, monads, lambdas, cooperative microthreads (though of course these could be simulated by call/cc), message passing, introspection and serialization, nongenerative record types, one-shot and partial continuations, maybe a little prototype-based OOP for flavor, and of course if you add prototype-based OOP, you'll need generics that are specializable by object rather than class (as well as consider the case of whether a method specialized for a particular prototype object still applies to its descendents), not to mention considering how that would affect the implementation of a meta-object protocol and multiple inheritance.

      Once you've done all this, Linux will truly be ready for the desktop. (Assuming you axiomatize your language definition first, to get rid of unnecessary features like for loops).

  34. That's not what exceptions are for... by Anonymous+Brave+Guy · · Score: 4, Insightful

    Sorry, but I think you're missing the point of exceptions. They are supposed to decouple generating the error from reacting to it, because in practice that's often useful.

    Exceptions are a systematic way to return control multiple layers up the code, without cluttering the code in between passing information it doesn't need to know or care about. They are best used where the code that directly causes the error can't handle it because it doesn't know how, and the code that handles it doesn't care where it came from, because the code that was trying to run aborted anyway.

    You could write at least a good length article on what exceptions are and aren't good for, but in short, if you ever throw exceptions exclusively at one level and catch them exclusively at the next level up, there's a good chance you're using the wrong tool for the wrong job.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    1. Re:That's not what exceptions are for... by defile · · Score: 3, Informative

      Some people say exceptions. I say goto. Easy to understand, easy to implement, and very clean IMO:

      int addclient(int s,struct sockpair *sp)
      {
      struct sockaddr_in sin;
      socklen_t sl;
      int local,remote;

      sl = sizeof (struct sockaddr_in);
      if (-1 == (local = accept(s,(struct sockaddr *)&sin,&sl))) {
      perror("accept()");
      goto just_return;
      }
      fcntl(local,F_SETFL,O_NONBLOCK);

      if (extent >= TCPFWD_NO) {
      fprintf(stderr,"error: out of buckets! %u >= %u\n",extent,TCPFWD_NO);
      goto close_local;
      }

      if (-1 == (remote = socket(PF_INET,SOCK_STREAM,0))) {
      perror("socket()");
      goto close_local;
      }

      /* reuse sin struct from accept() */
      memset(&sin,0,sizeof (struct sockaddr));

      sin.sin_family = AF_INET;
      sin.sin_port = htons(remote_port);
      sin.sin_addr.s_addr = inet_addr(remote_addr);

      if (INADDR_NONE == sin.sin_addr.s_addr) {
      fprintf(stderr,"inet_addr('%s'): failed\n",remote_addr);
      goto close_remote_local;
      }
      if (-1 == connect(remote,(struct sockaddr *)&sin,
      sizeof (struct sockaddr_in))) {
      perror("connect()");
      goto close_remote_local;
      }
      fcntl(remote,F_SETFL,O_NONBLOCK);

      sp[extent].allocated = 1;
      sp[extent].a = local;
      sp[extent].b = remote;

      extent++;
      return 0;

      close_remote_local:
      close(remote);
      close_local:
      close(local);
      just_return:
      return -1;
      }

  35. Linus and C++ in the kernel by noselasd · · Score: 4, Informative

    Linux made his view on C++ in the kernel a while ago here

  36. C vs C++ by steinnes · · Score: 4, Insightful

    These guys didn't do this with hopes of it being accepted into mainline, they did it to use with their pronto project (some sort of dynamic multicasting project, using the Linux kernel).

    Personally, I think mixing C++ into the kernel is not a good idea, generally, in my experience certain aspects of C++ are messy to debug, and if you're gonna skip using them, then perhaps you should've stuck to C.

    Also these guys used to distribute their pronto project in one tarball, a modified version of the Linux kernel, and the website for downloading it made you have to accept *their* license. When the issue of whether this was possibly in violation of the GPL, and if they should rather distribute a clean patch, came up on the local GLUG mailing list (www.rglug.org) their response was rather shocking, they absolutely refused to acknowledge that they should perhaps distribute their code in another way, and even reverted to speculations about the legitimacy and enforcability of the GPL. To their defense, the original 'article' on the matter was very inflammatory and made some rather derogatory remarks, and IIRC they changed their website some time later.

    Multicasting is a cool technology, and dynamic multicasting routers such as RU is researching and developing with the Pronto project, may well be the key to using the internet as a single infrastructure for 95% of our content-delivery and communication needs (digital TV through the internet, without exponentially increasing bandwidth load, etc), so I hope RU keep on, and their work be fruitful :-)

    Also, to everyone who refers to the creator of Linux, as 'Linux'... his name is 'Linus', get it through your heads, this is slashdot.org not mouthbreathers.org ;-)

  37. Reality check by pslam · · Score: 2, Informative
    Nothing will come out of it, for the simple reason that C++ does not belong in any kernel. In a kernel, all the code needs to be transparent, and you definitely don't want to hide implementation and the usual abstractions.

    The simple reason for that is that otherwise the kernel would be unpredictable. Let's say the error logging function used the string class (which likes to allocate memory behind your back). If the memory allocation function fails and tries to print an error message... you got yourself a kernel crash. This is why the kernel is significantly more difficult to program than, say, a word processor.

    Put the strawman away. You don't absolutely have to use all the features C++ gives you if they aren't right for you. Don't use exceptions or run-time typing in an environment where you don't need it, or don't know if it'll work. Personally I never use either because I strongly disagree with the code they generate. If you don't understand that skilled usage of C++ generates exactly the same code that the equivalent C would (except the C++ took less time to type and checked your syntax better), you don't understand the point of C++ whatsoever. It's just a glorified type checking macro expander. And there's no reason to use plain C when you've got that at your disposal.

    Now have a look at examples of kernels written in C++. One easy example: Red Hat eCos. Just saying that C++ doesn't do kernels well doesn't remove the fact that people do use it in kernels, it works very well, and there are many examples out there.

  38. less snarky by pyrrho · · Score: 2, Insightful

    C++ is an extension of C... a continuation of it's ideals to see the machine as the machine sees itself, to allow the programmer latitude with the machine while giving ways for the programmer to protect itself from common problems.

    C++ is not distinct from C because it's evolution has been driven by adhering to the systems oriented philosophy of C and also by a very real effort to keep C++ "compatible" with C.

    Obviously, to take advantage of C++'s improvments, you have to learn and use them.

    --

    -pyrrho

  39. C++ in embedded applications is a bad idea by amightywind · · Score: 3, Insightful

    Embedded dev is now often C++ based.

    Too bad too. I am developing FAA Level A avionics software using C++, I am sorry to say. What a debocle. For starters, the compilers for non-gcc supported platforms uniformly suck. Typical compilers for DSP's lag the C++ standard by 10 years, and crash frequently. And my project is proof that if a language feature exists it will be used, no matter how pointless. For example:

    /* Rational person sets a control register in C */
    *SOMEREG_ptr = BIT_A | BIT_B;

    or

    // C++, is this really better?
    Register_set<std::uint16_t> regset(base_address);
    regset.write(SOMEREG_OFFSET , Register_set<>::BIT_A | Register_set<>::BIT_B);

    Gross. Please keep C++ out of the Linux kernel!

    --
    an ill wind that blows no good
  40. (d) There's a big fat hole in the standard. by Ungrounded+Lightning · · Score: 2, Interesting

    My pet peve: the gaping hole in the standard regarding the use of virtual functions from constructors and destructors and routines that serve them.

    If a member object's constructor, or a routine it calls, somehow gets hold of a pointer to the containing object and calls a virtual function, IMHO it should be performing a legal operation and should get the BASE CLASS version of the function. Ditto in the destructor. (At this stage of construction the base class is fully functional, while the derived class is not yet initialized making attempts to call its version of the function massively broken.) Ditto during destruction. The derived class version should be the one you get beginning with the first line of the body code of the constructor and ending with the last line of the body code of the destructor. (The object transitions during those sections of code, which can be coded carefully to only use virtual member functions whose support is initialized.)

    Everywhere else C++ uses extreme care to get the "right" level of virtual function. (This is unlike Objective C and Smalltalk, which "get it wrong" big time by calling derived class (subclass) versions in base class (superclass) construction code, breaking the already-debugged code.) But here the standards - and the implementors - missed an imporatant point.

    With an opportunity for both construction and destruction code to get it "right" (call the base class version) or" wrong" separately you have four binary combinations - of which one is "right" and three "wrong". In the early days (pre-standard), cfront got it "wrong" one way, gcc another way, and three commercial compilers for PCs the third way. (So the standard would have imposed equal pain by prescribing the "right" way, leaving them all "broken".) But the first ANSII standard explicitly left it undefined, while the second one not only affirmed that but explicitly warned against calling virtual functions from constructors and destructors.

    (I did bring this up with the committee both times, but was unable to sway them, even to make it a recommendation or to provide a "pedantic construction/destruction order" switch.)

    Getting it "right" would have had considerable benefits. There's a lot of useful things (which I won't go into here) that become easy if it's "right" and breaks badly - or requires combersome workarounds - if it's "wrong". And getting it "wrong" also leads to subtle bugs and interactions even if you're NOT trying to do something fancy.

    (Because it was "wrong" in all the compilers and not forced by the standard, a large programming project I was working on back then was forced into workarounds that gutted the opportunities to build complex objects using member objects, replacing them with smalltalk-style heap-allocated objects strung together by pointers (with enormous overhead as a reault) and creating an initialization function hierarchy parallel to the construction hierarchy to get things properly spun up.

    In the kernel the code must be solid and really should be tight and do things the obvious and simple way. So a feature-gutting, bug-attracting, spec ambiguity like this is a nightmare.

    Thus for me:

    * (d) There's a big fat hole in the standard.

    Is a killer.

    --
    Bantam Dominique roosters crow a four-note song. Once you've heard it as "Happy BIRTHday" you can't NOT hear it that way
    1. Re:(d) There's a big fat hole in the standard. by Ungrounded+Lightning · · Score: 2, Interesting

      Everywhere else C++ uses extreme care to get the "right" level of virtual function.

      (Or overridden functions in general, whether virtual or not.)

      --
      Bantam Dominique roosters crow a four-note song. Once you've heard it as "Happy BIRTHday" you can't NOT hear it that way
  41. Haiku uses C++ in kernel by Anonymous Coward · · Score: 2, Informative

    Haiku (formerly OpenBeOS) has had parts of the kernel in C++ since the beginning.

    Most notably the reimplementation of the Be File System. (Now OpenBFS)

    http://cvs.sourceforge.net/viewcvs.py/open-beos/ cu rrent/src/add-ons/kernel/file_systems/bfs/
    The filesystem is not slow at all. Actually the Haiku-people did some speed comparisons with Be's BFS and OpenBFS won.

    Other parts of the kernel is C++ as well. The device manager, an experimental vm..

    I've never really understood this anti-c++ in kernel thing.

  42. C++ is a bad idea for bad programmers by Chemisor · · Score: 4, Insightful

    > // C++, is this really better?
    > Register_set regset(base_address);
    > regset.write(SOMEREG_OFFSET , Register_set::BIT_A | Register_set::BIT_B);

    Only a complete novice would write code like this. Your code setting *SOMEREG_ptr = BIT_A | BIT_B will work just fine in C++ too. In fact, you could transparently support multiple types of registers by overloading operator= of SOMEREG_ptr, which could be a polymorphic class. And if you think that is going to bloat your code, you obviously have never looked at the output of a good compiler like gcc. A good C++ design is FAR more readable than any C hack you can come up with.

    > Typical compilers for DSP's lag the C++ standard by 10 years

    That is the problem of your compiler, not the language. Stop bashing C++ when you should be blaming your vendor for not being able to write a decent compiler, or even port gcc to their platform.

    1. Re:C++ is a bad idea for bad programmers by Foole · · Score: 3, Insightful

      I think you missed his point.

      The code sample was meant to show that some people will find excuses to use C++ features when the C equivalent works perfectly well. *HOPEFULLY* this won't happen in linux.

      amightywind wasn't bashing C++ in general, only in the context of embedded dev. I think they made this perfectly clear in the first 2 lines.

      I'd say they do blame the vendor, but the current state is that C++ in not good for embedded dev. If you can't get a good C++ compiler for the platform, then C++ is not a good choice of language. This has no direct reflection on C++ as a language.

      --
      This is not a turnip.
  43. Exceptional programming by Baldrson · · Score: 3, Interesting
    If you want to optimize exception handling then choose an exception-based execution model. Most people -- particularly Perl programmers -- are familiar with the short-circuit "or" and short-circuit "and" style of programming. "and" binds more tightly than "or" so that a sequence of "and" looks like a normal execution thread with no exceptions, whereas a sequence of "or" looks like a cascade of exception handlers (if all the prior expressions in the "or" sequence fail then you take the next one as an exception handler).

    When I say "thread" above I'm not just throwing around an ad hoc term -- you can use this to provide the basis for parallel execution in an OS or language.

    There is an entire school of thought built around this idea called logic programming and it is based on the most widely used foundation for mathematics -- the predicate calculus.

    I don't know why people spend so much time and energy optimizing things that are less powerful.

    As for object oriented programming, As I've said before:

    Almost all the Object Oriented stuff people layer on predicates are, at best, an ad hoc, and poor, means of optimizing execution speed.

    Let me explain.

    One of the principles of polymorphism is that the same method has the same abstract meaning regardless of the kind of object. A predicate considered as a method subsumes such polymorphism by simply trying the various possible implementations of the method and committing to only those that succeed. If more than one succeeds then so be it -- that's the whole idea of relations as opposed to functions.

    So, one reason you want all this OO stuff is the inheritance hierarchies keep you from going through all possible interpretations of a given method when the vast majority of them will fail for a given object.

    Another, related, problem is that inheritance provides defaults without requiring a lot of thinking on the part of the computer. What I mean by "thinking" here is the sort of thing that is done by statistical imputation of missing data via algorithms like expectation maximization (EM) [clusty.com] or multi-relational data mining via inductive logic programming .

    So, the other reason you want all this OO stuff is so you can avoid mining a background database to provide reasonable defaults for various aspects of the data.

    Some might be concerned that over-riding isn't absolute in such a system -- that you don't absolutely block, say, more generic methods when you have more specific ones present, and they're right. You don't block those methods -- you lower their priority by lowering the probability of those implementations via the statistical methods of imputation and/or induction. In a microthreading environment they most likely won't get any resources allocated to them before other higher priority implementations have succeeded. In a single threaded/depth-first environment they will be down the list of desired alternatives -- but they won't be discarded until something equivalent to a prolog cut operation kills them off.

    However, and this is the important point, the work that has been expended toward OO facilities has vastly outstripped the effort that which has been put toward more parsimonious ways of optimizing predicate systems.

    One of the better predicate calculus systems out there -- more promising due to its use of tabling to avoid infinite regress on head-recursive definitions and its optimization of queries using some fairly general theorems of predicate calculus -- is XSB . It has an interface to odbc and a direct interface to Oracle, but it would be better if it had something like a

    1. Re:Exceptional programming by Sinner · · Score: 2, Insightful

      I actually was wondering if this was a troll while I was reading it... parts of it read like text generated by a Markov chains... syntactically correct but semantically nonsense. There used to be (still are?) crapflooders on IMDb whose reviews were very similar in comprehensibility to this.

      But then I realised it's Baldrson, and the penny dropped. Most trolls are indistinguishable from idiots, but Baldrson is a genius who's indistinguishable from a troll. I think he comes from a parallel universe where his beard is considered normal.

      Someone needs to get Baldrson and ESR alone in a room together. I'm intrigued to know whether they'd fight or make out. But what if the combined comedy facial hair reached critical mass? Is it worth the risk?

      --
      fish and pipes
  44. Re:"The fact is..." he's out of touch by mikefe · · Score: 2, Interesting

    The fact is that the Linux kernel is not just C, it also has parts where it uses assembler because they don't trust even the C compiler for that part of the code.

    The fact is that in the kernel much of the low level code cares about the exact physical layout of memory, and if it were mostly C++ you would need more parts in assembly which must be ported to each archatecture.

    Yes, C can be used in a higher level, but you are calling functions that deal with the low level from there is a very much OO way.

    Also, when you see people benchmarking how many cycles a processor actually takes to perform a snip of code and analyzing the assembly of the C program, I sincerely doubt that they would not be able to do the same for C++.

    --
    There: Something at a specific location.
    Their: Owned by someone.
    Please make sure your english compiles.
  45. Shapiro's take on this by Peaker · · Score: 3, Interesting

    Shapiro is the guy working on a research Operating System project (The EROS system).

    EROS was originally implemented in C++, but then
    it was reimplemented in C.

  46. Re:Dumb Person... by rjh · · Score: 5, Insightful

    First, you're not dumb; you just don't know much about the issue. Which is good: it means you know a lot more than a lot of the people who have been responding so far.

    Essentially, C++ offers support for many, many different types of programming. Just like there are some tasks for which object-orientation is better than procedural, there are some projects for which generics are superior, for which functional programming is superior, etc., etc.

    C++ is not an object-oriented language and was never intended to be (as reading Stroustrup will tell you); C++ was meant to support a broad variety of programming styles, of which object-oriented programming is just one.

    So what do we gain by allowing the kernel to use C++? Mostly, we allow kernel programmers flexibility to solve problems in different ways. However, the trick to this is that while we're giving the programmers additional tools with which to do their jobs, we're giving them more complex tools which sometimes fail in extremely bad ways.

    Exceptions are a good example. Up until very recently, code that used exceptions was about 5% slower than code that was exception-free. This five percent penalty was unavoidable overhead. Now, some people got bit by this five percent hit (usually people working in realtime fields) and came to the conclusion of "oh, C++ sucks for RTOS because exceptions give a five percent hit".

    The reason why they came to that conclusion is easy to understand: it's easier to blame their tool than their knowledge of the tool. It's easy to say "oh, C++ sucks"; it's harder on the ego to say "well, I didn't know that about C++, and it bit me in the ass."

    Many--and maybe most--people who condemn C++ have not used it recently. Linus, for instance, condemns C++ based on his experiences with it from 1992, six years before the C++ language had been standardized and ten years before GNU got a decent C++ compiler.

    C++ is a very complex language, as anyone, even C++ aficionados, will tell you. On the other hand, in the hands of someone who's made the (significant) investment to become a skilled C++ programmer, C++ is capable of breathtaking power and elegance.

    The conflict is essentially this: one side believes "if we add C++ support to the kernel, we'll have lots of incompetent C++ people doing all manner of incompetent C++ things which are really stupid and killing performance" and the other believes "with C++ support to the kernel, we give programmers different ways to solve approach problems, and I'm not going to deny all programmers the benefit of C++ just because many programmers can't use it effectively."

    I sincerely think that adding C++ support to the kernel is a good idea, subject to some strict requirements. For instance, have a C++ Czar for the kernel, someone Linus trusts to have wisdom and understanding of C++; and make sure that all C++ checkins to the kernel go through the C++ Czar to ensure that C++ is being used wisely, and not as an impediment to understanding.

  47. The kernel is too bloated as it is... by jedimark · · Score: 3, Insightful
    Something tells me the kernel tree needs a major prune... it's damn well past rewrite time. 36Mb download now? Come on, this is getting rediculous!

    Ged rid of all these crappy drivers and related crap out of the kernel source tree, and just provide the basics. They should start a new sister project for maintaining drivers, and split them up too for goodness sake. Why should I have to diff the whole stinking tree, if i've made a few changes to a networking components? or added a soundcard driver?

    BEOS was onto a good thing using the microkernel, completely seperate subsections for drivers, and the ability to control teams of processes - these would all be very useful in a mainstream O/S.

    C++ output may be a bit larger, but isn't all that bad, objects are very easy to visualise, and the source usually ends up smaller. Kernel Modules with a better designed interface would be an good start. And if C++ could help out here, why not?

    It's about time the kernel guys opened up to a some fresh ideas. Sure, linux is already an awesome O/S, but you can't fight an the evil dragon wearing nothing but asbestos undies...

    As long as they keep STL out of the kernel I will be happy. (imho templates make code look butt ugly and a behemoth to maintain)

  48. What about BeOS? by JohnDeHope3 · · Score: 3, Insightful

    I thought the BeOS was written all in C++ and it was darn fast. Or perhaps just the public API was C++ and the actual stuff underneath was C? I dunno. I liked the BeOS. Hmm that RC5 cd is around here someplace...

    1. Re:What about BeOS? by Anonymous Coward · · Score: 2, Informative

      Be had a strict "no c++ in the kernel" rule. You're correct in that they did use c++ extensively in user space.

  49. Approach -- and meet by devphil · · Score: 2, Interesting


    Even g++ can give the zero-overhead ideal for exceptions. It's heavily dependant on the platform and the platform-specific ABI.

    Linux on x86 ain't one of those platforms.

    --
    You cannot apply a technological solution to a sociological problem. (Edwards' Law)
  50. Re:C++ isn't needed to do kernel OOP by jedimark · · Score: 3, Interesting
    Sure you can - if you like doing all the dirty work yourself... (not that anythings wrong with dirty work :-)

    Although sometimes it is good to throw in a little abstraction. Being able to visualise some things on a different level really does help a programmer wrap their head around difficult issues that can't easily be solved going the hard yards..

    For example, learning forth as a kid did wonders for me being able to get a very solid grasp on recursion. True, it's not something you use everyday, but it's a different way to think, and some problems can only be solved (efficiently) that way.

    (My point is...) Having a few different programming models at your disposal is not such a bad thing. Yes, along with C++ comes a little bloat, but it also includes C in the bargain. It'd be nice having a little choice for those who want it.

    My language of choice these days is a hybrid of C and C++ (well, more lazy C++) - sure it means I have to link in an extra library, but I can break out with a different model when I see a real need for it.

    It is a little different at the kernel level, but their really isn't much stopping that extra bloat being included when a module is loaded.

  51. C's reason for existence; BSD versus Linux by bcrowell · · Score: 2, Insightful
    A few random thoughts about this:
    1. Choosing a programming language is all about choosing the right tool for the job. To me, the last couple of decades' worth of buffer overflow exploits show that C is not the right tool for writing application programs. Still, there was always at least one big justification for the continued existence of C: low-level OS programming. If there were really signs of migration away from using C for that job, then I'd really start wondering whether C was anything more than a legacy language.
    2. I would've actually gone the other direction: C is too big and complicated for OS programming, and includes too many unnecessary features. For example, it's perfectly possible to write an OS without ever using floating point.
    3. C++ would be a badly designed language if you considered it only in its own right. The only reason it had to be complicated and crufty is that it was designed for backward compatibility with C. But if C is becoming irrelevant, then why should we saddle ourselves with a bag-on-the-side like C++ for the sake of C compatibility?
    4. I assume Linus will reject the patch, but if the Linux kernel ever did become C++-based, this would be an interesting new differentiation between Linux and BSD. BSD already has the edge in server performance, and I assume that a switch from C to C++ would incur at least somewhat of a performance hit.
    5. Does anyone know if C++ is in use in other kernels, such as Hurd, Mach, or Plan 9?
    1. Re:C's reason for existence; BSD versus Linux by downbad · · Score: 2, Informative

      according to these benchmarks, linux 2.6 is faster freebsd 5.1.

  52. Re:Question by multipartmixed · · Score: 2, Interesting

    Different strokes for different folks.

    You're a CS student in college, you don't really need to know. What you need to spend all your time doing is learning how to PROGRAM and do it well.

    Worry about the specific tools later. You could do just as well with just about any language of the right paradigm. C++ is actually a mixed-paradigm language, not all that great for teaching.

    --

    Do daemons dream of electric sleep()?
  53. Re: exceptions vs return values by Anonymous Coward · · Score: 2, Interesting
    The parent poster has the right idea when he said "if you ever throw exceptions exclusively at one level and catch them exclusively at the next level up, there's a good chance you're using the wrong tool for the wrong job."

    In theory, an exception is just a more expedient return statement -- it lets you immediately branch to the handler. In some sense, they're a bit like using setjmp/longjmp, labeled branches (a feature not found in C/C++), or continuations (another feature not found in C/C++). But it also means that there is absolutely no benefit provided if you only use it as an alternate means of returning to the caller.

    Exception handler addresses can be pushed onto the processor stack just like the return instruction pointer (or they can be pushed onto a separate exception stack). Any function that needs to do exception 'cleanup work' can push its own exception address instead of its caller's.
    a() catches
    b() ^
    c() |
    d() |
    e() throws
    If you're passing an exception through multiple functions, raising an exception can bypass significant number of comparisons and jumps. It also reduces clutter in the intermediate functions that don't have to bother testing for an error condition and passing back a return value.

    However, in C++ you run into the situation where 1) nearly EVERY function has an implicit exception handler to calls all the destructors for the stack variables, and 2) optional exception handlers require expensive runtime typechecking comparisons to see which handler gets to run. The former means you don't end up saving much with C++ catch-all exceptions (i.e. "(...)"), and the latter means you actually end up losing performance with type-specific exception handlers! The article mentions using pointer comparisons here to help reduce this performance hit.

    Basically you use C++ exceptions for convenience/safety, not performance. They're particularly useful when you're calling 'unknown' code like virtual functions/function pointers (in other words: drivers), and that's why there's interest in using them in the kernel.
  54. kinda useless... by Ayanami+Rei · · Score: 3, Interesting

    Having a linux kernel running as a layer on top of a JVM is kinda useless since it's designed to run some sort of native binaries. So the question becomes: which target architecture do you then emulate in the JVM to accomodate the user space programs, or do you force all userland apps to be java bytecode as well? Then what's the point? Just use straight java on the JVM.

    Really, more useful would be a full-fledged java-based x86 or whatever simulator with emulated hardware that a kernel would target. Then any standard propietary binaries could run in that, and even be migrated across an java cluster.

    --
    THIS THING CAN TURN ON A DIME, MACROSSZERO STYLE ALSO FUCK BETA, ~NYORON
  55. wait a minute.. by tasinet · · Score: 2, Funny

    ..you mean the linux kernel isn't written in Visual Basic?

  56. Re:"The fact is..." he's out of touch by alder · · Score: 2, Informative
    It doesn't add C++ support to the kernel...
    That's not what the articel says ;-) - "We have implemented a complete kernel level run-time support for C++ in the Linux kernel." And a bit farther: "The implementation of the C++ ABI is based on the implementation provided with the source of the GNU g++ compiler. We modified it to run in kernel space..."
  57. Advantages of C++ by Spy+der+Mann · · Score: 2, Informative

    If the Kernel is C++, this means the API calls can ALSO be C++ (with some restrictions, of course). This could mean no more kernel-recompiling for loading modules, no more .so recompiling and ending the .os dependancy hell...

    What we're talking about is using a whole new computing paradigm in the very core of an operating system. (it may be not new for apps, but for the kernel... just think about it).

    As an OOP'er, I'm frankly excited by the idea.

    And no, we're not talking about interpreted runtime languages like C# or java. We're talking about the REAL thing.

    C++ means that the code will be easier to maintain, changes will be easier to track, and who knows. Perhaps a boost in the development that might JUST be what Linux needs to defeat Winblows as the next Desktop OS.

  58. It's just discipline by Julian+Morrison · · Score: 2, Insightful

    You can do stupid juvenile garble in C too, like rewrite the reserved words with #define macros. You don't because it's dumb and because Linus would laugh his ass off and tell you to throw it away, go read "C for dummies" and try again.

    Nobody's forcing you to use C++ features where they would be a bad idea.

  59. You obviously have little real world experience by Viol8 · · Score: 2, Insightful

    "If someone tells me that they are a C/C++ programmer, I'm going to assume they're a novice at both languages."

    Thats an assanine statement to make. I've been a professional programmer for 11 years, most of that doing C AND C++. Yes thats using both languages or a mixture of the 2 depending on what project I've worked on. And I'm quite happy doing either high level OO template programming (C++) or low level boolean bit operations, memory management, function pointers etc (C). Most people I know who do C/C++ would have the same ability and most people I've interviewed myself I would expect the same off. If they can't handle malloc & free they're as useless to me as if they can't handle temaplates.

    "in my head I know that the interview is probably already over."

    Then I suspect you're probably responsible for your company not hiring a lot of good people since you obviously have an arrogant attitude and give the impression that only you can be master of both. If you worked for me I'd never let you near an interview room.

  60. Obligatory Quote by zerojoker · · Score: 2, Funny

    Object-oriented programming is an exceptionally bad idea which could only have originated in California. (Edsger Dijkstra)

  61. Templates by wtd · · Score: 2, Informative

    You miss what is probably the biggest advantage of C++ (and possibly one of the most controversial).

    Templates allow for some incredibly slick code, and vastly improve both programmer productivity and type safety.

  62. C++? Why no love for... by l4m3z0r · · Score: 3, Interesting

    Whats wrong with objective-c. I would consider that to be a much more viable option for adding object support into the linux kernel because thats basically what we are talking about. Without objects C++ offers no real benefit over C and in fact with the absence of objects is a detrement. Objective-C on the other hand is pure C with some nifty object support stapled on. Way better and in my opinion much more likely to be accepted by them kernel folks.

  63. Re:You have no idea what OO is all about. by ChrisMDP · · Score: 2, Insightful

    I respectfully disagree, having spent several years of my life coding C++ and Java professionally.

    There's more to OO than mere polymorphism. Encapsulation is a very useful feature in its own right. By 'could cause problems', read 'could cause problems in kernel development'. For example, virtual functions require lookups and dereferencing at runtime, and the vtable arbitrarily increases the size of an object, both of which are undesirable in kernel development.