5f3759df 0x
5f3759df 0x

Reputation: 17

A assertion succeed in userspace but failed in kernel

I am new to linux kernel and I found a strange behavior when I use "BUG_ON".

This is my sample code in userspace, doing comparison on 16-bit integer:

#include <stdio.h>
#include <assert.h>

typedef unsigned short digit;

int main(){
#define Bn_SHIFT ((sizeof(digit) << 3) - 1)
#define Bn_MASK ((digit)((1 << Bn_SHIFT) - 1))
       digit carry = 3694;
       printf("Assert(carry <= Bn_MASK), carry=%d, Bn_MASK=%d ", carry, Bn_MASK);
       assert(carry <= Bn_MASK);
#undef Bn_SHIFT
#undef Bn_MASK
    return 0;
}

It runs well with the following command:

~$ gcc userspace.c -o userspace -O0 -Werror -Wall -g
~$ ./userspace
Assert(carry <= Bn_MASK), carry=3694, Bn_MASK=32767

To implement above function in kernel module, I forked kobject-example.c and modified with it:

--- kobject-example-original.c    2021-05-17 16:02:15.952798660 +0800
+++ kobject-example.c   2021-05-17 14:45:00.851229416 +0800
@@ -10,6 +10,7 @@
 #include <linux/sysfs.h>
 #include <linux/module.h>
 #include <linux/init.h>
+#include <linux/bug.h>
 
 /*
  * This module shows how to create a simple subdirectory in sysfs called
@@ -22,12 +23,23 @@
 static int baz;
 static int bar;
 
+typedef unsigned short digit;
+
 /*
  * The "foo" file where a static variable is read from and written to.
  */
 static ssize_t foo_show(struct kobject *kobj, struct kobj_attribute *attr,
                        char *buf)
 {
+
+
+#define Bn_SHIFT ((sizeof(digit) << 3) - 1)
+#define Bn_MASK ((digit)((1 << Bn_SHIFT) - 1))
+       digit carry = 3694;
+       printk("BUG_ON(carry <= Bn_MASK), carry=%d, Bn_MASK=%d ", carry, Bn_MASK);
+       BUG_ON(carry <= Bn_MASK);
+#undef Bn_SHIFT
+#undef Bn_MASK
        return sprintf(buf, "%d\n", foo);
 }

Makefile:

CONFIG_MODULE_SIG = n
TARGET_MODULE := kobject-example

obj-m := $(TARGET_MODULE).o
ccflags-y := -std=gnu99 -Wno-declaration-after-statement -g -O0

KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)

all:
    $(MAKE) -C $(KDIR) M=$(PWD) modules

However, when I ran it, the BUG_ON was triggered.

~$ make && sudo ismod kobject-example.ko
~$ cat /sys/kernel/kobject_example/foo
Segmentation fault

I think this problem is not related to integer conversion, because the rank of carry is less than Bn_MASK(32-bit integer) and the carry will be implicitly converted to 32-bit integer when doing comparison.

Can somebody give me a hint?

Upvotes: 0

Views: 176

Answers (1)

user14215102
user14215102

Reputation:

assert fails when the condition is false

BUG_ON fails when the condition is true, see https://kernelnewbies.org/FAQ/BUG

Your condition is true.

Upvotes: 3

Related Questions