From 5a09292f1fa8c984e29a4a418acb6052589bd5dd Mon Sep 17 00:00:00 2001 From: Thomas Haller Date: Tue, 5 May 2020 09:12:01 +0200 Subject: [PATCH] shared: fix accessing "str" argument to NM_STR_HAS_PREFIX() macro twice Macros preferably behave function-like, for example in that they evaluate arguments exactly ones. Sometimes, we want to evaluate arguments lazily, like in NM_IN_SET() or nm_g_set_error_take_lazy(). But it is almost always undesirable to evaluate an argument more than once. Fix NM_STR_HAS_PREFIX() for that. Also, rename the local variable to not use the name "_str", which may be a common name that the caller would like to use. --- shared/nm-glib-aux/nm-macros-internal.h | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/shared/nm-glib-aux/nm-macros-internal.h b/shared/nm-glib-aux/nm-macros-internal.h index d5a8513e54..6b7285e470 100644 --- a/shared/nm-glib-aux/nm-macros-internal.h +++ b/shared/nm-glib-aux/nm-macros-internal.h @@ -929,19 +929,24 @@ nm_streq0 (const char *s1, const char *s2) #define NM_STR_HAS_PREFIX(str, prefix) \ ({ \ - const char *const _str = (str); \ + const char *const _str_has_prefix = (str); \ \ - _str && (strncmp ((str), ""prefix"", NM_STRLEN (prefix)) == 0); \ + nm_assert (strlen (prefix) == NM_STRLEN (prefix)); \ + \ + _str_has_prefix \ + && (strncmp (_str_has_prefix, ""prefix"", NM_STRLEN (prefix)) == 0); \ }) #define NM_STR_HAS_SUFFIX(str, suffix) \ ({ \ - const char *_str; \ + const char *const _str_has_suffix = (str); \ gsize _l; \ \ - ( (_str = (str)) \ - && ((_l = strlen (_str)) >= NM_STRLEN (suffix)) \ - && (memcmp (&_str[_l - NM_STRLEN (suffix)], \ + nm_assert (strlen (suffix) == NM_STRLEN (suffix)); \ + \ + ( _str_has_suffix \ + && ((_l = strlen (_str_has_suffix)) >= NM_STRLEN (suffix)) \ + && (memcmp (&_str_has_suffix[_l - NM_STRLEN (suffix)], \ ""suffix"", \ NM_STRLEN (suffix)) == 0)); \ })