util: Return valid allocation for qemu_try_memalign() with zero size
authorPeter Maydell <peter.maydell@linaro.org>
Sat, 26 Feb 2022 18:07:18 +0000 (18:07 +0000)
committerPeter Maydell <peter.maydell@linaro.org>
Mon, 7 Mar 2022 13:14:07 +0000 (13:14 +0000)
Currently qemu_try_memalign()'s behaviour if asked to allocate
0 bytes is rather variable:
 * on Windows, we will assert
 * on POSIX platforms, we get the underlying behaviour of
   the posix_memalign() or equivalent function, which may be
   either "return a valid non-NULL pointer" or "return NULL"

Explictly check for 0 byte allocations, so we get consistent
behaviour across platforms.  We handle them by incrementing the size
so that we return a valid non-NULL pointer that can later be passed
to qemu_vfree().  This is permitted behaviour for the
posix_memalign() API and is the most usual way that underlying
malloc() etc implementations handle a zero-sized allocation request,
because it won't trip up calling code that assumes NULL means an
error.  (This includes our own qemu_memalign(), which will abort on
NULL.)

This change is a preparation for sharing the qemu_try_memalign() code
between Windows and POSIX.

Signed-off-by: Peter Maydell <peter.maydell@linaro.org>
Reviewed-by: Richard Henderson <richard.henderson@linaro.org>
Reviewed-by: Philippe Mathieu-Daudé <f4bug@amsat.org>
util/oslib-posix.c
util/oslib-win32.c

index 0278902ee79df3cea00c15126bedc77e89c22ee5..f7e22f4ff9b058ff7364ec6956f3714b7d0cfb99 100644 (file)
@@ -209,6 +209,9 @@ void *qemu_try_memalign(size_t alignment, size_t size)
         g_assert(is_power_of_2(alignment));
     }
 
+    if (size == 0) {
+        size++;
+    }
 #if defined(CONFIG_POSIX_MEMALIGN)
     int ret;
     ret = posix_memalign(&ptr, alignment, size);
index 058574146951a8b269fbe1e9007aa84d6da4242c..8c28d70904de9cbfb558791b8aa9cd2d499b17c1 100644 (file)
@@ -48,12 +48,14 @@ void *qemu_try_memalign(size_t alignment, size_t size)
 {
     void *ptr;
 
-    g_assert(size != 0);
     if (alignment < sizeof(void *)) {
         alignment = sizeof(void *);
     } else {
         g_assert(is_power_of_2(alignment));
     }
+    if (size == 0) {
+        size++;
+    }
     ptr = _aligned_malloc(size, alignment);
     trace_qemu_memalign(alignment, size, ptr);
     return ptr;