Using assertion in the Linux kernel

后端 未结 6 1147
挽巷
挽巷 2021-02-05 03:09

I have a question about assert() in Linux: can I use it in the kernel?

If no, what techniques do you usually use if, for example I don\'t want to enter NULL

相关标签:
6条回答
  • 2021-02-05 03:34

    No. Unless you're working on the kernel core and rather on a module, you should do your best to never crash (technically, abort()) the kernel. If you don't want to use a NULL pointer, just don't do it. Check it before using it, and produce an error log if it is.

    The closest thing you might want to do if you're actually handling a fatal case is the panic() function or the BUG_ON and WARN_ON macros, which will abort execution and produce diagnostic messages, a stack trace and a list of modules.

    0 讨论(0)
  • 2021-02-05 03:41

    I use this macro, it uses BUG() but adds some more info I normally use for debugging, and of course you can edit it to include more info if you wish:

    #define ASSERT(x)                                                       \
    do {    if (x) break;                                                   \
            printk(KERN_EMERG "### ASSERTION FAILED %s: %s: %d: %s\n",      \
                   __FILE__, __func__, __LINE__, #x); dump_stack(); BUG();  \
    } while (0)
    
    0 讨论(0)
  • 2021-02-05 03:43

    BUG_ON() is the appropriate approach to do it. It checks for the condition to be true and calls the macro BUG().

    How BUG() handles the rest is explained very well in the following article:

    http://kernelnewbies.org/FAQ/BUG

    0 讨论(0)
  • 2021-02-05 03:46

    Well, dereferencing null pointer will produce an oops, which you can use to find the offending code. Now, if you want to assert() a given condition, you can use

    BUG_ON(condition)
    

    A less lethal mechanism is WARN_ON, which will produce a backtrace without crashing the kernel.

    0 讨论(0)
  • 2021-02-05 03:49

    One option would be to use the macro BUG_ON(). It will printk a message, and then panic() (i.e. crash) the kernel.

    http://kernelnewbies.org/KernelHacking-HOWTO/Debugging_Kernel

    Of course, this should only be used as an error handling strategy of last resort (just like assert)...

    0 讨论(0)
  • 2021-02-05 03:51

    The corresponding kernel macros are BUG_ON and WARN_ON. The former is for when you want to make the kernel panic and bring the system down (i.e., unrecoverable error). The latter is for when you want to log something to the kernel log (viewable via dmesg).

    As @Michael says, in the kernel, you need to validate anything that comes from userspace and just handle it, whatever it is. BUG_ON and WARN_ON are to catch bugs in your own code or problems with the hardware.

    0 讨论(0)
提交回复
热议问题