1 /* sigproc.cc: inter/intra signal and sub process handler
3 Copyright 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
4 2006, 2007, 2008, 2009, 2010, 2011, 2012 Red Hat, Inc.
6 This file is part of Cygwin.
8 This software is a copyrighted work licensed under the terms of the
9 Cygwin license. Please consult the file "CYGWIN_LICENSE" for
13 #include "miscfuncs.h"
15 #include <sys/cygwin.h>
22 #include "child_info_magic.h"
23 #include "shared_info.h"
26 #include "exception.h"
31 #define WSSC 60000 // Wait for signal completion
32 #define WPSP 40000 // Wait for proc_subproc mutex
34 #define no_signals_available(x) (!my_sendsig || ((x) && myself->exitcode & EXITCODE_SET) || (&_my_tls == _sig_tls))
39 struct sigaction
*global_sigs
;
44 char NO_COPY myself_nowait_dummy
[1] = {'0'};// Flag to sig_send that signal goes to
45 // current process but no wait is required
47 #define Static static NO_COPY
49 HANDLE NO_COPY sigCONT
; // Used to "STOP" a process
51 Static
bool sigheld
; // True if holding signals
53 Static
int nprocs
; // Number of deceased children
54 Static
char cprocs
[(NPROCS
+ 1) * sizeof (pinfo
)];// All my children info
55 #define procs ((pinfo *) cprocs) // All this just to avoid expensive
56 // constructor operation at DLL startup
57 Static waitq waitq_head
; // Start of queue for wait'ing threads
59 Static muto sync_proc_subproc
; // Control access to subproc stuff
61 _cygtls NO_COPY
*_sig_tls
;
63 Static HANDLE my_sendsig
;
64 Static HANDLE my_readsig
;
66 /* Function declarations */
67 static int __stdcall
checkstate (waitq
*) __attribute__ ((regparm (1)));
68 static __inline__
bool get_proc_lock (DWORD
, DWORD
);
69 static bool __stdcall
remove_proc (int);
70 static bool __stdcall
stopped_or_terminated (waitq
*, _pinfo
*);
71 static void WINAPI
wait_sig (VOID
*arg
);
73 /* wait_sig bookkeeping */
77 sigpacket sigs
[NSIG
+ 1];
83 void reset () {curr
= &start
; prev
= &start
;}
84 void add (sigpacket
&);
86 bool pending () const {return !!start
.next
;}
88 sigpacket
*save () const {return curr
;}
89 void restore (sigpacket
*saved
) {curr
= saved
;}
90 friend void __stdcall
sig_dispatch_pending (bool);
91 friend void WINAPI
wait_sig (VOID
*arg
);
94 Static pending_signals sigq
;
100 cygheap
->sigs
= global_sigs
=
101 (struct sigaction
*) ccalloc_abort (HEAP_SIGS
, NSIG
, sizeof (struct sigaction
));
102 global_sigs
[SIGSTOP
].sa_flags
= SA_RESTART
| SA_NODEFER
;
106 signal_fixup_after_exec ()
108 global_sigs
= cygheap
->sigs
;
109 /* Set up child's signal handlers */
110 for (int i
= 0; i
< NSIG
; i
++)
112 global_sigs
[i
].sa_mask
= 0;
113 if (global_sigs
[i
].sa_handler
!= SIG_IGN
)
115 global_sigs
[i
].sa_handler
= SIG_DFL
;
116 global_sigs
[i
].sa_flags
&= ~ SA_SIGINFO
;
121 /* Get the sync_proc_subproc muto to control access to
122 * children, proc arrays.
123 * Attempt to handle case where process is exiting as we try to grab
127 get_proc_lock (DWORD what
, DWORD val
)
129 if (!cygwin_finished_initializing
)
131 Static
int lastwhat
= -1;
132 if (!sync_proc_subproc
)
134 sigproc_printf ("sync_proc_subproc is NULL");
137 if (sync_proc_subproc
.acquire (WPSP
))
142 system_printf ("Couldn't acquire %s for(%d,%d), last %d, %E",
143 sync_proc_subproc
.name
, what
, val
, lastwhat
);
147 static bool __stdcall
148 proc_can_be_signalled (_pinfo
*p
)
150 if (!(p
->exitcode
& EXITCODE_SET
))
152 if (ISSTATE (p
, PID_INITIALIZING
) ||
153 (((p
)->process_state
& (PID_ACTIVE
| PID_IN_USE
)) ==
154 (PID_ACTIVE
| PID_IN_USE
)))
163 pid_exists (pid_t pid
)
165 return pinfo (pid
)->exists ();
168 /* Return true if this is one of our children, false otherwise. */
169 static inline bool __stdcall
172 for (int i
= 0; i
< nprocs
; i
++)
173 if (procs
[i
]->pid
== pid
)
178 /* Handle all subprocess requests
181 proc_subproc (DWORD what
, DWORD val
)
189 #define wval ((waitq *) val)
190 #define vchild (*((pinfo *) val))
192 sigproc_printf ("args: %x, %d", what
, val
);
194 if (!get_proc_lock (what
, val
)) // Serialize access to this function
196 system_printf ("couldn't get proc lock. what %d, val %d", what
, val
);
202 /* Add a new subprocess to the children arrays.
203 * (usually called from the main thread)
206 /* Filled up process table? */
207 if (nprocs
>= NPROCS
)
209 sigproc_printf ("proc table overflow: hit %d processes, pid %d\n",
210 nprocs
, vchild
->pid
);
215 /* fall through intentionally */
217 case PROC_DETACHED_CHILD
:
218 if (vchild
!= myself
)
220 vchild
->ppid
= what
== PROC_DETACHED_CHILD
? 1 : myself
->pid
;
221 vchild
->uid
= myself
->uid
;
222 vchild
->gid
= myself
->gid
;
223 vchild
->pgid
= myself
->pgid
;
224 vchild
->sid
= myself
->sid
;
225 vchild
->ctty
= myself
->ctty
;
226 vchild
->cygstarted
= true;
227 vchild
->process_state
|= PID_INITIALIZING
;
229 if (what
== PROC_DETACHED_CHILD
)
231 /* fall through intentionally */
233 case PROC_REATTACH_CHILD
:
234 procs
[nprocs
] = vchild
;
235 rc
= procs
[nprocs
].wait ();
238 sigproc_printf ("added pid %d to proc table, slot %d", vchild
->pid
,
244 /* Handle a wait4() operation. Allocates an event for the calling
245 * thread which is signaled when the appropriate pid exits or stops.
246 * (usually called from the main thread)
249 wval
->ev
= NULL
; // Don't know event flag yet
251 if (wval
->pid
== -1 || !wval
->pid
)
252 child
= NULL
; // Not looking for a specific pid
253 else if (!mychild (wval
->pid
))
254 goto out
; // invalid pid. flag no such child
256 wval
->status
= 0; // Don't know status yet
257 sigproc_printf ("wval->pid %d, wval->options %d", wval
->pid
, wval
->options
);
259 /* If the first time for this thread, create a new event, otherwise
262 if ((wval
->ev
= wval
->thread_ev
) == NULL
)
264 wval
->ev
= wval
->thread_ev
= CreateEvent (&sec_none_nih
, TRUE
, FALSE
,
266 ProtectHandle1 (wval
->ev
, wq_ev
);
269 ResetEvent (wval
->ev
);
271 waitq_head
.next
= wval
; /* Add at the beginning. */
272 wval
->next
= w
; /* Link in rest of the list. */
276 case PROC_EXEC_CLEANUP
:
279 for (w
= &waitq_head
; w
->next
!= NULL
; w
= w
->next
)
280 CloseHandle (w
->next
->ev
);
283 /* Clear all waiting threads. Called from exceptions.cc prior to
284 the main thread's dispatch to a signal handler function.
285 (called from wait_sig thread) */
287 /* Clear all "wait"ing threads. */
289 sigproc_printf ("clear waiting threads");
291 sigproc_printf ("looking for processes to reap, nprocs %d", nprocs
);
295 /* Scan the linked list of wait()ing threads. If a wait's parameters
296 match this pid, then activate it. */
297 for (w
= &waitq_head
; w
->next
!= NULL
; w
= w
->next
)
299 if ((potential_match
= checkstate (w
)) > 0)
300 sigproc_printf ("released waiting thread");
301 else if (!clearing
&& !(w
->next
->options
& WNOHANG
) && potential_match
< 0)
302 sigproc_printf ("only found non-terminated children");
303 else if (potential_match
<= 0) // nothing matched
305 sigproc_printf ("waiting thread found no children");
306 HANDLE oldw
= w
->next
->ev
;
309 w
->next
->status
= -1; /* flag that a signal was received */
310 else if (!potential_match
|| !(w
->next
->options
& WNOHANG
))
312 if (!SetEvent (oldw
))
313 system_printf ("couldn't wake up wait event %p, %E", oldw
);
314 w
->next
= w
->next
->next
;
321 sigproc_printf ("finished processing terminated/stopped child");
324 waitq_head
.next
= NULL
;
325 sigproc_printf ("finished clearing");
328 if (global_sigs
[SIGCHLD
].sa_handler
== (void *) SIG_IGN
)
329 for (int i
= 0; i
< nprocs
; i
+= remove_proc (i
))
334 sync_proc_subproc
.release (); // Release the lock
336 sigproc_printf ("returning %d", rc
);
342 // FIXME: This is inelegant
344 _cygtls::remove_wq (DWORD wait
)
346 if (exit_state
< ES_FINAL
&& waitq_head
.next
&& sync_proc_subproc
347 && sync_proc_subproc
.acquire (wait
))
349 for (waitq
*w
= &waitq_head
; w
->next
!= NULL
; w
= w
->next
)
352 ForceCloseHandle1 (wq
.thread_ev
, wq_ev
);
356 sync_proc_subproc
.release ();
364 if ((h
= InterlockedExchangePointer (&my_readsig
, NULL
)))
365 ForceCloseHandle1 (h
, my_readsig
);
368 /* Cover function to `do_exit' to handle exiting even in presence of more
369 exceptions. We used to call exit, but a SIGSEGV shouldn't cause atexit
372 _cygtls::signal_exit (int rc
)
374 HANDLE myss
= my_sendsig
;
375 my_sendsig
= NULL
; /* Make no_signals_allowed return true */
377 /* This code used to try to always close my_readsig but it ended up
378 blocking for reasons that people in google think make sense.
379 It's possible that it was blocking because ReadFile was still active
380 but it isn't clear why this only caused random hangs rather than
381 consistent hangs. So, for now at least, avoid closing my_readsig
382 unless this is the signal thread. */
383 if (&_my_tls
== _sig_tls
)
384 close_my_readsig (); /* Stop any currently executing sig_sends */
388 sp
.si
.si_signo
= __SIGEXIT
;
390 /* Write a packet to the wait_sig thread which tells it to exit and
392 WriteFile (myss
, &sp
, sizeof (sp
), &len
, NULL
);
394 signal_debugger (rc
& 0x7f);
396 if (rc
== SIGQUIT
|| rc
== SIGABRT
)
399 c
.ContextFlags
= CONTEXT_FULL
;
400 GetThreadContext (hMainThread
, &c
);
402 if (cygheap
->rlim_core
> 0UL)
408 sigproc_printf ("terminating captive process");
409 TerminateProcess (ch_spawn
, sigExeced
= rc
);
412 if ((rc
& 0x80) && !try_to_debug ())
413 stackdump (thread_context
.ebp
, true);
415 lock_process
until_exit (true);
416 if (have_execed
|| exit_state
> ES_PROCESS_LOCKED
)
419 /* Starve other threads in a vain attempt to stop them from doing something
421 SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_TIME_CRITICAL
);
423 sigproc_printf ("about to call do_exit (%x)", rc
);
427 /* Terminate the wait_subproc thread.
428 Called on process exit.
429 Also called by spawn_guts to disassociate any subprocesses from this
430 process. Subprocesses will then know to clean up after themselves and
431 will not become procs. */
435 sigproc_printf ("nprocs %d", nprocs
);
438 sync_proc_subproc
.acquire (WPSP
);
440 proc_subproc (PROC_CLEARWAIT
, 1);
442 /* Clean out proc processes from the pid list. */
443 for (int i
= 0; i
< nprocs
; i
++)
445 /* If we've execed then the execed process will handle setting ppid
446 to 1 iff it is a Cygwin process. */
447 if (!have_execed
|| !have_execed_cygwin
)
449 if (procs
[i
].wait_thread
)
450 procs
[i
].wait_thread
->terminate_thread ();
451 /* Release memory associated with this process unless it is 'myself'.
452 'myself' is only in the procs table when we've execed. We reach
453 here when the next process has finished initializing but we still
454 can't free the memory used by 'myself' since it is used later on
455 during cygwin tear down. */
456 if (procs
[i
] != myself
)
460 sync_proc_subproc
.release ();
462 sigproc_printf ("leaving");
465 /* Clear pending signal */
467 sig_clear (int target_sig
)
469 if (&_my_tls
!= _sig_tls
)
470 sig_send (myself
, -target_sig
);
474 sigpacket
*save
= sigq
.save ();
476 while ((q
= sigq
.next ()))
477 if (q
->si
.si_signo
== target_sig
)
479 q
->si
.si_signo
= __SIGDELETE
;
487 sigpending (sigset_t
*mask
)
489 sigset_t outset
= (sigset_t
) sig_send (myself
, __SIGPENDING
);
490 if (outset
== SIG_BAD_MASK
)
496 /* Force the wait_sig thread to wake up and scan for pending signals */
498 sig_dispatch_pending (bool fast
)
500 if (exit_state
|| &_my_tls
== _sig_tls
)
503 sigproc_printf ("exit_state %d, cur thread id %p, _sig_tls %p, sigq.start.next %p",
504 exit_state
, GetCurrentThreadId (), _sig_tls
, sigq
.start
.next
);
509 /* Non-atomically test for any signals pending and wake up wait_sig if any are
510 found. It's ok if there's a race here since the next call to this function
512 FIXME: Eventually, wait_sig should wake up on its own to deal with pending
515 sig_send (myself
, fast
? __SIGFLUSHFAST
: __SIGFLUSH
);
518 /* Signal thread initialization. Called from dll_crt0_1.
519 This routine starts the signal handling thread. */
523 char char_sa_buf
[1024];
524 PSECURITY_ATTRIBUTES sa
= sec_user_nih ((PSECURITY_ATTRIBUTES
) char_sa_buf
, cygheap
->user
.sid());
525 DWORD err
= fhandler_pipe::create (sa
, &my_readsig
, &my_sendsig
,
526 sizeof (sigpacket
), "sigwait",
531 api_fatal ("couldn't create signal pipe, %E");
533 ProtectHandle (my_readsig
);
534 myself
->sendsig
= my_sendsig
;
535 /* sync_proc_subproc is used by proc_subproc. It serializes
536 access to the children and proc arrays. */
537 sync_proc_subproc
.init ("sync_proc_subproc");
538 new cygthread (wait_sig
, cygself
, "sig");
541 /* Called on process termination to terminate signal and process threads.
544 sigproc_terminate (exit_states es
)
546 exit_states prior_exit_state
= exit_state
;
548 if (!cygwin_finished_initializing
)
549 sigproc_printf ("don't worry about signal thread");
550 else if (prior_exit_state
>= ES_FINAL
)
551 sigproc_printf ("already performed");
554 sigproc_printf ("entering");
555 sig_send (myself_nowait
, __SIGEXIT
);
556 proc_terminate (); // clean up process stuff
561 sig_send (_pinfo
*p
, int sig
)
563 if (sig
== __SIGHOLD
)
567 else if (sig
== __SIGFLUSH
|| sig
== __SIGFLUSHFAST
)
569 else if (sig
== __SIGNOHOLD
|| sig
== __SIGEXIT
)
574 else if (&_my_tls
== _main_tls
)
577 system_printf ("signal %d sent to %p while signals are on hold", sig
, p
);
583 si
.si_code
= SI_KERNEL
;
584 si
.si_pid
= si
.si_uid
= si
.si_errno
= 0;
585 return sig_send (p
, si
);
588 /* Send a signal to another process by raising its signal semaphore.
589 If pinfo *p == NULL, send to the current process.
590 If sending to this process, wait for notification that a signal has
591 completed before returning. */
593 sig_send (_pinfo
*p
, siginfo_t
& si
, _cygtls
*tls
)
599 bool communing
= si
.si_signo
== __SIGCOMMUNE
;
602 bool wait_for_completion
;
603 if (!(its_me
= (!have_execed
&& (p
== NULL
|| p
== myself
|| p
== myself_nowait
))))
605 /* It is possible that the process is not yet ready to receive messages
606 * or that it has exited. Detect this.
608 if (!proc_can_be_signalled (p
)) /* Is the process accepting messages? */
610 sigproc_printf ("invalid pid %d(%x), signal %d",
611 p
->pid
, p
->process_state
, si
.si_signo
);
614 wait_for_completion
= false;
618 if (no_signals_available (si
.si_signo
!= __SIGEXIT
))
621 goto out
; // Either exiting or not yet initializing
623 wait_for_completion
= p
!= myself_nowait
&& _my_tls
.isinitialized () && !exit_state
;
629 sendsig
= my_sendsig
;
634 for (int i
= 0; !p
->sendsig
&& i
< 10000; i
++)
639 dwProcessId
= p
->dwProcessId
;
643 dupsig
= p
->exec_sendsig
;
644 dwProcessId
= p
->exec_dwProcessId
;
649 sigproc_printf ("sendsig handle never materialized");
652 HANDLE hp
= OpenProcess (PROCESS_DUP_HANDLE
, false, dwProcessId
);
656 sigproc_printf ("OpenProcess failed, %E");
660 if (!DuplicateHandle (hp
, dupsig
, GetCurrentProcess (), &sendsig
, 0,
661 false, DUPLICATE_SAME_ACCESS
) || !sendsig
)
664 sigproc_printf ("DuplicateHandle failed, %E");
668 VerifyHandle (sendsig
);
673 si
._si_commune
._si_process_handle
= hp
;
675 HANDLE
& tome
= si
._si_commune
._si_write_handle
;
676 HANDLE
& fromthem
= si
._si_commune
._si_read_handle
;
677 if (!CreatePipeOverlapped (&fromthem
, &tome
, &sec_all_nih
))
679 sigproc_printf ("CreatePipe for __SIGCOMMUNE failed, %E");
683 if (!DuplicateHandle (GetCurrentProcess (), tome
, hp
, &tome
, 0, false,
684 DUPLICATE_SAME_ACCESS
| DUPLICATE_CLOSE_SOURCE
))
686 sigproc_printf ("DuplicateHandle for __SIGCOMMUNE failed, %E");
693 sigproc_printf ("sendsig %p, pid %d, signal %d, its_me %d", sendsig
, p
->pid
, si
.si_signo
, its_me
);
698 else if (si
.si_signo
== __SIGPENDING
)
699 pack
.mask
= &pending
;
700 else if (si
.si_signo
== __SIGFLUSH
|| si
.si_signo
> 0)
701 pack
.mask
= tls
? &tls
->sigmask
: &_main_tls
->sigmask
;
707 pack
.si
.si_pid
= myself
->pid
;
709 pack
.si
.si_uid
= myself
->uid
;
710 pack
.pid
= myself
->pid
;
712 if (wait_for_completion
)
714 pack
.wakeup
= CreateEvent (&sec_none_nih
, FALSE
, FALSE
, NULL
);
715 sigproc_printf ("wakeup %p", pack
.wakeup
);
716 ProtectHandle (pack
.wakeup
);
721 if (!communing
|| !(si
._si_commune
._si_code
& PICOM_EXTRASTR
))
723 leader
= (char *) &pack
;
724 packsize
= sizeof (pack
);
728 size_t n
= strlen (si
._si_commune
._si_str
);
729 char *p
= leader
= (char *) alloca (sizeof (pack
) + sizeof (n
) + n
);
730 memcpy (p
, &pack
, sizeof (pack
)); p
+= sizeof (pack
);
731 memcpy (p
, &n
, sizeof (n
)); p
+= sizeof (n
);
732 memcpy (p
, si
._si_commune
._si_str
, n
); p
+= n
;
733 packsize
= p
- leader
;
737 if (!WriteFile (sendsig
, leader
, packsize
, &nb
, NULL
) || nb
!= packsize
)
739 /* Couldn't send to the pipe. This probably means that the
740 process is exiting. */
743 sigproc_printf ("WriteFile for pipe %p failed, %E", sendsig
);
744 ForceCloseHandle (sendsig
);
748 if (no_signals_available (true))
749 sigproc_printf ("I'm going away now");
750 else if (!p
->exec_sendsig
)
751 system_printf ("error sending signal %d to pid %d, pipe handle %p, %E",
752 si
.si_signo
, p
->pid
, sendsig
);
754 if (GetLastError () == ERROR_BROKEN_PIPE
)
762 /* No need to wait for signal completion unless this was a signal to
765 If it was a signal to this process, wait for a dispatched signal.
766 Otherwise just wait for the wait_sig to signal that it has finished
767 processing the signal. */
768 if (wait_for_completion
)
770 sigproc_printf ("Waiting for pack.wakeup %p", pack
.wakeup
);
771 rc
= WaitForSingleObject (pack
.wakeup
, WSSC
);
772 ForceCloseHandle (pack
.wakeup
);
777 sigproc_printf ("Not waiting for sigcomplete. its_me %d signal %d",
778 its_me
, si
.si_signo
);
780 ForceCloseHandle (sendsig
);
784 if (rc
== WAIT_OBJECT_0
)
785 rc
= 0; // Successful exit
788 if (!no_signals_available (true))
789 system_printf ("wait for sig_complete event failed, signal %d, rc %d, %E",
795 if (wait_for_completion
&& si
.si_signo
!= __SIGFLUSHFAST
)
796 _my_tls
.call_signal_handler ();
802 if (si
._si_commune
._si_process_handle
)
803 CloseHandle (si
._si_commune
._si_process_handle
);
804 if (si
._si_commune
._si_read_handle
)
805 CloseHandle (si
._si_commune
._si_read_handle
);
808 ForceCloseHandle (pack
.wakeup
);
809 if (si
.si_signo
!= __SIGPENDING
)
815 sigproc_printf ("returning %p from sending signal %d", rc
, si
.si_signo
);
819 int child_info::retry_count
= 0;
821 /* Initialize some of the memory block passed to child processes
822 by fork/spawn/exec. */
823 child_info::child_info (unsigned in_cb
, child_info_types chtype
,
824 bool need_subproc_ready
):
825 cb (in_cb
), intro (PROC_MAGIC_GENERIC
), magic (CHILD_INFO_MAGIC
),
826 type (chtype
), cygheap (::cygheap
), cygheap_max (::cygheap_max
),
827 flag (0), retry (child_info::retry_count
), rd_proc_pipe (NULL
),
830 /* It appears that when running under WOW64 on Vista 64, the first DWORD
831 value in the datastructure lpReserved2 is pointing to (msv_count in
832 Cygwin), has to reflect the size of that datastructure as used in the
833 Microsoft C runtime (a count value, counting the number of elements in
834 two subsequent arrays, BYTE[count and HANDLE[count]), even though the C
835 runtime isn't used. Otherwise, if msv_count is 0 or too small, the
836 datastructure gets overwritten.
838 This seems to be a bug in Vista's WOW64, which apparently copies the
839 lpReserved2 datastructure not using the cbReserved2 size information,
840 but using the information given in the first DWORD within lpReserved2
841 instead. 32 bit Windows and former WOW64 don't care if msv_count is 0
842 or a sensible non-0 count value. However, it's not clear if a non-0
843 count doesn't result in trying to evaluate the content, so we do this
844 really only for Vista 64 for now.
846 Note: It turns out that a non-zero value *does* harm operation on
847 XP 64 and 2K3 64 (Crash in CreateProcess call).
849 The value is sizeof (child_info_*) / 5 which results in a count which
850 covers the full datastructure, plus not more than 4 extra bytes. This
851 is ok as long as the child_info structure is cosily stored within a bigger
853 msv_count
= wincap
.needs_count_in_si_lpres2 () ? in_cb
/ 5 : 0;
855 fhandler_union_cb
= sizeof (fhandler_union
);
856 user_h
= cygwin_user_h
;
857 if (strace
.active ())
859 if (need_subproc_ready
)
861 subproc_ready
= CreateEvent (&sec_all
, FALSE
, FALSE
, NULL
);
862 flag
|= _CI_ISCYGWIN
;
864 sigproc_printf ("subproc_ready %p", subproc_ready
);
865 /* Create an inheritable handle to pass to the child process. This will
866 allow the child to duplicate handles from the parent to itself. */
868 if (!DuplicateHandle (GetCurrentProcess (), GetCurrentProcess (),
869 GetCurrentProcess (), &parent
, 0, true,
870 DUPLICATE_SAME_ACCESS
))
871 system_printf ("couldn't create handle to myself for child, %E");
874 child_info::~child_info ()
879 child_info_fork::child_info_fork () :
880 child_info (sizeof *this, _CH_FORK
, true),
881 forker_finished (NULL
)
885 child_info_spawn::child_info_spawn (child_info_types chtype
, bool need_subproc_ready
) :
886 child_info (sizeof *this, chtype
, need_subproc_ready
)
888 if (type
== _CH_EXEC
)
893 else if (!(ev
= CreateEvent (&sec_none_nih
, false, false, NULL
)))
894 api_fatal ("couldn't create signalling event for exec, %E");
896 get_proc_lock (PROC_EXECING
, 0);
897 lock
= &sync_proc_subproc
;
898 /* exit with lock held */
903 cygheap_exec_info::alloc ()
905 return (cygheap_exec_info
*) ccalloc_abort (HEAP_1_EXEC
, 1,
906 sizeof (cygheap_exec_info
)
907 + (nprocs
* sizeof (children
[0])));
911 child_info_spawn::wait_for_myself ()
914 myself
.remember (false);
915 WaitForSingleObject (ev
, INFINITE
);
919 child_info::cleanup ()
923 CloseHandle (subproc_ready
);
924 subproc_ready
= NULL
;
928 CloseHandle (parent
);
933 ForceCloseHandle (rd_proc_pipe
);
938 ForceCloseHandle (wr_proc_pipe
);
944 child_info_spawn::cleanup ()
950 for (char **e
= moreinfo
->envp
; *e
; e
++)
952 cfree (moreinfo
->envp
);
954 if (type
!= _CH_SPAWN
&& moreinfo
->myself_pinfo
)
955 CloseHandle (moreinfo
->myself_pinfo
);
964 if (type
== _CH_EXEC
)
966 if (iscygwin () && hExeced
)
967 proc_subproc (PROC_EXEC_CLEANUP
, 0);
968 sync_proc_subproc
.release ();
971 child_info::cleanup ();
974 /* Record any non-reaped subprocesses to be passed to about-to-be-execed
975 process. FIXME: There is a race here if the process exits while we
978 cygheap_exec_info::record_children ()
980 for (nchildren
= 0; nchildren
< nprocs
; nchildren
++)
982 children
[nchildren
].pid
= procs
[nchildren
]->pid
;
983 children
[nchildren
].p
= procs
[nchildren
];
988 child_info_spawn::record_children ()
990 if (type
== _CH_EXEC
&& iscygwin ())
991 moreinfo
->record_children ();
994 /* Reattach non-reaped subprocesses passed in from the cygwin process
995 which previously operated under this pid. FIXME: Is there a race here
996 if the process exits during cygwin's exec handoff? */
998 cygheap_exec_info::reattach_children (HANDLE parent
)
1000 for (int i
= 0; i
< nchildren
; i
++)
1002 pinfo
p (parent
, children
[i
].p
, children
[i
].pid
);
1004 debug_only_printf ("couldn't reattach child %d from previous process", children
[i
].pid
);
1005 else if (!p
.reattach ())
1006 debug_only_printf ("attach of child process %d failed", children
[i
].pid
);
1008 debug_only_printf ("reattached pid %d<%u>, process handle %p, rd_proc_pipe %p->%p",
1009 p
->pid
, p
->dwProcessId
, p
.hProcess
,
1010 children
[i
].p
.rd_proc_pipe
, p
.rd_proc_pipe
);
1015 child_info_spawn::reattach_children ()
1017 moreinfo
->reattach_children (parent
);
1021 child_info::ready (bool execed
)
1025 sigproc_printf ("subproc_ready not set");
1029 if (dynamically_loaded
)
1030 sigproc_printf ("not really ready");
1031 else if (!SetEvent (subproc_ready
))
1032 api_fatal ("SetEvent failed, %E");
1034 sigproc_printf ("signalled %p that I was ready", subproc_ready
);
1038 CloseHandle (subproc_ready
);
1039 subproc_ready
= NULL
;
1044 child_info::sync (pid_t pid
, HANDLE
& hProcess
, DWORD howlong
)
1049 unsigned nsubproc_ready
;
1052 nsubproc_ready
= WAIT_OBJECT_0
+ 3;
1055 w4
[n
++] = subproc_ready
;
1060 sigproc_printf ("n %d, waiting for subproc_ready(%p) and child process(%p)", n
, w4
[0], w4
[1]);
1061 DWORD x
= WaitForMultipleObjects (n
, w4
, FALSE
, howlong
);
1065 system_printf ("wait failed, pid %u, %E", pid
);
1070 if (x
!= nsubproc_ready
)
1073 GetExitCodeProcess (hProcess
, &exit_code
);
1078 exit_code
= STILL_ACTIVE
;
1079 if (type
== _CH_EXEC
&& my_wr_proc_pipe
)
1081 ForceCloseHandle1 (hProcess
, childhProc
);
1085 sigproc_printf ("pid %u, WFMO returned %d, exit_code %p, res %d", pid
, x
,
1092 child_info::proc_retry (HANDLE h
)
1096 sigproc_printf ("exit_code %p", exit_code
);
1099 case STILL_ACTIVE
: /* shouldn't happen */
1100 sigproc_printf ("STILL_ACTIVE? How'd we get here?");
1102 case STATUS_DLL_NOT_FOUND
:
1103 case STATUS_ACCESS_VIOLATION
:
1104 case STATUS_ILLEGAL_INSTRUCTION
:
1105 case STATUS_ILLEGAL_DLL_PSEUDO_RELOCATION
: /* pseudo-reloc.c specific */
1107 case STATUS_CONTROL_C_EXIT
:
1110 /* fall through intentionally */
1111 case STATUS_DLL_INIT_FAILED
:
1112 case STATUS_DLL_INIT_FAILED_LOGOFF
:
1113 case EXITCODE_RETRY
:
1117 case EXITCODE_FORK_FAILED
: /* windows prevented us from forking */
1120 /* Count down non-recognized exit codes more quickly since they aren't
1121 due to known conditions. */
1123 if (!iscygwin () && (exit_code
& 0xffff0000) != 0xc0000000)
1125 if ((retry
-= 2) < 0)
1131 ForceCloseHandle1 (h
, childhProc
);
1136 child_info_fork::abort (const char *fmt
, ...)
1142 strace_vprintf (SYSTEM
, fmt
, ap
);
1143 TerminateProcess (GetCurrentProcess (), EXITCODE_FORK_FAILED
);
1146 TerminateProcess (GetCurrentProcess (), EXITCODE_RETRY
);
1150 /* Check the state of all of our children to see if any are stopped or
1153 static int __stdcall
1154 checkstate (waitq
*parent_w
)
1156 int potential_match
= 0;
1158 sigproc_printf ("nprocs %d", nprocs
);
1160 /* Check already dead processes first to see if they match the criteria
1161 * given in w->next. */
1163 for (int i
= 0; i
< nprocs
; i
++)
1164 if ((res
= stopped_or_terminated (parent_w
, procs
[i
])))
1167 potential_match
= 1;
1171 sigproc_printf ("no matching terminated children found");
1172 potential_match
= -!!nprocs
;
1175 sigproc_printf ("returning %d", potential_match
);
1176 return potential_match
;
1179 /* Remove a proc from procs by swapping it with the last child in the list.
1180 Also releases shared memory of exited processes. */
1181 static bool __stdcall
1182 remove_proc (int ci
)
1186 if (_my_tls
._ctinfo
!= procs
[ci
].wait_thread
)
1187 procs
[ci
].wait_thread
->terminate_thread ();
1189 else if (procs
[ci
]->exists ())
1192 sigproc_printf ("removing procs[%d], pid %d, nprocs %d", ci
, procs
[ci
]->pid
,
1194 if (procs
[ci
] != myself
)
1195 procs
[ci
].release ();
1198 /* Wait for proc_waiter thread to make a copy of this element before
1199 moving it or it may become confused. The chances are very high that
1200 the proc_waiter thread has already done this by the time we
1202 if (!have_execed
&& !exit_state
)
1203 while (!procs
[nprocs
].waiter_ready
)
1205 procs
[ci
] = procs
[nprocs
];
1210 /* Check status of child process vs. waitq member.
1212 parent_w is the pointer to the parent of the waitq member in question.
1213 child is the subprocess being considered.
1215 Returns non-zero if waiting thread released. */
1216 static bool __stdcall
1217 stopped_or_terminated (waitq
*parent_w
, _pinfo
*child
)
1220 waitq
*w
= parent_w
->next
;
1222 sigproc_printf ("considering pid %d", child
->pid
);
1225 else if (w
->pid
== 0)
1226 might_match
= child
->pgid
== myself
->pgid
;
1227 else if (w
->pid
< 0)
1228 might_match
= child
->pgid
== -w
->pid
;
1230 might_match
= (w
->pid
== child
->pid
);
1237 if (!((terminated
= (child
->process_state
== PID_EXITED
))
1238 || ((w
->options
& WCONTINUED
) && child
->stopsig
== SIGCONT
)
1239 || ((w
->options
& WUNTRACED
) && child
->stopsig
&& child
->stopsig
!= SIGCONT
)))
1242 parent_w
->next
= w
->next
; /* successful wait. remove from wait queue */
1243 w
->pid
= child
->pid
;
1247 sigproc_printf ("stopped child, stop signal %d", child
->stopsig
);
1248 if (child
->stopsig
== SIGCONT
)
1249 w
->status
= __W_CONTINUED
;
1251 w
->status
= (child
->stopsig
<< 8) | 0x7f;
1256 child
->process_state
= PID_REAPED
;
1257 w
->status
= (__uint16_t
) child
->exitcode
;
1259 add_rusage (&myself
->rusage_children
, &child
->rusage_children
);
1260 add_rusage (&myself
->rusage_children
, &child
->rusage_self
);
1264 add_rusage ((struct rusage
*) w
->rusage
, &child
->rusage_children
);
1265 add_rusage ((struct rusage
*) w
->rusage
, &child
->rusage_self
);
1269 if (!SetEvent (w
->ev
)) /* wake up wait4 () immediately */
1270 system_printf ("couldn't wake up wait event %p, %E", w
->ev
);
1275 talktome (siginfo_t
*si
)
1277 unsigned size
= sizeof (*si
);
1278 sigproc_printf ("pid %d wants some information", si
->si_pid
);
1279 if (si
->_si_commune
._si_code
& PICOM_EXTRASTR
)
1283 if (!ReadFile (my_readsig
, &n
, sizeof (n
), &nb
, NULL
) || nb
!= sizeof (n
))
1285 siginfo_t
*newsi
= (siginfo_t
*) alloca (size
+= n
+ 1);
1287 newsi
->_si_commune
._si_str
= (char *) (newsi
+ 1);
1288 if (!ReadFile (my_readsig
, newsi
->_si_commune
._si_str
, n
, &nb
, NULL
) || nb
!= n
)
1290 newsi
->_si_commune
._si_str
[n
] = '\0';
1294 pinfo
pi (si
->si_pid
);
1296 new cygthread (commune_process
, size
, si
, "commune");
1300 pending_signals::add (sigpacket
& pack
)
1303 if (sigs
[pack
.si
.si_signo
].si
.si_signo
)
1305 se
= sigs
+ pack
.si
.si_signo
;
1307 se
->mask
= &pack
.tls
->sigmask
;
1317 pending_signals::del ()
1319 sigpacket
*next
= curr
->next
;
1321 curr
->si
.si_signo
= 0;
1331 pending_signals::next ()
1335 if (!curr
|| !(curr
= curr
->next
))
1342 /* Process signals by waiting for signal data to arrive in a pipe.
1343 Set a completion event if one was specified. */
1347 _sig_tls
= &_my_tls
;
1348 sigCONT
= CreateEvent (&sec_none_nih
, FALSE
, FALSE
, NULL
);
1350 sigproc_printf ("entering ReadFile loop, my_readsig %p, my_sendsig %p",
1351 my_readsig
, my_sendsig
);
1354 pack
.si
.si_signo
= 0;
1357 if (pack
.si
.si_signo
== __SIGHOLD
)
1358 WaitForSingleObject (sigCONT
, INFINITE
);
1361 if (!ReadFile (my_readsig
, &pack
, sizeof (pack
), &nb
, NULL
))
1364 if (nb
!= sizeof (pack
))
1366 system_printf ("short read from signal pipe: %d != %d", nb
,
1371 if (!pack
.si
.si_signo
)
1374 system_printf ("zero signal?");
1379 sigset_t dummy_mask
;
1382 dummy_mask
= _main_tls
->sigmask
;
1383 pack
.mask
= &dummy_mask
;
1387 bool clearwait
= false;
1388 switch (pack
.si
.si_signo
)
1391 talktome (&pack
.si
);
1394 strace
.activate (false);
1400 while ((q
= sigq
.next ()))
1401 if (pack
.tls
->sigmask
& (bit
= SIGTOMASK (q
->si
.si_signo
)))
1409 case __SIGFLUSHFAST
:
1411 while ((q
= sigq
.next ()))
1413 int sig
= q
->si
.si_signo
;
1414 if (sig
== __SIGDELETE
|| q
->process () > 0)
1416 if (sig
== __SIGNOHOLD
&& q
->si
.si_signo
== SIGCHLD
)
1422 sigproc_printf ("saw __SIGEXIT");
1423 break; /* handle below */
1425 init_console_handler (true);
1428 if (pack
.si
.si_signo
< 0)
1429 sig_clear (-pack
.si
.si_signo
);
1432 int sig
= pack
.si
.si_signo
;
1433 // FIXME: REALLY not right when taking threads into consideration.
1434 // We need a per-thread queue since each thread can have its own
1435 // list of blocked signals. CGF 2005-08-24
1436 if (sigq
.sigs
[sig
].si
.si_signo
&& sigq
.sigs
[sig
].tls
== pack
.tls
)
1437 sigproc_printf ("signal %d already queued", pack
.si
.si_signo
);
1440 int sigres
= pack
.process ();
1445 system_printf ("Failed to arm signal %d from pid %d", pack
.si
.si_signo
, pack
.pid
);
1447 sigq
.add (pack
); // FIXME: Shouldn't add this in !sh condition
1456 proc_subproc (PROC_CLEARWAIT
, 0);
1460 sigproc_printf ("signalling pack.wakeup %p", pack
.wakeup
);
1461 SetEvent (pack
.wakeup
);
1463 if (pack
.si
.si_signo
== __SIGEXIT
)
1467 close_my_readsig ();
1468 sigproc_printf ("signal thread exiting");