From 5bc511203e02dda24a7f45a373e44d5861b5f088 Mon Sep 17 00:00:00 2001 From: Thomas Haller Date: Tue, 13 Apr 2021 14:54:25 +0200 Subject: [PATCH] all: make nm_steal_pointer() and g_steal_pointer() more typesafe using typeof() The previous code would always cast the argument to "void *", and thus loose some type information. For example, gulong variable = 0; g_steal_pointer(&variable); would compile, when it shouldn't. In general, we try to avoid redefining glib macros and headers. But we really want those extra compile time checks that we can get, so let's do it. --- src/libnm-glib-aux/nm-glib.h | 31 ++++++++++--------------------- src/libnm-std-aux/nm-std-aux.h | 21 +++++++++------------ 2 files changed, 19 insertions(+), 33 deletions(-) diff --git a/src/libnm-glib-aux/nm-glib.h b/src/libnm-glib-aux/nm-glib.h index befb8d9013..df957f0d58 100644 --- a/src/libnm-glib-aux/nm-glib.h +++ b/src/libnm-glib-aux/nm-glib.h @@ -407,30 +407,19 @@ _nm_g_hash_table_get_keys_as_array(GHashTable *hash_table, guint *length) /*****************************************************************************/ -static inline gpointer -_nm_g_steal_pointer(gpointer pp) -{ - gpointer *ptr = (gpointer *) pp; - gpointer ref; - - ref = *ptr; - *ptr = NULL; - - return ref; -} - -#if !GLIB_CHECK_VERSION(2, 44, 0) -static inline gpointer -g_steal_pointer(gpointer pp) -{ - return _nm_g_steal_pointer(pp); -} -#endif - #ifdef g_steal_pointer #undef g_steal_pointer #endif -#define g_steal_pointer(pp) ((typeof(*(pp))) _nm_g_steal_pointer(pp)) + +#define g_steal_pointer(pp) \ + ({ \ + typeof(*(pp)) *const _pp = (pp); \ + typeof(**_pp) *const _p = *_pp; \ + _nm_unused const void *const _p_type_check = _p; \ + \ + *_pp = NULL; \ + _p; \ + }) /*****************************************************************************/ diff --git a/src/libnm-std-aux/nm-std-aux.h b/src/libnm-std-aux/nm-std-aux.h index 30adeb5893..7c38f11ace 100644 --- a/src/libnm-std-aux/nm-std-aux.h +++ b/src/libnm-std-aux/nm-std-aux.h @@ -753,18 +753,15 @@ _nm_auto_fclose(FILE **pfd) /*****************************************************************************/ -static inline void * -_nm_steal_pointer(void *pp) -{ - void **ptr = (void **) pp; - void * ref; - - ref = *ptr; - *ptr = NULL; - return ref; -} - -#define nm_steal_pointer(pp) ((typeof(*(pp))) _nm_steal_pointer(pp)) +#define nm_steal_pointer(pp) \ + ({ \ + typeof(*(pp)) *const _pp = (pp); \ + typeof(**_pp) *const _p = *_pp; \ + _nm_unused const void *const _p_type_check = _p; \ + \ + *_pp = NULL; \ + _p; \ + }) /** * nm_steal_int: