Subject: Re: [PATCH] netlink: don't copy over empty attribute data

From: Andrey Ryabinin <[email-masked]>
Date: Mon, 27 Oct 2014 19:46:33 +0300

On 10/27/2014 05:42 PM, Sasha Levin wrote:
> On 10/26/2014 10:03 PM, David Miller wrote:
>> From: Sasha Levin <[email-masked]>
>> Date: Sun, 26 Oct 2014 19:32:42 -0400
>>
>>> How so? GCC states clearly that you should *never* pass a NULL
>>> pointer there:
>>>
>>> "The pointers passed to memmove (and similar functions in <string.h>) must
>>> be non-null even when nbytes==0" (https://gcc.gnu.org/gcc-4.9/porting_to.html).
>>>
>>> Even if it doesn't dereference it, it can break somehow in a subtle way. Leaving
>>> the kernel code assuming that gcc (or any other compiler) would always behave
>>> the same in a situation that shouldn't occur.
>>
>> Show me a legal way in which one could legally dereference the pointer
>> when length is zero, and I'll entertain this patch.
> 
> The moment you've triggered an undefined behaviour you have GCC license to
> dereference anything it wants. GCC would be well within it's rights
> dereferencing a NULL "from".
> 
> They even state it clearly in that GCC 4.9 porting guide I've linked above:
> 
> """
> Calling copy(p, NULL, 0) can therefore deference a null pointer and crash.
> 
> The example above needs to be fixed to avoid the invalid memmove call, for example:
> 
> 
>     if (nbytes != 0)
>       memmove (dest, src, nbytes);
> """
> 

In example from link null ptr deref could happen because GCC will optimize away null pointer check after
memmove():

int copy (int* dest, int* src, size_t nbytes) {
    memmove (dest, src, nbytes);
    if (src != NULL)  <---- GCC will eliminate this check because src can't be null.
      return *src; <-- NULL ptr deref
    return 0;
  }

Even though GCC and C standard treats such code ( memmove(dest, NULL, 0); ) as invalid, it probably will not crash in linux kernel case,
because that kind of optimization disabled via -fno-delete-null-pointer-checks option.

> Thanks,
> Sasha