From e627ac95bef4d61c2d264fc87d767cb7a948c38f Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Fri, 30 Sep 2016 14:36:59 +0200 Subject: [PATCH] ash: [VAR] Initialise OPTIND after importing environment Upstream commit 1: Date: Fri, 23 Aug 2013 21:27:42 +1000 [VAR] Initialise OPTIND after importing environment On Sat, Mar 23, 2013 at 01:46:20AM +0000, Chris F.A. Johnson wrote: > According to both the dash man page and the POSIX spec, "When the > shell is invoked, OPTIND is initialized to 1." > > However, it actually takes the value of the environment variable > if it exists: > > $ OPTIND=4 dash -c 'echo "$OPTIND"' > 4 > $ OPTIND=4 bash -c 'echo "$OPTIND"' > 1 > $ OPTIND=4 ksh -c 'echo "$OPTIND"' > 1 > $ OPTIND=4 ksh93 -c 'echo "$OPTIND"' > 1 This patch fixes this by initialising OPTIND after importing the environment. Signed-off-by: Herbert Xu Upstream commit 2: Date: Tue, 7 Oct 2014 22:24:42 +0800 [VAR] Use setvareq to set OPTIND initially There is no need to setvarint to set the initial value of OPTIND of one. This patch switchs to setvareq which also lets us avoid an unnecessary memory allocation. Signed-off-by: Herbert Xu Signed-off-by: Denys Vlasenko --- shell/ash.c | 4 +++- shell/shell_common.c | 1 + shell/shell_common.h | 2 ++ 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/shell/ash.c b/shell/ash.c index 9fd1b55e2..a7c03bbc2 100644 --- a/shell/ash.c +++ b/shell/ash.c @@ -1919,7 +1919,7 @@ static const struct { { VSTRFIXED|VTEXTFIXED , "PS2=> " , NULL }, { VSTRFIXED|VTEXTFIXED , "PS4=+ " , NULL }, #if ENABLE_ASH_GETOPTS - { VSTRFIXED|VTEXTFIXED , "OPTIND=1" , getoptsreset }, + { VSTRFIXED|VTEXTFIXED , defoptindvar, getoptsreset }, #endif #if ENABLE_ASH_RANDOM_SUPPORT { VSTRFIXED|VTEXTFIXED|VUNSET|VDYNAMIC, "RANDOM", change_random }, @@ -13124,6 +13124,8 @@ init(void) } } + setvareq((char*)defoptindvar, VTEXTFIXED); + setvar0("PPID", utoa(getppid())); #if ENABLE_ASH_BASH_COMPAT p = lookupvar("SHLVL"); diff --git a/shell/shell_common.c b/shell/shell_common.c index 14eeaafcc..98d862744 100644 --- a/shell/shell_common.c +++ b/shell/shell_common.c @@ -21,6 +21,7 @@ #include /* getrlimit */ const char defifsvar[] ALIGN1 = "IFS= \t\n"; +const char defoptindvar[] ALIGN1 = "OPTIND=1"; int FAST_FUNC is_well_formed_var_name(const char *s, char terminator) diff --git a/shell/shell_common.h b/shell/shell_common.h index 993ed5951..a82535c86 100644 --- a/shell/shell_common.h +++ b/shell/shell_common.h @@ -24,6 +24,8 @@ PUSH_AND_SET_FUNCTION_VISIBILITY_TO_HIDDEN extern const char defifsvar[] ALIGN1; /* "IFS= \t\n" */ #define defifs (defifsvar + 4) +extern const char defoptindvar[] ALIGN1; /* "OPTIND=1" */ + int FAST_FUNC is_well_formed_var_name(const char *s, char terminator); /* Builtins */ -- 2.25.1