From ed292a08dd8c3b11630d3699488fe9f53426aeb7 Mon Sep 17 00:00:00 2001 From: Sami Kerola Date: Sun, 12 Apr 2020 08:53:32 +0100 Subject: [PATCH] include: add remove_entry() to env.h A function to remove an command-line option argument, or environment variable. Requested-by: Karel Zak Reference: https://github.com/karelzak/util-linux/pull/1003#discussion_r403988092 Signed-off-by: Sami Kerola --- include/env.h | 6 ++++++ lib/env.c | 11 ++++++----- text-utils/more.c | 4 ++-- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/include/env.h b/include/env.h index db6f95932..6cee8e698 100644 --- a/include/env.h +++ b/include/env.h @@ -18,5 +18,11 @@ static inline void xsetenv(char const *name, char const *val, int overwrite) err(XSETENV_EXIT_CODE, _("failed to set the %s environment variable"), name); } +static inline int remote_entry(char **argv, int remove, int last) +{ + memmove(argv + remove, argv + remove + 1, sizeof(char *) * (last - remove)); + return last - 1; +} + #endif /* UTIL_LINUX_ENV_H */ diff --git a/lib/env.c b/lib/env.c index ea7d45782..009130db4 100644 --- a/lib/env.c +++ b/lib/env.c @@ -56,13 +56,15 @@ sanitize_env(void) char **envp = environ; char * const *bad; char **cur; - char **move; + int last = 0; + + for (cur = envp; *cur; cur++) + last++; for (cur = envp; *cur; cur++) { for (bad = forbid; *bad; bad++) { if (strncmp(*cur, *bad, strlen(*bad)) == 0) { - for (move = cur; *move; move++) - *move = *(move + 1); + last = remote_entry(envp, cur - envp, last); cur--; break; } @@ -75,8 +77,7 @@ sanitize_env(void) continue; if (!strchr(*cur, '/')) continue; /* OK */ - for (move = cur; *move; move++) - *move = *(move + 1); + last = remote_entry(envp, cur - envp, last); cur--; break; } diff --git a/text-utils/more.c b/text-utils/more.c index b4029444f..bbced5c38 100644 --- a/text-utils/more.c +++ b/text-utils/more.c @@ -74,6 +74,7 @@ # include #endif +#include "env.h" #include "strutils.h" #include "nls.h" #include "xalloc.h" @@ -251,8 +252,7 @@ static void argscan(struct more_control *ctl, int as_argc, char **as_argv) } } if (move) { - as_argc--; - memmove(as_argv + opt, as_argv + opt + 1, sizeof(char *) * (as_argc - opt)); + as_argc = remote_entry(as_argv, opt, as_argc); opt--; } }