Subject: Re: [BUG] Sticky-sh POSIX_TRAPS are function-local
From: Peter Stephenson <[email-masked]>
To: [email-masked]
Date: Fri, 04 Mar 2016 18:02:11 +0000
List-Id: Zsh Workers List <zsh-workers.zsh.org>

On Thu, 25 Feb 2016 14:52:24 +0100
Martijn Dekker <[email-masked]> wrote:
> But if a function defined with sticky emulation sets a POSIX trap, and
> that function is called from native zsh, then the old behaviour returns
> and a subsequent function-local trap wipes out the global POSIX trap. So
> this still kills my POSIX library functions that set a trap.

It looks like I've figured this out.

pws

diff --git a/Src/signals.c b/Src/signals.c
index 1344395..2eefc07 100644
--- a/Src/signals.c
+++ b/Src/signals.c
@@ -877,16 +877,21 @@ settrap(int sig, Eprog l, int flags)
             sig != SIGCHLD)
             install_handler(sig);
     }
+    sigtrapped[sig] |= flags;
     /*
      * Note that introducing the locallevel does not affect whether
      * sigtrapped[sig] is zero or not, i.e. a test without a mask
      * works just the same.
      */
-    sigtrapped[sig] |= (locallevel << ZSIG_SHIFT) | flags;
     if (sig == SIGEXIT) {
 	/* Make POSIX behaviour of EXIT trap sticky */
 	exit_trap_posix = isset(POSIXTRAPS);
+	/* POSIX exit traps are not local. */
+	if (!exit_trap_posix)
+	    sigtrapped[sig] |= (locallevel << ZSIG_SHIFT);
     }
+    else
+	sigtrapped[sig] |= (locallevel << ZSIG_SHIFT);
     unqueue_signals();
     return 0;
 }
--- a/Test/C03traps.ztst
+++ b/Test/C03traps.ztst
@@ -429,14 +429,32 @@
      fn
      echo exiting program
    ')
-0:POSX EXIT trap can have nested native mode EXIT trap
+0:POSIX EXIT trap can have nested native mode EXIT trap
 >entering program
 >entering native zsh function
 >native zsh function-local exit trap triggered
 >exiting program
 >POSIX exit trap triggered
 
-   (set -e
+   (cd ..; $ZTST_exe -fc '
+     echo entering program
+     emulate sh -c '\''spt() { trap "echo POSIX exit trap triggered" EXIT; }'\''
+     fn() {
+	trap "echo native zsh function-local exit trap triggered" EXIT
+	echo entering native zsh function
+     }
+     spt
+     fn
+     echo exiting program
+   ')
+0:POSIX EXIT trap not replaced if defined within function
+>entering program
+>entering native zsh function
+>native zsh function-local exit trap triggered
+>exiting program
+>POSIX exit trap triggered
+
+    (set -e
     printf "a\nb\n" | while read line
     do
        [[ $line = a* ]] || continue