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

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

commit 9a360d364bb8f20cc7ec7567d2d136ca5d8e2454
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]>

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 c76347f6f..6fd4cd965 100644
--- a/winsup/cygwin/fhandler/console.cc
+++ b/winsup/cygwin/fhandler/console.cc
@@ -2018,7 +2018,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);
@@ -2157,6 +2156,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])
     {