From 434a5633a563066357bbc3f331838ed41041ec1a Mon Sep 17 00:00:00 2001 From: Karel Zak Date: Mon, 21 Jul 2025 08:16:25 +0200 Subject: [PATCH] setpriv: Improve getgroups() Portability setpriv(1) is Linux-only, and on Linux, getgroups() returns at least one group. However, it's better to use more portable and generic code patterns and assume that getgroups() can return zero. Fixes: https://github.com/util-linux/util-linux/issues/3654 Reported-by: Alejandro Colomar Signed-off-by: Karel Zak --- sys-utils/setpriv.c | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/sys-utils/setpriv.c b/sys-utils/setpriv.c index c6ff7718e..a5c832f38 100644 --- a/sys-utils/setpriv.c +++ b/sys-utils/setpriv.c @@ -295,19 +295,15 @@ static void dump_label(const char *name) static void dump_groups(void) { int n = getgroups(0, NULL); - gid_t *groups; - - if (n < 0) { - warn("getgroups failed"); - return; - } - - groups = xmalloc(n * sizeof(gid_t)); - n = getgroups(n, groups); - if (n < 0) { - free(groups); - warn("getgroups failed"); - return; + gid_t *groups = NULL; + + if (n < 0) + goto failed; + if (n) { + groups = xmalloc(n * sizeof(gid_t)); + n = getgroups(n, groups); + if (n < 0) + goto failed; } printf(_("Supplementary groups: ")); @@ -323,6 +319,10 @@ static void dump_groups(void) } printf("\n"); free(groups); + return; +failed: + free(groups); + warn("getgroups failed"); } static void dump_pdeathsig(void) -- 2.47.2