Re: Useful KERNEL_ASSERT Macro

Horst von Brand (
Sun, 01 Aug 1999 19:49:53 -0400

Jordan Mendelson <> said:
> Tim Hockin wrote:
> >
> > > The following ASSERT macro seems adequate:
> > >
> > > #ifdef KERNEL_ASSERT
> > > #define KERNEL_ASSERT(expr) (expr || printk(KERN_DEBUG "%s/%d: Assertion fa
> iled!
> > > %s\n", __FILE__, __LINE__, #expr));
> > > #else
> > > #define KERNEL_ASSERT(expr) 0
> > > #endif

Why an expression, and not a statement? (Yes, I know this is C,
but...). Besides, the first version will return "true" always (either expr
is zero, in which case you get what printk() returns, or expr is true). The
second one will return "false" always. So the instrumented code will do
different things according to KERNEL_ASSERT...

Better take a look at the way assertions are handled in glibc (assert(3))

> > /* a general purpose kernel assert macro */
> > #define KERNEL_ASSERT(expr) if (!(expr)) \
> > printk(KERN_DEBUG "KASSERT: %s:%d" \
> > " - Assertion failed! (%s)\n", \
> > __FILE__, __LINE__, #expr)
> > #else
> > #define KERNEL_ASSERT(expr)
> > #endif

Do wrap this kind of stuff into "do { ... } while(0)"! If not, it _will_
screw up if's.

> > We could expand this debugging "macro library" quite a lot. I think it
> > would be worthwhile, if we can convince everyone to USE it. It would
> > cut a lot of redundant definitions of ASSERT and DEBUG_PRINT sorts of
> > macros.

> They both do the same thing, (expr || printk(...)) will cause the printk
> to only evaluate when expr is false, it's just a more compact way of
> writing it.

A bit too cute code, IMHO.

> But yeah, I think it would be a worthwhile thing to do and people
> shouldn't really be worrying about only enabling it in various functions,
> this particular KERNEL_ASSERT() macro should only be used to make sure a
> particular expression is true... if it's false, it's a bug and someone
> needs to fix it. Enabling this macro on a 100% working system should
> never result in any printk()'s...

... but result in massive bloat, and hang the system when an failed
assertion is hit (printk() can't be called everywhere!)

> So if your ethernet driver is having it's memory not allocated correctly,
> a KERNEL_ASSERT() in the memory subsystem and the ethernet driver would
> help you to understand why whereas enabling it just in the ethernet
> driver may not.

AFAIU, Linus doesn't want this kind of stuff in the kernel, for good
reason: It is bloat when enabled, and useless when disabled.

> Just food for thought.


Horst von Brand                   
Casilla 9G, Viņa del Mar, Chile                               +56 32 672616

- To unsubscribe from this list: send the line "unsubscribe linux-kernel" in the body of a message to Please read the FAQ at