Sunday, November 24, 2013

Force a Kernel Panic


Have you ever wanted to generate a kernel panic, for kernel testing purposes?

A few ways to generate a kernel panic, a kernel oops and reboots:
# echo 1 > /proc/sys/kernel/panic
# dd if=/dev/random of=/dev/port
# cat /dev/port
# cat /dev/zero > /dev/mem
Forcing an Alt-SysReq-c command from the console:
# echo c > /proc/sysrq-trigger

To generate a kernel panic from source code, we will need to compile a kernel module from the kernel source: (source)
// source: force_panic.c
#ifdef __KERNEL__

/* Makefile :
obj-m := force_panic.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)

default:
 $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules
*/

#include <linux/module.h>
#include <linux/kernel.h>

static int __init panic_init(void) {
  panic("force-panic");
  return 0;
}

static void __exit panic_exit(void) {
}

module_init(panic_init);
module_exit(panic_exit);

#endif
Generate a kernel oops: (source)
static int crash_module_init(void) {
     printf("crash module starting\n");
     int *p = 0;

     printk("%d\n", *p);

     return 0;
}

static void crash_module_exit(void) {
    printf("crash module exiting\n");
}

module_init(crash_module_init);
module_exit(crash_module_exit);



No comments: