[PATCH] kexec: check size before trying the malloc

HATAYAMA Daisuke d.hatayama at jp.fujitsu.com
Thu Mar 14 06:26:10 EDT 2013


From: Simon Horman <horms at verge.net.au>
Subject: Re: [PATCH] kexec: check size before trying the malloc
Date: Thu, 14 Mar 2013 09:37:03 +0100

> On Thu, Mar 14, 2013 at 01:16:25AM +0800, Zhang Yanfei wrote:
>> From: Zhang Yanfei <zhangyanfei at cn.fujitsu.com>
>> 
>> If size is zero, it is unnecessary to do the malloc operation.
>> So checking size first is better than doing malloc first.
>> 
>> Signed-off-by: Zhang Yanfei <zhangyanfei at cn.fujitsu.com>
> 
> Thanks, applied.
> 

Wait. The check should not be removed.

The behaviour when malloc() receives 0 as size is
implementation-defined. man malloc explains this:

     cannot be  allocated, a null  pointer shall be  returned. If
     the  size of  the  space  requested is  0,  the behavior  is
     implementation-defined: the value returned shall be either a
     null pointer or a unique pointer.

For example, on fedora 18 environement, malloc returns some object as
follows:

$ cat ./test.c
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
        printf("%p\n", malloc(0));

        return 0;
}
$ gcc ./test.c -o test
$ ./test
0x1451010
$ rpm -qa | grep glibc
glibc-2.16-28.fc18.x86_64

Normally, object returned by allocator consists of header part plus
data part. This returned size might have header part only, I'm not
sure. The programmer usually expects the size to be positive, so this
bug typically leads to buffer overrun.

Anyway, it must be abnormal case when 0 is passed to malloc() as
size. As explained in patch description, it's best if it's possible to
check the size before calling malloc(). But it's impossible to make
sure that everyone does that; so bug happens. There's no reason to
remove the zero check.

Thanks.
HATAYAMA, Daisuke




More information about the kexec mailing list