Bug 393099 - posix_memalign() invalid write if alignment == 0
Summary: posix_memalign() invalid write if alignment == 0
Status: RESOLVED FIXED
Alias: None
Product: valgrind
Classification: Developer tools
Component: memcheck (show other bugs)
Version: 3.13.0
Platform: Debian stable Linux
: NOR normal
Target Milestone: ---
Assignee: Julian Seward
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2018-04-13 10:26 UTC by Gabriel Ganne
Modified: 2018-04-16 08:27 UTC (History)
2 users (show)

See Also:
Latest Commit:
Version Fixed In:


Attachments
posix_memalign() test (744 bytes, text/x-csrc)
2018-04-13 10:26 UTC, Gabriel Ganne
Details

Note You need to log in before you can comment on or make changes to this bug.
Description Gabriel Ganne 2018-04-13 10:26:30 UTC
Created attachment 111999 [details]
posix_memalign() test

Hi,

The attached file tests posix_memalign() with an invalid alignment of 0.
The expected behavior is for posix_memalign() to return EINVAL and to leave memptr untouched, or to set it to NULL.

I propose the following patch I made on valgrind-3.13.0 sources :
* add a test on alignment == 0
* set mem to NULL explicitely so as to be validly test its value after calling posix_memalign() on failure

--- ./coregrind/m_replacemalloc/vg_replace_malloc.c.orig
+++ ./coregrind/m_replacemalloc/vg_replace_malloc.c
@@ -997,11 +997,11 @@
    int VG_REPLACE_FUNCTION_EZU(10160,soname,fnname) \
           ( void **memptr, SizeT alignment, SizeT size ) \
    { \
-      void *mem; \
+      void *mem = NULL; \
       \
       /* Test whether the alignment argument is valid.  It must be \
          a power of two multiple of sizeof (void *).  */ \
-      if (alignment % sizeof (void *) != 0 \
+      if (alignment == 0 || alignment % sizeof (void *) != 0 \
           || (alignment & (alignment - 1)) != 0) \
          return VKI_EINVAL; \
       \
Comment 1 Philippe Waroquiers 2018-04-15 06:15:19 UTC
Fix committed as 846aee3e402c4430139cce011ab8420f434532d1
and d9204e9eedc8a671e6f035318d28cb55440c3a8b.

Note that I only added the additional condition checking for 0 alignment,
as the assignment to mem has no effect (the result is in *memptr)
and posix_memalign man states:
      "On Linux (and other systems), posix_memalign() does not  modify  memptr
       on  failure.   A  requirement  standardizing this behavior was added in
       POSIX.1-2016."

Thanks for the bug and analysis
Comment 2 Gabriel Ganne 2018-04-16 08:27:28 UTC
Great thanks !