kobject: Add sanity check for kset->kobj.ktype in kset_register()
authorZhen Lei <thunder.leizhen@huawei.com>
Sat, 5 Aug 2023 08:41:13 +0000 (16:41 +0800)
committerGreg Kroah-Hartman <gregkh@linuxfoundation.org>
Sat, 19 Aug 2023 17:37:53 +0000 (19:37 +0200)
When I register a kset in the following way:
static struct kset my_kset;
kobject_set_name(&my_kset.kobj, "my_kset");
        ret = kset_register(&my_kset);

A null pointer dereference exception is occurred:
[ 4453.568337] Unable to handle kernel NULL pointer dereference at \
virtual address 0000000000000028
... ...
[ 4453.810361] Call trace:
[ 4453.813062]  kobject_get_ownership+0xc/0x34
[ 4453.817493]  kobject_add_internal+0x98/0x274
[ 4453.822005]  kset_register+0x5c/0xb4
[ 4453.825820]  my_kobj_init+0x44/0x1000 [my_kset]
... ...

Because I didn't initialize my_kset.kobj.ktype.

According to the description in Documentation/core-api/kobject.rst:
 - A ktype is the type of object that embeds a kobject.  Every structure
   that embeds a kobject needs a corresponding ktype.

So add sanity check to make sure kset->kobj.ktype is not NULL.

Signed-off-by: Zhen Lei <thunder.leizhen@huawei.com>
Link: https://lore.kernel.org/r/20230805084114.1298-2-thunder.leizhen@huaweicloud.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
lib/kobject.c

index 14e8452..72fa20f 100644 (file)
@@ -861,6 +861,11 @@ int kset_register(struct kset *k)
        if (!k)
                return -EINVAL;
 
+       if (!k->kobj.ktype) {
+               pr_err("must have a ktype to be initialized properly!\n");
+               return -EINVAL;
+       }
+
        kset_init(k);
        err = kobject_add_internal(&k->kobj);
        if (err) {