简体   繁体   中英

How to generate a kernel oops or panic crash in Linux kernel code?

How can I generate a kernel oops or crash in kernel code? Is there a function for that?

The usual way to crash the kernel is by using BUG() macro. There's also WARN() macro, which dumps the stack down to console but the kernel keeps running.

http://kernelnewbies.org/FAQ/BUG

What happens after kernels hits a BUG() macro (which eventually results in an internal trap) or some similar error condition (like null pointer dereference) depends on a setting of panic_on_oops global variable. If it's set to 0, the kernel will try to keep running (with whatever awful consequences). If it's set to 1, the kernel will enter the panic state and halt.

If you want to crash the kernel from user space, you've got a handy <SysRq> + <c> key combo (or, alternatively, echo c > /proc/sysrq-trigger ). It's worth looking at the handler implementation for this action ( http://code.metager.de/source/xref/linux/stable/drivers/tty/sysrq.c#134 ):

static void sysrq_handle_crash(int key)
{
    char *killer = NULL;

    panic_on_oops = 1;  /* force panic */
    wmb();
    *killer = 1;
}

The handler sets the global flag to make kernel panic on traps, then tries to dereference a random null pointer.

panic() function

The kernel also has a panic() function if you want to do it from inside a kernel module code:

#include <kernel.h>

panic("my message");

It is defined at kernel/panic.c .

Here is a minimal runnable example .

Related threads:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM