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

47 of 850 comments (clear)

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

    how long until c# is supported?

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

    2. 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"...

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

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

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

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

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

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

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

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

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

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

  8. 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 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?
    2. 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...

    3. 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.
  9. 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

  10. 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))

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

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

  13. 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
  14. 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
  15. 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!
  16. 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.

  17. 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!
  18. 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.

  19. 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.
  20. Linus and C++ in the kernel by noselasd · · Score: 4, Informative

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

  21. 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 ;-)

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

  23. 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).

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

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

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

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