[PATCH] added option to detect malloc(0) as error with ASAN

Kostya Serebryany kcc at google.com
Mon Mar 17 00:01:15 PDT 2014


+  if (size == 0 && common_flags()->detect_malloc_zero)
+    ReportIfMallocZero("memalign", stack);

I would prefer to pass 'size' as parameter and do both checks inside
ReportIfMallocZero.
You will also need to add tests with this flag on, off, and unset
 (similar to test/asan/TestCases/memcmp_strict_test.cc)

I may have more comments, so please send the change using
llvm.org/docs/Phabricator.html

Thanks!

--kcc



On Sun, Mar 16, 2014 at 12:29 AM, Dominique Pellé <dominique.pelle at gmail.com
> wrote:

> Hi
>
> Attached is a patch to detect call of malloc with size 0 as an
> error with ASAN. Calling malloc(0) is admittedly not necessarily
> incorrect, so the check is disabled by default and can be enabled
> by adding 'detect_malloc_zero=1' to the environment variable
> ASAN_OPTIONS. Behavior of malloc(0) depends on platforms:
> it returns an address on most platforms but returns NULL at
> least on AIX. So calling malloc(0) is a source of portability bugs.
>
> This is my fist clang patch and I'm not sure whether the patch is
> the best way to do that. Perhaps it would be better if UBSAN
> detected it rather than ASAN.
>
> Here is an example to illustrate:
>
> ===
> $ cat test-malloc0.cpp
>
> #include <cstdlib>
> #include <cstdio>
>
> int main(int argc, char *argv[])
> {
>   char *c = (char *)malloc(atoi(argv[1]));
>   if (c == NULL) {
>     fprintf(stderr, "Failed to allocate\n");
>     return -1;
>   }
>   free(c);
>   return 0;
> }
>
>
> $ clang++ --fsanitize=address
> $ ./a.out 0
> (no error reported by default, option needs to be enabled in ASAN_OPTIONS)
>
>
> $ export ASAN_OPTIONS=detect_malloc_zero=1
> $ ./a.out 0
> =================================================================
> ==7999==ERROR: malloc with 0 size is platform dependent
>     #0 0x46d52b in malloc
> /home/pel/sb/llvm/projects/compiler-rt/lib/asan/asan_malloc_linux.cc:75
>     #1 0x488314 in main (/home/pel/sb/a.out+0x488314)
>     #2 0x7ffd07136de4 in __libc_start_main
> /build/buildd/eglibc-2.17/csu/libc-start.c:260
>
> ==7999==ABORTING
>
> Regards
> Dominique
>
> _______________________________________________
> llvm-commits mailing list
> llvm-commits at cs.uiuc.edu
> http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20140317/e92d1ac7/attachment.html>


More information about the llvm-commits mailing list