Re: [PATCH] init/initramfs.c: check the return value of kstrdup()

From: Xiaoke Wang
Date: Fri Mar 04 2022 - 10:55:52 EST


On Fri, 04 Mar 2022 22:14:21 +0800, Greg KH <gregkh@xxxxxxxxxxxxxxxxxxx> wrote:
>> struct dir_entry *de = kmalloc(sizeof(struct dir_entry), GFP_KERNEL);
>> if (!de)
>> panic_show_mem("can't allocate dir_entry buffer");
>> - INIT_LIST_HEAD(&de->list);
>> de->name = kstrdup(name, GFP_KERNEL);
>> + if (!de->name) {
>
> How can this fail? Have you ever hit this in real life?
>
>> +kfree(de);
>> +panic_show_mem("can't duplicate dir name");
>
> Why are you freeing memory if you are panicing?
>
> How was this tested?

Thank you for taking the time.
I found this with a static tool, without dynamic testing.
kstrdup() allocates memory for copying the string and I noticed all the
other allocation functions in this file have the check for their return
value such as `de` on the above code. So I suppose this is also needed
to be checked and I intuitively add kfree() on the error path.
I'm sorry to bother you if this is actually unnecessary.

Regards,
Xiaoke Wang