FAQ/BUG

BUG() and BUG_ON(condition) are used as a debugging help when something in the kernel goes terribly wrong. When a BUG_ON() assertion fails, or the code takes a branch with BUG() in it, the kernel will print out the contents of the registers and a stack trace. After that the current process will die.

The following are examples of how BUG() and BUG_ON() are used, from a piece of code that is not supposed to run in interrupt context. The explicit if with BUG() is the coding style used in older kernels. In the 2.6 kernel, generally BUG_ON() is preferred.

if (in_interrupt())
BUG();
BUG_ON(in_interrupt());

How it works

#define BUG() __asm__ __volatile__("ud2\n")

BUG() is defined as an invalid instruction, which means the CPU will throw an invalid opcode exception. This is caught in arch/i386/kernel/entry.S, in the invalid_op entry point, which calls the generated function do_invalid_op from arch/i386/kernel/traps.c. The following macros generate the do_invalid_op() function:

The do_trap() function will discover that the trap happened while running in kernel mode, and that there is no fixup for exceptions that happen while running at this address. See FAQ/TestWpBit to learn about exception fixups.