[newlib-cygwin/cygwin-3_6-branch] Cygwin: console: Fix deadlock in console teardown that arises from pcon

Takashi Yano via Cygwin-cvs <[email protected]> Fri, 29 May 2026 02:33:56 +0000 (GMT)
Newsgroups gmane.os.cygwin.cvs
Message-ID <[email protected]>
https://sourceware.org/git/gitweb.cgi?p=3Dnewlib-cygwin.git;h=3Dd541ca756ac=
14f874ed12a1c416d13dc9f7e4c87

commit d541ca756ac14f874ed12a1c416d13dc9f7e4c87
Author: Takashi Yano <[email protected]>
Date:   Thu May 21 16:36:20 2026 +0900

    Cygwin: console: Fix deadlock in console teardown that arises from pcon
   =20
    When a console process originating from a pseudo console exits, the
    current sequence is as follows:
   =20
      1) atexit handlers (pcon_handover_proc) called. This also closes
         parent_pty_input_mutex which is introduced by the commit
         c4fb720afcf1.
      2) close_all_files() is called via _exit(). This terminates
         cons_master_thread.
   =20
    parent_pty_input_mutex is referenced in cons_master_thread, so
    cons_master_thread may still use the mutex after it has been closed.
    This can lead to undesired behaviour, including a deadlock. Instead
    of registering pcon_hand_over_proc() as an atexit handler, this
    patch calls pcon_handover_proc() at a point in fhandler_console::close
    where cons_master_thread has already terminated, ensuring that no
    other thread accesses the mutex.
   =20
    Addresses: https://github.com/msys2/msys2-runtime/issues/338
    Fixes: c4fb720afcf1 ("Cygwin: console: Use input_mutex in the parent PT=
Y in master thread")
    Signed-off-by: Takashi Yano <[email protected]>
    Reviewed-by: Johannes Schindelin <[email protected]>
    (cherry picked from commit 9a360d364bb8f20cc7ec7567d2d136ca5d8e2454)

Diff:
---
 winsup/cygwin/fhandler/console.cc | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/winsup/cygwin/fhandler/console.cc b/winsup/cygwin/fhandler/con=
sole.cc
index 6220a9142..224177bd5 100644
--- a/winsup/cygwin/fhandler/console.cc
+++ b/winsup/cygwin/fhandler/console.cc
@@ -1954,7 +1954,6 @@ fhandler_console::setup_pcon_hand_over ()
 	if (get_console_process_id (owner, true, false, false, false))
 	  {
 	    inside_pcon =3D true;
-	    atexit (fhandler_console::pcon_hand_over_proc);
 	    parent_pty =3D i;
 	    parent_pty_input_mutex =3D
 	      cygwin_shared->tty[i]->open_input_mutex (MAXIMUM_ALLOWED);
@@ -2092,6 +2091,8 @@ fhandler_console::close (int flag)
   CloseHandle (output_mutex);
   output_mutex =3D NULL;
=20
+  pcon_hand_over_proc ();
+
   WaitForSingleObject (shared_info_mutex, INFINITE);
   if (--shared_info_state[unit] =3D=3D 0 && shared_console_info[unit])
     {