clinuxlinux-kernelmemsetkmalloc

Linux kernel NULL-pointer dereference in memset from kzalloc


Quite by chance stumbled upon some code in kernel jungles and was a bit confused. There are two implementations of kzalloc(): in tools/virtio/linux/kernel.h and the main one in linux/slab.h. Obviously, in most cases the second one is used. But sometimes the "virtio" kzalloc() is used.

"virtio" kzalloc() looks like this:

static inline void *kzalloc(size_t s, gfp_t gfp)
{
    void *p = kmalloc(s, gfp);

    memset(p, 0, s);
    return p;
}

My confusion is that "fake" kmalloc() used inside "tools" directory can return NULL-pointer. Also it looks like the memset() implementation doesn't check NULL-pointers so there could be NULL-pointer dereference. Is it a bug or am I missing something?


Solution

  • Yes, that definitely looks like a bug.

    The tools/ subdirectory is a collection of user space tools (as the name suggests). You can also see this by the fact that several C standard library headers are included. So this of course is not a kernel bug (that would have been very bad), just a minor oversight in the virtio testing tool.

    That virtio testing tool seems to re-define some kernel APIs to mock their behavior in userspace. That function though doesn't seem to be ever used in practice, just merely defined.

    marco:~/git/linux/tools/virtio$ grep -r kzalloc
    linux/kernel.h:static inline void *kzalloc(size_t s, gfp_t gfp)
    ringtest/ptr_ring.c:static inline void *kzalloc(unsigned size, gfp_t flags)
    marco:~/git/linux/tools/virtio$
    

    It's probably meant to be used by someone who wishes to test some virtio kernel code in userspace.


    In any case, you could try reporting the bug. The get_mantainer.pl script suggests:

    $ perl scripts/get_maintainer.pl -f tools/virtio/linux/kernel.h
    Bad divisor in main::vcs_assign: 0
    "Michael S. Tsirkin" <mst@redhat.com> (maintainer:VIRTIO CORE AND NET DRIVERS)
    Jason Wang <jasowang@redhat.com> (maintainer:VIRTIO CORE AND NET DRIVERS)
    virtualization@lists.linux-foundation.org (open list:VIRTIO CORE AND NET DRIVERS)
    linux-kernel@vger.kernel.org (open list)