Manual Page Search Parameters

KASSERT(9) Kernel Developer's Manual KASSERT(9)

KASSERTkernel expression verification macros

options INVARIANTS


#include <sys/param.h>
#include <sys/systm.h>

KASSERT(expression, msg);

MPASS(expression);

Assertions are widely used within the FreeBSD kernel to verify programmatic assumptions. For violations of run-time assumptions and invariants, it is desirable to fail as soon and as loudly as possible. Assertions are optional code; for non-recoverable error conditions an explicit call to panic(9) is usually preferred.

The () macro tests the given boolean expression. If expression evaluates to false, and the kernel is compiled with options INVARIANTS, the panic(9) function is called. This terminates the running system at the point of the error, possibly dropping into the kernel debugger or initiating a kernel core dump. The second argument, msg, is a printf(9) format string and its arguments, enclosed in parentheses. The formatted string will become the panic string.

In a kernel that is built without options INVARIANTS, the assertion macros are defined to be no-ops. This eliminates the runtime overhead of widespread assertions from release builds of the kernel. Therefore, checks which can be performed in a constant amount of time can be added as assertions without concern about their performance impact. More expensive checks, such as those that output to console, or verify the integrity of a chain of objects are generally best hidden behind the DIAGNOSTIC kernel option.

The () macro (read as: "must-pass") is a convenience wrapper around KASSERT() that automatically generates a sensible assertion message including file and line information.

A hypothetical struct foo object must not have its 'active' flag set when calling foo_dealloc():

void
foo_dealloc(struct foo *fp)
{

	KASSERT((fp->foo_flags & FOO_ACTIVE) == 0,
	    ("%s: fp %p is still active", __func__, fp));
	...
}

The assertion

MPASS(td == curthread);

located on line 87 of a file named foo.c would generate the following panic message:

panic: Assertion td == curthread failed at foo.c:87

panic(9)

This manual page was written by Jonathan M. Bresler <jmb@FreeBSD.org> and
Mitchell Horne <mhorne@FreeBSD.org>.

March 16, 2023 release-23.11