diff options
author | Thomas Haller <thaller@redhat.com> | 2020-10-02 11:34:31 +0200 |
---|---|---|
committer | Thomas Haller <thaller@redhat.com> | 2020-10-02 11:51:33 +0200 |
commit | 978145f8baae59ad1e4f6231744e2a9184870e3e (patch) | |
tree | 7970d2b3cefa5f3e7a441e2285a6809ca20e5a5e | |
parent | 456d26d816ad2d506d4027138939b7612cc39390 (diff) | |
download | NetworkManager-978145f8baae59ad1e4f6231744e2a9184870e3e.tar.gz |
shared: return NULL from nm_malloc_maybe_a() when asking for zero bytes
The documentation of g_alloca()/alloca() isn't clear about what
happens when asking for zero bytes. Make it clear, by always returning
NULL.
Also, add a static assertion that @alloca_maxlen is a well-defined
positive integer.
-rw-r--r-- | shared/nm-glib-aux/nm-macros-internal.h | 47 |
1 files changed, 26 insertions, 21 deletions
diff --git a/shared/nm-glib-aux/nm-macros-internal.h b/shared/nm-glib-aux/nm-macros-internal.h index 70cbeb17ef..db1597fabe 100644 --- a/shared/nm-glib-aux/nm-macros-internal.h +++ b/shared/nm-glib-aux/nm-macros-internal.h @@ -1491,23 +1491,24 @@ nm_memdup(gconstpointer data, gsize size) return p; } -#define nm_malloc_maybe_a(alloca_maxlen, bytes, to_free) \ - ({ \ - const gsize _bytes = (bytes); \ - typeof(to_free) _to_free = (to_free); \ - typeof(*_to_free) _ptr; \ - \ - G_STATIC_ASSERT_EXPR((alloca_maxlen) <= 500); \ - nm_assert(_to_free && !*_to_free); \ - \ - if (_bytes <= (alloca_maxlen)) { \ - _ptr = g_alloca(_bytes); \ - } else { \ - _ptr = g_malloc(_bytes); \ - *_to_free = _ptr; \ - }; \ - \ - _ptr; \ +#define nm_malloc_maybe_a(alloca_maxlen, bytes, to_free) \ + ({ \ + const gsize _bytes = (bytes); \ + typeof(to_free) _to_free = (to_free); \ + typeof(*_to_free) _ptr; \ + \ + G_STATIC_ASSERT_EXPR((alloca_maxlen) <= 500u); \ + G_STATIC_ASSERT_EXPR((alloca_maxlen) > 0u); \ + nm_assert(_to_free && !*_to_free); \ + \ + if (G_LIKELY(_bytes <= (alloca_maxlen))) { \ + _ptr = _bytes > 0u ? g_alloca(_bytes) : NULL; \ + } else { \ + _ptr = g_malloc(_bytes); \ + *_to_free = _ptr; \ + }; \ + \ + _ptr; \ }) #define nm_malloc0_maybe_a(alloca_maxlen, bytes, to_free) \ @@ -1516,12 +1517,16 @@ nm_memdup(gconstpointer data, gsize size) typeof(to_free) _to_free = (to_free); \ typeof(*_to_free) _ptr; \ \ - G_STATIC_ASSERT_EXPR((alloca_maxlen) <= 500); \ + G_STATIC_ASSERT_EXPR((alloca_maxlen) <= 500u); \ + G_STATIC_ASSERT_EXPR((alloca_maxlen) > 0u); \ nm_assert(_to_free && !*_to_free); \ \ - if (_bytes <= (alloca_maxlen)) { \ - _ptr = g_alloca(_bytes); \ - memset(_ptr, 0, _bytes); \ + if (G_LIKELY(_bytes <= (alloca_maxlen))) { \ + if (_bytes > 0u) { \ + _ptr = g_alloca(_bytes); \ + memset(_ptr, 0, _bytes); \ + } else \ + _ptr = NULL; \ } else { \ _ptr = g_malloc0(_bytes); \ *_to_free = _ptr; \ |