From fb7551634a453d809079bb127adb360ac053711b Mon Sep 17 00:00:00 2001
From: Martijn Dekker <martijn@inlv.org>
Date: Sat, 13 Feb 2021 15:56:13 +0000
Subject: [PATCH] Fix exec/redirect (fd != 1) in shared-state comsub (re:
 db72f41f)

That OpenSUSE patch introduced a bug: file descriptors other than 1
that were globally redirected using 'exec' or 'redirect' no longer
survived a ${ shared-state; } command substitution.

Related: https://github.com/ksh93/ksh/issues/128

src/cmd/ksh93/sh/io.c:
- Add check for shp->subshare to the OpenSUSE patch.

src/cmd/ksh93/tests/io.sh:
- Add test.
---
 src/cmd/ksh93/sh/io.c     | 2 +-
 src/cmd/ksh93/tests/io.sh | 8 ++++++++
 2 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/src/cmd/ksh93/sh/io.c b/src/cmd/ksh93/sh/io.c
index 8104c9614f43..8cbc987cab69 100644
--- a/src/cmd/ksh93/sh/io.c
+++ b/src/cmd/ksh93/sh/io.c
@@ -1448,7 +1448,7 @@ int	sh_redirect(Shell_t *shp,struct ionod *iop, int flag)
 				}
 				else if(sh_subsavefd(fn))
 				{
-					if(fd==fn)
+					if(fd==fn && !shp->subshare)
 					{
 						if((r=sh_fcntl(fd,F_DUPFD,10)) > 0)
 						{
diff --git a/src/cmd/ksh93/tests/io.sh b/src/cmd/ksh93/tests/io.sh
index d74404b8ba92..6fb5b42cfd08 100755
--- a/src/cmd/ksh93/tests/io.sh
+++ b/src/cmd/ksh93/tests/io.sh
@@ -577,6 +577,14 @@ if	[[ -s "$tmp/fdleak.txt" ]]
 then	exec 3>&-
 	err_exit "Open file descriptor leaks out of subshell"
 fi
+# However, it should still survive a shared-state command sustitution if it's not 1 (stdout).
+redirect 3>&-  # close FD 3 just in case
+: ${ redirect 3>"$tmp/fdshared.txt"; }
+{ echo good >&3; } 2>/dev/null
+if	[[ ! -s "$tmp/fdshared.txt" ]]
+then	err_exit "Open file descriptor does not survive shared-state command substitution"
+fi
+redirect 3>&-
 
 # ======
 # On unpatched ksh on macOS, 'read' used to block when reading from a FIFO and there was no final newline.