OSDN Git Service

b4a9ee18f821d8608850a5929dbfaf6285fafa1d
[pf3gnuchains/sourceware.git] / winsup / cygwin / sigproc.cc
1 /* sigproc.cc: inter/intra signal and sub process handler
2
3    Copyright 1997, 1998, 1999, 2000, 2001, 2002, 2003 Red Hat, Inc.
4
5    Written by Christopher Faylor
6
7 This file is part of Cygwin.
8
9 This software is a copyrighted work licensed under the terms of the
10 Cygwin license.  Please consult the file "CYGWIN_LICENSE" for
11 details. */
12
13 #include "winsup.h"
14 #include <stdlib.h>
15 #include <time.h>
16 #include <sys/wait.h>
17 #include <stdlib.h>
18 #include <sys/cygwin.h>
19 #include <assert.h>
20 #include <sys/signal.h>
21 #include "cygerrno.h"
22 #include "sync.h"
23 #include "pinfo.h"
24 #include "security.h"
25 #include "path.h"
26 #include "fhandler.h"
27 #include "dtable.h"
28 #include "cygheap.h"
29 #include "child_info_magic.h"
30 #include "shared_info.h"
31 #include "cygthread.h"
32 #include "cygtls.h"
33 #include "sigproc.h"
34 #include "perthread.h"
35
36 /*
37  * Convenience defines
38  */
39 #define WSSC              60000 // Wait for signal completion
40 #define WPSP              40000 // Wait for proc_subproc mutex
41
42 #define PSIZE 63                // Number of processes
43
44 #define wake_wait_subproc() SetEvent (events[0])
45
46 #define no_signals_available() (!hwait_sig || !sig_loop_wait || exit_state)
47
48 #define NZOMBIES        256
49
50 struct sigelem
51 {
52   int sig;
53   int pid;
54   _threadinfo *tls;
55   class sigelem *next;
56   friend class pending_signals;
57   friend int __stdcall sig_dispatch_pending ();
58 };
59
60 class pending_signals
61 {
62   sigelem sigs[NSIG + 1];
63   sigelem start;
64   sigelem *end;
65   sigelem *prev;
66   sigelem *curr;
67   int empty;
68 public:
69   void reset () {curr = &start; prev = &start;}
70   void add (int sig, int pid, _threadinfo *tls);
71   void del ();
72   sigelem *next ();
73   friend int __stdcall sig_dispatch_pending ();
74 };
75
76 struct sigpacket
77 {
78   int sig;
79   pid_t pid;
80   HANDLE wakeup;
81   sigset_t *mask;
82   _threadinfo *tls;
83 };
84
85 static pending_signals sigqueue;
86
87 struct sigaction *global_sigs;
88
89 void __stdcall
90 sigalloc ()
91 {
92   cygheap->sigs = global_sigs =
93     (struct sigaction *) ccalloc (HEAP_SIGS, NSIG, sizeof (struct sigaction));
94 }
95
96 void __stdcall
97 signal_fixup_after_exec ()
98 {
99   global_sigs = cygheap->sigs;
100   /* Set up child's signal handlers */
101   for (int i = 0; i < NSIG; i++)
102     {
103       global_sigs[i].sa_mask = 0;
104       if (global_sigs[i].sa_handler != SIG_IGN)
105         global_sigs[i].sa_handler = SIG_DFL;
106     }
107 }
108
109 /*
110  * Global variables
111  */
112 const char *__sp_fn ;
113 int __sp_ln;
114
115 char NO_COPY myself_nowait_dummy[1] = {'0'};// Flag to sig_send that signal goes to
116                                         //  current process but no wait is required
117 HANDLE NO_COPY signal_arrived;          // Event signaled when a signal has
118                                         //  resulted in a user-specified
119                                         //  function call
120 /*
121  * Common variables
122  */
123
124
125 /* How long to wait for message/signals.  Normally this is infinite.
126  * On termination, however, these are set to zero as a flag to exit.
127  */
128
129 #define Static static NO_COPY
130
131 Static DWORD proc_loop_wait = 1000;     // Wait for subprocesses to exit
132 Static DWORD sig_loop_wait = INFINITE;  // Wait for signals to arrive
133
134 Static HANDLE sigcomplete_main;         // Event signaled when a signal has
135                                         //  finished processing for the main
136                                         //  thread
137 HANDLE NO_COPY sigCONT;                 // Used to "STOP" a process
138 Static cygthread *hwait_sig;            // Handle of wait_sig thread
139 Static cygthread *hwait_subproc;        // Handle of sig_subproc thread
140
141 Static HANDLE wait_sig_inited;          // Control synchronization of
142                                         //  message queue startup
143
144 /* Used by WaitForMultipleObjects.  These are handles to child processes.
145  */
146 Static HANDLE events[PSIZE + 1];          // All my children's handles++
147 #define hchildren (events + 1)          // Where the children handles begin
148 Static char cpchildren[PSIZE * sizeof (pinfo)];         // All my children info
149 Static int nchildren;                   // Number of active children
150 Static char czombies[(NZOMBIES + 1) * sizeof (pinfo)];          // All my deceased children info
151 Static int nzombies;                    // Number of deceased children
152
153 #define pchildren ((pinfo *) cpchildren)
154 #define zombies ((pinfo *) czombies)
155
156 Static waitq waitq_head = {0, 0, 0, 0, 0, 0, 0};// Start of queue for wait'ing threads
157 Static waitq waitq_main;                // Storage for main thread
158
159 muto NO_COPY *sync_proc_subproc = NULL; // Control access to subproc stuff
160
161 DWORD NO_COPY sigtid = 0;               // ID of the signal thread
162
163 /* Functions
164  */
165 static int __stdcall checkstate (waitq *) __attribute__ ((regparm (1)));
166 static __inline__ BOOL get_proc_lock (DWORD, DWORD);
167 static void __stdcall remove_zombie (int);
168 static DWORD WINAPI wait_sig (VOID *arg);
169 static int __stdcall stopped_or_terminated (waitq *, _pinfo *);
170 static DWORD WINAPI wait_subproc (VOID *);
171
172 /* Determine if the parent process is alive.
173  */
174
175 BOOL __stdcall
176 my_parent_is_alive ()
177 {
178   DWORD res;
179   if (!myself->ppid_handle)
180     {
181       debug_printf ("No myself->ppid_handle");
182       res = FALSE;
183     }
184   else
185     for (int i = 0; i < 2; i++)
186       switch (res = WaitForSingleObject (myself->ppid_handle, 0))
187         {
188           case WAIT_OBJECT_0:
189             debug_printf ("parent dead.");
190             res = FALSE;
191             goto out;
192           case WAIT_TIMEOUT:
193             debug_printf ("parent still alive");
194             res = TRUE;
195             goto out;
196           case WAIT_FAILED:
197             DWORD werr = GetLastError ();
198             if (werr == ERROR_INVALID_HANDLE && i == 0)
199               continue;
200             system_printf ("WFSO for myself->ppid_handle(%p) failed, error %d",
201                            myself->ppid_handle, werr);
202             res = FALSE;
203             goto out;
204         }
205 out:
206   return res;
207 }
208
209 void __stdcall
210 wait_for_sigthread ()
211 {
212   sigproc_printf ("wait_sig_inited %p", wait_sig_inited);
213   HANDLE hsig_inited = wait_sig_inited;
214   (void) WaitForSingleObject (hsig_inited, INFINITE);
215   wait_sig_inited = NULL;
216   (void) ForceCloseHandle1 (hsig_inited, wait_sig_inited);
217 }
218
219 /* Get the sync_proc_subproc muto to control access to
220  * children, zombie arrays.
221  * Attempt to handle case where process is exiting as we try to grab
222  * the mutex.
223  */
224 static BOOL
225 get_proc_lock (DWORD what, DWORD val)
226 {
227   Static int lastwhat = -1;
228   if (!sync_proc_subproc)
229     return FALSE;
230   if (sync_proc_subproc->acquire (WPSP))
231     {
232       lastwhat = what;
233       return TRUE;
234     }
235   if (!sync_proc_subproc)
236     return FALSE;
237   system_printf ("Couldn't aquire sync_proc_subproc for(%d,%d), %E, last %d",
238                   what, val, lastwhat);
239   return TRUE;
240 }
241
242 static BOOL __stdcall
243 proc_can_be_signalled (_pinfo *p)
244 {
245   if (p == myself_nowait || p == myself)
246     {
247       assert (!wait_sig_inited);
248       return 1;
249     }
250
251   return ISSTATE (p, PID_INITIALIZING) ||
252          (((p)->process_state & (PID_ACTIVE | PID_IN_USE)) ==
253           (PID_ACTIVE | PID_IN_USE));
254 }
255
256 BOOL __stdcall
257 pid_exists (pid_t pid)
258 {
259   pinfo p (pid);
260   return proc_exists (p);
261 }
262
263 /* Test to determine if a process really exists and is processing signals.
264  */
265 BOOL __stdcall
266 proc_exists (_pinfo *p)
267 {
268   return p && !(p->process_state & (PID_EXITED | PID_ZOMBIE));
269 }
270
271 /* Return 1 if this is one of our children, zero otherwise.
272    FIXME: This really should be integrated with the rest of the proc_subproc
273    testing.  Scanning these lists twice is inefficient. */
274 int __stdcall
275 mychild (int pid)
276 {
277   for (int i = 0; i < nchildren; i++)
278     if (pchildren[i]->pid == pid)
279       return 1;
280   for (int i = 0; i < nzombies; i++)
281     if (zombies[i]->pid == pid)
282       return 1;
283   return 0;
284 }
285
286 /* Handle all subprocess requests
287  */
288 #define vchild (*((pinfo *) val))
289 int __stdcall
290 proc_subproc (DWORD what, DWORD val)
291 {
292   int rc = 1;
293   int potential_match;
294   _pinfo *child;
295   int clearing;
296   waitq *w;
297
298 #define wval     ((waitq *) val)
299
300   sigproc_printf ("args: %x, %d", what, val);
301
302   if (!get_proc_lock (what, val))       // Serialize access to this function
303     {
304       system_printf ("couldn't get proc lock.  Something is wrong.");
305       goto out1;
306     }
307
308   switch (what)
309     {
310     /* Add a new subprocess to the children arrays.
311      * (usually called from the main thread)
312      */
313     case PROC_ADDCHILD:
314       if (nchildren >= PSIZE - 1)
315         {
316           rc = 0;
317           break;
318         }
319       pchildren[nchildren] = vchild;
320       hchildren[nchildren] = vchild->hProcess;
321       if (!DuplicateHandle (hMainProc, vchild->hProcess, hMainProc, &vchild->pid_handle,
322                             0, 0, DUPLICATE_SAME_ACCESS))
323         system_printf ("Couldn't duplicate child handle for pid %d, %E", vchild->pid);
324       ProtectHandle1 (vchild->pid_handle, pid_handle);
325
326       if (!DuplicateHandle (hMainProc, hMainProc, vchild->hProcess, &vchild->ppid_handle,
327                             SYNCHRONIZE | PROCESS_DUP_HANDLE, TRUE, 0))
328         system_printf ("Couldn't duplicate my handle<%p> for pid %d, %E", hMainProc, vchild->pid);
329       vchild->ppid = myself->pid;
330       vchild->uid = myself->uid;
331       vchild->gid = myself->gid;
332       vchild->pgid = myself->pgid;
333       vchild->sid = myself->sid;
334       vchild->ctty = myself->ctty;
335       vchild->process_state |= PID_INITIALIZING | (myself->process_state & PID_USETTY);
336
337       sigproc_printf ("added pid %d to wait list, slot %d, winpid %p, handle %p",
338                   vchild->pid, nchildren, vchild->dwProcessId,
339                   vchild->hProcess);
340       nchildren++;
341
342       wake_wait_subproc ();
343       break;
344
345     /* A child process had terminated.
346        Possibly this is just due to an exec().  Cygwin implements an exec()
347        as a "handoff" from one windows process to another.  If child->hProcess
348        is different from what is recorded in hchildren, then this is an exec().
349        Otherwise this is a normal child termination event.
350        (called from wait_subproc thread) */
351     case PROC_CHILDTERMINATED:
352       if (hchildren[val] != pchildren[val]->hProcess)
353         {
354           sigproc_printf ("pid %d[%d], reparented old hProcess %p, new %p",
355                           pchildren[val]->pid, val, hchildren[val], pchildren[val]->hProcess);
356           HANDLE h = hchildren[val];
357           hchildren[val] = pchildren[val]->hProcess; /* Filled out by child */
358           sync_proc_subproc->release ();        // Release the lock ASAP
359           ForceCloseHandle1 (h, childhProc);
360           ProtectHandle1 (pchildren[val]->hProcess, childhProc);
361           rc = 0;
362           goto out;                     // This was an exec()
363         }
364
365       sigproc_printf ("pid %d[%d] terminated, handle %p, nchildren %d, nzombies %d",
366                   pchildren[val]->pid, val, hchildren[val], nchildren, nzombies);
367
368       int thiszombie;
369       thiszombie = nzombies;
370       zombies[nzombies] = pchildren[val];       // Add to zombie array
371       zombies[nzombies++]->process_state = PID_ZOMBIE;// Walking dead
372
373       sigproc_printf ("zombifying [%d], pid %d, handle %p, nchildren %d",
374                       val, pchildren[val]->pid, hchildren[val], nchildren);
375       if ((int) val < --nchildren)
376         {
377           hchildren[val] = hchildren[nchildren];
378           pchildren[val] = pchildren[nchildren];
379         }
380
381       /* See if we should care about the this terminated process.  If we've
382          filled up our table or if we're ignoring SIGCHLD, then we immediately
383          remove the process and move on. Otherwise, this process becomes a zombie
384          which must be reaped by a wait() call. */
385       if (nzombies >= NZOMBIES
386           || global_sigs[SIGCHLD].sa_handler == (void *) SIG_IGN)
387         {
388           sigproc_printf ("automatically removing zombie %d", thiszombie);
389           remove_zombie (thiszombie);
390         }
391
392       /* Don't scan the wait queue yet.  Caller will send SIGCHLD to this process.
393          This will cause an eventual scan of waiters. */
394       break;
395
396     /* Handle a wait4() operation.  Allocates an event for the calling
397      * thread which is signaled when the appropriate pid exits or stops.
398      * (usually called from the main thread)
399      */
400     case PROC_WAIT:
401       wval->ev = NULL;          // Don't know event flag yet
402
403       if (wval->pid <= 0)
404         child = NULL;           // Not looking for a specific pid
405       else if (!mychild (wval->pid))
406         goto out;               // invalid pid.  flag no such child
407
408       wval->status = 0;         // Don't know status yet
409       sigproc_printf ("wval->pid %d, wval->options %d", wval->pid, wval->options);
410
411       /* If the first time for this thread, create a new event, otherwise
412        * reset the event.
413        */
414       if ((wval->ev = wval->thread_ev) == NULL)
415         {
416           wval->ev = wval->thread_ev = CreateEvent (&sec_none_nih, TRUE,
417                                                     FALSE, NULL);
418           ProtectHandle (wval->ev);
419         }
420
421       ResetEvent (wval->ev);
422       w = waitq_head.next;
423       waitq_head.next = wval;   /* Add at the beginning. */
424       wval->next = w;           /* Link in rest of the list. */
425       clearing = 0;
426       goto scan_wait;
427
428     /* Clear all waiting threads.  Called from exceptions.cc prior to
429        the main thread's dispatch to a signal handler function.
430        (called from wait_sig thread) */
431     case PROC_CLEARWAIT:
432       /* Clear all "wait"ing threads. */
433       if (val)
434         sigproc_printf ("clear waiting threads");
435       else
436         sigproc_printf ("looking for processes to reap");
437       clearing = val;
438
439     scan_wait:
440       /* Scan the linked list of wait()ing threads.  If a wait's parameters
441        * match this pid, then activate it.
442        */
443       for (w = &waitq_head; w->next != NULL; w = w->next)
444         {
445           if ((potential_match = checkstate (w)) > 0)
446             sigproc_printf ("released waiting thread");
447           else if (!clearing && !(w->next->options & WNOHANG) && potential_match < 0)
448             sigproc_printf ("only found non-terminated children");
449           else if (potential_match <= 0)                // nothing matched
450             {
451               sigproc_printf ("waiting thread found no children");
452               HANDLE oldw = w->next->ev;
453               w->next->pid = 0;
454               if (clearing)
455                 w->next->status = -1;           /* flag that a signal was received */
456               else if (!potential_match || !(w->next->options & WNOHANG))
457                 w->next->ev = NULL;
458               if (!SetEvent (oldw))
459                 system_printf ("couldn't wake up wait event %p, %E", oldw);
460               w->next = w->next->next;
461             }
462           if (w->next == NULL)
463             break;
464         }
465
466       if (!clearing)
467         sigproc_printf ("finished processing terminated/stopped child");
468       else
469         {
470           waitq_head.next = NULL;
471           sigproc_printf ("finished clearing");
472         }
473       break;
474   }
475
476 out:
477   sync_proc_subproc->release ();        // Release the lock
478 out1:
479   sigproc_printf ("returning %d", rc);
480   return rc;
481 }
482
483 /* Terminate the wait_subproc thread.
484  * Called on process exit.
485  * Also called by spawn_guts to disassociate any subprocesses from this
486  * process.  Subprocesses will then know to clean up after themselves and
487  * will not become zombies.
488  */
489 void __stdcall
490 proc_terminate (void)
491 {
492   sigproc_printf ("nchildren %d, nzombies %d", nchildren, nzombies);
493   /* Signal processing is assumed to be blocked in this routine. */
494   if (hwait_subproc)
495     {
496       proc_loop_wait = 0;       // Tell wait_subproc thread to exit
497       sync_proc_subproc->acquire (WPSP);
498       wake_wait_subproc ();     // Wake wait_subproc loop
499       hwait_subproc = NULL;
500
501       (void) proc_subproc (PROC_CLEARWAIT, 1);
502
503       /* Clean out zombie processes from the pid list. */
504       int i;
505       for (i = 0; i < nzombies; i++)
506         {
507           if (zombies[i]->hProcess)
508             {
509               ForceCloseHandle1 (zombies[i]->hProcess, childhProc);
510               ForceCloseHandle1 (zombies[i]->pid_handle, pid_handle);
511             }
512           zombies[i]->ppid = 1;
513           zombies[i]->process_state = PID_EXITED;       /* CGF FIXME - still needed? */
514           zombies[i].release ();        // FIXME: this breaks older gccs for some reason
515         }
516
517       /* Disassociate my subprocesses */
518       for (i = 0; i < nchildren; i++)
519         {
520           if (!pchildren[i]->hProcess)
521             sigproc_printf ("%d(%d) hProcess cleared already?", pchildren[i]->pid,
522                         pchildren[i]->dwProcessId);
523           else
524             {
525               ForceCloseHandle1 (pchildren[i]->hProcess, childhProc);
526               sigproc_printf ("%d(%d) closed child handle", pchildren[i]->pid,
527                               pchildren[i]->dwProcessId);
528               pchildren[i]->ppid = 1;
529               if (pchildren[i]->pgid == myself->pid)
530                 pchildren[i]->process_state |= PID_ORPHANED;
531             }
532           pchildren[i].release ();
533         }
534       nchildren = nzombies = 0;
535       /* Just zero sync_proc_subproc as the delete below seems to cause
536          problems for older gccs. */
537         sync_proc_subproc = NULL;
538     }
539   sigproc_printf ("leaving");
540 }
541
542 /* Clear pending signal */
543 void __stdcall
544 sig_clear (int target_sig)
545 {
546   if (GetCurrentThreadId () != sigtid)
547     sig_send (myself, -target_sig);
548   else
549     {
550       sigqueue.reset ();
551       sigelem *q;
552       while ((q = sigqueue.next ()))
553         if (q->sig == target_sig)
554           {
555             sigqueue.del ();
556             break;
557           }
558     }
559   return;
560 }
561
562 extern "C" int
563 sigpending (sigset_t *mask)
564 {
565   sigset_t outset = (sigset_t) sig_send (myself, __SIGPENDING);
566   if (outset == SIG_BAD_MASK)
567     return -1;
568   *mask = outset;
569   return 0;
570 }
571
572 /* Force the wait_sig thread to wake up and scan for pending signals */
573 int __stdcall
574 sig_dispatch_pending ()
575 {
576   if (exit_state || GetCurrentThreadId () == sigtid || !sigqueue.start.next)
577     return 0;
578
579   (void) sig_send (myself, __SIGFLUSH);
580   return call_signal_handler_now ();
581 }
582
583 /* Message initialization.  Called from dll_crt0_1
584  *
585  * This routine starts the signal handling thread.  The wait_sig_inited
586  * event is used to signal that the thread is ready to handle signals.
587  * We don't wait for this during initialization but instead detect it
588  * in sig_send to gain a little concurrency.
589  */
590 void __stdcall
591 sigproc_init ()
592 {
593   wait_sig_inited = CreateEvent (&sec_none_nih, TRUE, FALSE, NULL);
594   ProtectHandle (wait_sig_inited);
595
596   /* sync_proc_subproc is used by proc_subproc.  It serialises
597    * access to the children and zombie arrays.
598    */
599   new_muto (sync_proc_subproc);
600
601   /* local event signaled when main thread has been dispatched
602      to a signal handler function. */
603   signal_arrived = CreateEvent (&sec_none_nih, TRUE, FALSE, NULL);
604   ProtectHandle (signal_arrived);
605
606   hwait_sig = new cygthread (wait_sig, cygself, "sig");
607   hwait_sig->zap_h ();
608
609   /* Initialize waitq structure for main thread.  A waitq structure is
610    * allocated for each thread that executes a wait to allow multiple threads
611    * to perform waits.  Pre-allocate a waitq structure for the main thread.
612    */
613   waitq *w;
614   if ((w = (waitq *)waitq_storage.get ()) == NULL)
615     {
616       w = &waitq_main;
617       waitq_storage.set (w);
618     }
619   memset (w, 0, sizeof *w);     // Just to be safe
620
621   global_sigs[SIGSTOP].sa_flags = SA_RESTART | SA_NODEFER;
622   sigproc_printf ("process/signal handling enabled(%x)", myself->process_state);
623   return;
624 }
625
626 /* Called on process termination to terminate signal and process threads.
627  */
628 void __stdcall
629 sigproc_terminate (void)
630 {
631   hwait_sig = NULL;
632
633   if (!sig_loop_wait)
634     sigproc_printf ("sigproc handling not active");
635   else
636     {
637       sigproc_printf ("entering");
638       sig_loop_wait = 0;        // Tell wait_sig to exit when it is
639                                 //  finished with anything it is doing
640       ForceCloseHandle (sigcomplete_main);
641       CloseHandle (myself->sendsig);
642     }
643   proc_terminate ();            // Terminate process handling thread
644
645   return;
646 }
647
648 /* Send a signal to another process by raising its signal semaphore.
649  * If pinfo *p == NULL, send to the current process.
650  * If sending to this process, wait for notification that a signal has
651  * completed before returning.
652  */
653 int __stdcall
654 sig_send (_pinfo *p, int sig, void *tls)
655 {
656   int rc = 1;
657   BOOL its_me;
658   HANDLE sendsig;
659   sigpacket pack;
660
661   bool wait_for_completion;
662   // FIXMENOW: Avoid using main thread's completion event!
663   if (!(its_me = (p == NULL || p == myself || p == myself_nowait)))
664     wait_for_completion = false;
665   else
666     {
667       if (no_signals_available ())
668         goto out;               // Either exiting or not yet initializing
669       if (wait_sig_inited)
670         wait_for_sigthread ();
671       wait_for_completion = p != myself_nowait && _my_tls.isinitialized ();
672       p = myself;
673     }
674
675   /* It is possible that the process is not yet ready to receive messages
676    * or that it has exited.  Detect this.
677    */
678   if (!proc_can_be_signalled (p))       /* Is the process accepting messages? */
679     {
680       sigproc_printf ("invalid pid %d(%x), signal %d",
681                   p->pid, p->process_state, sig);
682       set_errno (ESRCH);
683       goto out;
684     }
685
686   sigproc_printf ("pid %d, signal %d, its_me %d", p->pid, sig, its_me);
687
688   if (its_me)
689     {
690       sendsig = myself->sendsig;
691       if (wait_for_completion)
692         pack.wakeup = sigcomplete_main;
693     }
694   else
695     {
696       HANDLE hp = OpenProcess (PROCESS_DUP_HANDLE, false, p->dwProcessId);
697       if (!hp)
698         {
699           sigproc_printf ("OpenProcess failed, %E");
700           __seterrno ();
701           goto out;
702         }
703       for (int i = 0; !p->sendsig && i < 10000; i++)
704         low_priority_sleep (0);
705       if (!DuplicateHandle (hp, p->sendsig, hMainProc, &sendsig, false, 0,
706                             DUPLICATE_SAME_ACCESS) || !sendsig)
707         {
708           sigproc_printf ("DuplicateHandle failed, %E");
709           __seterrno ();
710           goto out;
711         }
712       CloseHandle (hp);
713       pack.wakeup = NULL;
714     }
715
716   sigset_t pending;
717   if (!its_me)
718     pack.mask = NULL;
719   else if (sig == __SIGPENDING)
720     pack.mask = &pending;
721   else if (sig == __SIGFLUSH || sig > 0)
722     pack.mask = &myself->getsigmask ();
723   else
724     pack.mask = NULL;
725
726   pack.sig = sig;
727   pack.pid = myself->pid;
728   pack.tls = (_threadinfo *) tls;
729   DWORD nb;
730   if (!WriteFile (sendsig, &pack, sizeof (pack), &nb, NULL) || nb != sizeof (pack))
731     {
732       /* Couldn't send to the pipe.  This probably means that the
733          process is exiting.  */
734       if (!its_me)
735         {
736           sigproc_printf ("WriteFile for pipe %p failed, %E", sendsig);
737           __seterrno ();
738           ForceCloseHandle (sendsig);
739         }
740       else
741         {
742           if (no_signals_available ())
743             sigproc_printf ("I'm going away now");
744           else
745             system_printf ("error sending signal %d to pid %d, pipe handle %p, %E",
746                           sig, p->pid, sendsig);
747         }
748       goto out;
749     }
750
751
752   /* No need to wait for signal completion unless this was a signal to
753      this process.
754
755      If it was a signal to this process, wait for a dispatched signal.
756      Otherwise just wait for the wait_sig to signal that it has finished
757      processing the signal.  */
758   if (wait_for_completion)
759     {
760       sigproc_printf ("Waiting for pack.wakeup %p", pack.wakeup);
761       rc = WaitForSingleObject (pack.wakeup, WSSC);
762     }
763   else
764     {
765       rc = WAIT_OBJECT_0;
766       sigproc_printf ("Not waiting for sigcomplete.  its_me %d signal %d", its_me, sig);
767       if (!its_me)
768         ForceCloseHandle (sendsig);
769     }
770
771   if (rc == WAIT_OBJECT_0)
772     rc = 0;             // Successful exit
773   else
774     {
775       /* It's an error unless sig_loop_wait == 0 (the process is exiting). */
776       if (!no_signals_available ())
777         system_printf ("wait for sig_complete event failed, signal %d, rc %d, %E",
778                       sig, rc);
779       set_errno (ENOSYS);
780       rc = -1;
781     }
782
783   if (wait_for_completion)
784     call_signal_handler_now ();
785
786 out:
787   if (sig != __SIGPENDING)
788     /* nothing */;
789   else if (!rc)
790     rc = (int) pending;
791   else
792     rc = SIG_BAD_MASK;
793   sigproc_printf ("returning %p from sending signal %d", rc, sig);
794   return rc;
795 }
796
797 /* Initialize the wait_subproc thread.
798  * Called from fork() or spawn() to initialize the handling of subprocesses.
799  */
800 void __stdcall
801 subproc_init (void)
802 {
803   if (hwait_subproc)
804     return;
805
806   /* A "wakeup" handle which can be toggled to make wait_subproc reexamine
807    * the hchildren array.
808    */
809   events[0] = CreateEvent (&sec_none_nih, FALSE, FALSE, NULL);
810   hwait_subproc = new cygthread (wait_subproc, NULL, "proc");
811   hwait_subproc->zap_h ();
812   ProtectHandle (events[0]);
813   sigproc_printf ("started wait_subproc thread");
814 }
815
816 /* Initialize some of the memory block passed to child processes
817    by fork/spawn/exec. */
818
819 void __stdcall
820 init_child_info (DWORD chtype, child_info *ch, pid_t pid, HANDLE subproc_ready)
821 {
822   memset (ch, 0, sizeof *ch);
823   ch->cb = chtype == PROC_FORK ? sizeof (child_info_fork) : sizeof (child_info);
824   ch->intro = PROC_MAGIC_GENERIC;
825   ch->magic = CHILD_INFO_MAGIC;
826   ch->type = chtype;
827   ch->cygpid = pid;
828   ch->subproc_ready = subproc_ready;
829   ch->pppid_handle = myself->ppid_handle;
830   ch->fhandler_union_cb = sizeof (fhandler_union);
831   ch->user_h = cygwin_user_h;
832 }
833
834 /* Check the state of all of our children to see if any are stopped or
835  * terminated.
836  */
837 static int __stdcall
838 checkstate (waitq *parent_w)
839 {
840   int potential_match = 0;
841
842   sigproc_printf ("nchildren %d, nzombies %d", nchildren, nzombies);
843
844   /* Check already dead processes first to see if they match the criteria
845    * given in w->next.
846    */
847   for (int i = 0; i < nzombies; i++)
848     switch (stopped_or_terminated (parent_w, zombies[i]))
849       {
850       case -1:
851         potential_match = -1;
852         break;
853       case 1:
854         remove_zombie (i);
855         potential_match = 1;
856         goto out;
857       }
858
859   sigproc_printf ("checking alive children");
860
861   /* No dead terminated children matched.  Check for stopped children. */
862   for (int i = 0; i < nchildren; i++)
863     switch (stopped_or_terminated (parent_w, pchildren[i]))
864       {
865       case -1:
866         potential_match = -1;
867         break;
868       case 1:
869         potential_match = 1;
870         goto out;
871       }
872
873 out:
874   sigproc_printf ("returning %d", potential_match);
875   return potential_match;
876 }
877
878 /* Remove a zombie from zombies by swapping it with the last child in the list.
879  */
880 static void __stdcall
881 remove_zombie (int ci)
882 {
883   sigproc_printf ("removing %d, pid %d, nzombies %d", ci, zombies[ci]->pid,
884                   nzombies);
885
886   if (zombies[ci])
887     {
888       ForceCloseHandle1 (zombies[ci]->hProcess, childhProc);
889       ForceCloseHandle1 (zombies[ci]->pid_handle, pid_handle);
890       zombies[ci].release ();
891     }
892
893   if (ci < --nzombies)
894     zombies[ci] = zombies[nzombies];
895
896   return;
897 }
898
899 /* Check status of child process vs. waitq member.
900  *
901  * parent_w is the pointer to the parent of the waitq member in question.
902  * child is the subprocess being considered.
903  *
904  * Returns
905  *   1 if stopped or terminated child matches parent_w->next criteria
906  *  -1 if a non-stopped/terminated child matches parent_w->next criteria
907  *   0 if child does not match parent_w->next criteria
908  */
909 static int __stdcall
910 stopped_or_terminated (waitq *parent_w, _pinfo *child)
911 {
912   int potential_match;
913   waitq *w = parent_w->next;
914
915   sigproc_printf ("considering pid %d", child->pid);
916   if (w->pid == -1)
917     potential_match = 1;
918   else if (w->pid == 0)
919     potential_match = child->pgid == myself->pgid;
920   else if (w->pid < 0)
921     potential_match = child->pgid == -w->pid;
922   else
923     potential_match = (w->pid == child->pid);
924
925   if (!potential_match)
926     return 0;
927
928   BOOL terminated;
929
930   if ((terminated = child->process_state == PID_ZOMBIE) ||
931       ((w->options & WUNTRACED) && child->stopsig))
932     {
933       parent_w->next = w->next; /* successful wait.  remove from wait queue */
934       w->pid = child->pid;
935
936       if (!terminated)
937         {
938           sigproc_printf ("stopped child");
939           w->status = (child->stopsig << 8) | 0x7f;
940           child->stopsig = 0;
941         }
942       else /* Should only get here when child has been moved to the zombies array */
943         {
944           DWORD status;
945           if (!GetExitCodeProcess (child->hProcess, &status))
946             status = 0xffff;
947           if (status & EXIT_SIGNAL)
948             w->status = (status >> 8) & 0xff;   /* exited due to signal */
949           else
950             w->status = (status & 0xff) << 8;   /* exited via "exit ()" */
951
952           add_rusage (&myself->rusage_children, &child->rusage_children);
953           add_rusage (&myself->rusage_children, &child->rusage_self);
954
955           if (w->rusage)
956             {
957               add_rusage ((struct rusage *) w->rusage, &child->rusage_children);
958               add_rusage ((struct rusage *) w->rusage, &child->rusage_self);
959             }
960         }
961
962       if (!SetEvent (w->ev))    /* wake up wait4 () immediately */
963         system_printf ("couldn't wake up wait event %p, %E", w->ev);
964       return 1;
965     }
966
967   return -potential_match;
968 }
969
970 static void
971 talktome ()
972 {
973   winpids pids ((DWORD) PID_MAP_RW);
974   for (unsigned i = 0; i < pids.npids; i++)
975     if (pids[i]->hello_pid == myself->pid)
976       if (!IsBadWritePtr (pids[i], sizeof (_pinfo)))
977         pids[i]->commune_recv ();
978 }
979
980 /* Process signals by waiting for a semaphore to become signaled.
981    Then scan an in-memory array representing queued signals.
982    Executes in a separate thread.
983
984    Signals sent from this process are sent a completion signal so
985    that returns from kill/raise do not occur until the signal has
986    has been handled, as per POSIX.  */
987
988 void
989 pending_signals::add (int sig, int pid, _threadinfo *tls)
990 {
991   sigelem *se;
992   for (se = start.next; se; se = se->next)
993     if (se->sig == sig)
994       return;
995   while (sigs[empty].sig)
996     if (++empty == NSIG)
997       empty = 0;
998   se = sigs + empty;
999   se->sig = sig;
1000   se->next = NULL;
1001   se->tls = tls;
1002   se->pid = pid;
1003   if (end)
1004     end->next = se;
1005   end = se;
1006   if (!start.next)
1007     start.next = se;
1008   empty++;
1009 }
1010
1011 void
1012 pending_signals::del ()
1013 {
1014   sigelem *next = curr->next;
1015   prev->next = next;
1016   curr->sig = 0;
1017 #ifdef DEBUGGING
1018   curr->next = NULL;
1019 #endif
1020   if (end == curr)
1021     end = prev;
1022   empty = curr - sigs;
1023   curr = next;
1024 }
1025
1026 sigelem *
1027 pending_signals::next ()
1028 {
1029   sigelem *res;
1030   prev = curr;
1031   if (!curr || !(curr = curr->next))
1032     res = NULL;
1033   else
1034     res = curr;
1035   return res;
1036 }
1037
1038 /* Process signals by waiting for signal data to arrive in a pipe.
1039    Set a completion event if one was specified. */
1040 static DWORD WINAPI
1041 wait_sig (VOID *self)
1042 {
1043   HANDLE readsig;
1044   char sa_buf[1024];
1045
1046   /* Initialization */
1047   (void) SetThreadPriority (GetCurrentThread (), WAIT_SIG_PRIORITY);
1048
1049   /* sigcomplete_main      - event used to signal main thread on signal
1050                              completion */
1051   if (!CreatePipe (&readsig, &myself->sendsig, sec_user_nih (sa_buf), 0))
1052     api_fatal ("couldn't create signal pipe, %E");
1053   sigcomplete_main = CreateEvent (&sec_none_nih, FALSE, FALSE, NULL);
1054   sigproc_printf ("sigcomplete_main %p", sigcomplete_main);
1055   sigCONT = CreateEvent (&sec_none_nih, FALSE, FALSE, NULL);
1056
1057   /* Setting dwProcessId flags that this process is now capable of receiving
1058      signals.  Prior to this, dwProcessId was set to the windows pid of
1059      of the original windows process which spawned us unless this was a
1060      "toplevel" process.  */
1061   myself->dwProcessId = GetCurrentProcessId ();
1062   myself->process_state |= PID_ACTIVE;
1063   myself->process_state &= ~PID_INITIALIZING;
1064
1065   ProtectHandle (sigcomplete_main);
1066
1067   /* If we've been execed, then there is still a stub left in the previous
1068      windows process waiting to see if it's started a cygwin process or not.
1069      Signalling subproc_ready indicates that we are a cygwin process.  */
1070   if (child_proc_info && child_proc_info->type == PROC_EXEC)
1071     {
1072       debug_printf ("subproc_ready %p", child_proc_info->subproc_ready);
1073       if (!SetEvent (child_proc_info->subproc_ready))
1074         system_printf ("SetEvent (subproc_ready) failed, %E");
1075       ForceCloseHandle1 (child_proc_info->subproc_ready, subproc_ready);
1076       /* Initialize an "indirect" pid block so that if someone looks up this
1077          process via its Windows PID it will be redirected to the appropriate
1078          Cygwin PID shared memory block. */
1079       static pinfo NO_COPY myself_identity;
1080       myself_identity.init (cygwin_pid (myself->dwProcessId), PID_EXECED);
1081     }
1082
1083   SetEvent (wait_sig_inited);
1084   sigtid = GetCurrentThreadId ();
1085
1086   for (;;)
1087     {
1088       DWORD nb;
1089       sigpacket pack;
1090       if (!ReadFile (readsig, &pack, sizeof (pack), &nb, NULL))
1091         break;
1092
1093       if (nb != sizeof (pack))
1094         {
1095           system_printf ("short read from signal pipe: %d != %d", nb,
1096                          sizeof (pack));
1097           continue;
1098         }
1099
1100       if (!pack.sig)
1101         {
1102 #ifdef DEBUGGING
1103           system_printf ("zero signal?");
1104 #endif
1105           continue;
1106         }
1107
1108       sigset_t dummy_mask;
1109       if (!pack.mask)
1110         {
1111           dummy_mask = myself->getsigmask ();
1112           pack.mask = &dummy_mask;
1113         }
1114
1115       sigelem *q;
1116       switch (pack.sig)
1117         {
1118         case __SIGCOMMUNE:
1119           talktome ();
1120           break;
1121         case __SIGSTRACE:
1122           strace.hello ();
1123           break;
1124         case __SIGPENDING:
1125           *pack.mask = 0;
1126           unsigned bit;
1127           sigqueue.reset ();
1128           while ((q = sigqueue.next ()))
1129             if (myself->getsigmask () & (bit = SIGTOMASK (q->sig)))
1130               *pack.mask |= bit;
1131           break;
1132         case __SIGFLUSH:
1133           sigqueue.reset ();
1134           while ((q = sigqueue.next ()))
1135             if (sig_handle (q->sig, *pack.mask, q->pid, q->tls) > 0)
1136               sigqueue.del ();
1137           break;
1138         default:
1139           if (pack.sig < 0)
1140             sig_clear (-pack.sig);
1141           else
1142             {
1143               if (sig_handle (pack.sig, *pack.mask, pack.pid, pack.tls) <= 0)
1144                 sigqueue.add (pack.sig, pack.pid, pack.tls);// FIXME: Shouldn't add this in !sh condition
1145               if (pack.sig == SIGCHLD)
1146                 proc_subproc (PROC_CLEARWAIT, 0);
1147             }
1148           break;
1149         }
1150       if (pack.wakeup)
1151         SetEvent (pack.wakeup);
1152     }
1153
1154   sigproc_printf ("done");
1155   ExitThread (0);
1156 }
1157
1158 /* Wait for subprocesses to terminate. Executes in a separate thread. */
1159 static DWORD WINAPI
1160 wait_subproc (VOID *)
1161 {
1162   sigproc_printf ("starting");
1163   int errloop = 0;
1164
1165   for (;;)
1166     {
1167       DWORD rc = WaitForMultipleObjects (nchildren + 1, events, FALSE,
1168                                          proc_loop_wait);
1169       if (rc == WAIT_TIMEOUT)
1170         if (!proc_loop_wait)
1171           break;                        // Exiting
1172         else
1173           continue;
1174
1175       if (rc == WAIT_FAILED)
1176         {
1177           if (!proc_loop_wait)
1178             break;
1179
1180           /* It's ok to get an ERROR_INVALID_HANDLE since another thread may have
1181              closed a handle in the children[] array.  So, we try looping a couple
1182              of times to stabilize. FIXME - this is not foolproof.  Probably, this
1183              thread should be responsible for closing the children. */
1184           if (!errloop++)
1185             proc_subproc (PROC_NOTHING, 0);     // Just synchronize and continue
1186           if (errloop < 10)
1187             continue;
1188
1189           system_printf ("wait failed. nchildren %d, wait %d, %E",
1190                         nchildren, proc_loop_wait);
1191
1192           for (int i = 0; i <= nchildren; i++)
1193             if ((rc = WaitForSingleObject (events[i], 0)) == WAIT_OBJECT_0 ||
1194                 rc == WAIT_TIMEOUT)
1195               continue;
1196             else if (i == 0)
1197                 system_printf ("nchildren %d, event[%d] %p, %E", nchildren, i, events[i]);
1198             else
1199               {
1200                 system_printf ("nchildren %d, event[%d] %p, pchildren[%d] %p, events[0] %p, %E",
1201                                nchildren, i, events[i], i - 1, (_pinfo *) pchildren[i - 1], events[0]);
1202                 system_printf ("pid %d, dwProcessId %u, hProcess %p, progname '%s'",
1203                                pchildren[i - 1]->pid, pchildren[i - 1]->dwProcessId,
1204                                pchildren[i - 1]->hProcess, pchildren[i - 1]->progname);
1205               }
1206           break;
1207         }
1208
1209       errloop = 0;
1210       rc -= WAIT_OBJECT_0;
1211       if (rc-- != 0)
1212         {
1213           rc = proc_subproc (PROC_CHILDTERMINATED, rc);
1214           if (!proc_loop_wait)          // Don't bother if wait_subproc is
1215             break;                      //  exiting
1216
1217           /* Send a SIGCHLD to myself.   We do this here, rather than in proc_subproc
1218              to avoid the proc_subproc lock since the signal thread will eventually
1219              be calling proc_subproc and could unnecessarily block. */
1220           if (rc)
1221             sig_send (myself_nowait, SIGCHLD);
1222         }
1223       sigproc_printf ("looping");
1224     }
1225
1226   ForceCloseHandle (events[0]);
1227   events[0] = NULL;
1228   sigproc_printf ("done");
1229   ExitThread (0);
1230 }