OSDN Git Service

a9f7c17ac75846d9918c4ad4ba30d8bf57077397
[pf3gnuchains/sourceware.git] / winsup / cygwin / sigproc.cc
1 /* sigproc.cc: inter/intra signal and sub process handler
2
3    Copyright 1997, 1998, 1999, 2000 Cygnus Solutions.
4
5    Written by Christopher Faylor <cgf@cygnus.com>
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 <stdlib.h>
14 #include <time.h>
15 #include <sys/wait.h>
16 #include <errno.h>
17 #include <stdlib.h>
18 #include "winsup.h"
19 #include "sync.h"
20
21 extern BOOL allow_ntsec;
22
23 /*
24  * Convenience defines
25  */
26 #define WSSC               60000 // Wait for signal completion
27 #define WPSP               40000 // Wait for proc_subproc mutex
28 #define WSPX               20000 // Wait for wait_sig to terminate
29 #define WWSP               20000 // Wait for wait_subproc to terminate
30
31 #define WAIT_SIG_PRIORITY               THREAD_PRIORITY_NORMAL
32
33 #define TOTSIGS (NSIG + __SIGOFFSET)
34
35 #define sip_printf(fmt, args...) sigproc_printf (fmt , ## args)
36
37 #define wake_wait_subproc() SetEvent (events[0])
38
39 #define no_signals_available() (!hwait_sig || !sig_loop_wait)
40
41 /*
42  * Global variables
43  */
44 const char *__sp_fn ;
45 int __sp_ln;
46
47 char NO_COPY myself_nowait_dummy[1] = {'0'};// Flag to sig_send that signal goes to
48                                         //  current process but no wait is required
49 char NO_COPY myself_nowait_nonmain_dummy[1] = {'1'};// Flag to sig_send that signal goes to
50                                         //  current process but no wait is required
51                                         //  if this is not the main thread.
52
53 HANDLE NO_COPY signal_arrived;          // Event signaled when a signal has
54                                         //  resulted in a user-specified
55                                         //  function call
56 /*
57  * Common variables
58  */
59
60
61 /* How long to wait for message/signals.  Normally this is infinite.
62  * On termination, however, these are set to zero as a flag to exit.
63  */
64
65 #define Static static NO_COPY
66
67 Static DWORD proc_loop_wait = 500;      // Wait for subprocesses to exit
68 Static DWORD sig_loop_wait = 500;       // Wait for signals to arrive
69
70 Static HANDLE sigcatch_nonmain = NULL;  // The semaphore signaled when
71                                         //  signals are available for
72                                         //  processing from non-main thread
73 Static HANDLE sigcatch_main = NULL;     // Signalled when main thread sends a
74                                         //  signal
75 Static HANDLE sigcatch_nosync = NULL;   // Signal wait_sig to scan sigtodo
76                                         //  but not to bother with any
77                                         //  synchronization
78 Static HANDLE sigcomplete_main = NULL;  // Event signaled when a signal has
79                                         //  finished processing for the main
80                                         //  thread
81 Static HANDLE sigcomplete_nonmain = NULL;// Semaphore raised for non-main
82                                         //  threads when a signal has finished
83                                         //  processing
84 Static HANDLE hwait_sig = NULL;         // Handle of wait_sig thread
85 Static HANDLE hwait_subproc = NULL;     // Handle of sig_subproc thread
86
87 Static HANDLE wait_sig_inited = NULL;   // Control synchronization of
88                                         //  message queue startup
89
90 /* Used by WaitForMultipleObjects.  These are handles to child processes.
91  */
92 Static HANDLE events[PSIZE + 1] = {0};  // All my children's handles++
93 #define hchildren (events + 1)          // Where the children handles begin
94 Static pinfo *pchildren[PSIZE] = {NULL};// All my children info
95 Static pinfo *zombies[PSIZE] = {NULL};  // All my deceased children info
96 Static int nchildren = 0;               // Number of active children
97 Static int nzombies = 0;                // Number of deceased children
98
99 Static waitq waitq_head = {0, 0, 0, 0, 0, 0, 0};// Start of queue for wait'ing threads
100 Static waitq waitq_main;                // Storage for main thread
101
102 muto NO_COPY *sync_proc_subproc = NULL; // Control access to subproc stuff
103
104 DWORD NO_COPY maintid = 0;              // ID of the main thread
105 DWORD NO_COPY sigtid = 0;               // ID of the signal thread
106
107 int NO_COPY pending_signals = 0;        // TRUE if signals pending
108
109 /* Functions
110  */
111 static int __stdcall checkstate (waitq *);
112 static __inline__ BOOL get_proc_lock (DWORD, DWORD);
113 static HANDLE __stdcall getsem (pinfo *, const char *, int, int);
114 static void __stdcall remove_child (int);
115 static void __stdcall remove_zombie (int);
116 static DWORD WINAPI wait_sig (VOID *arg);
117 static int __stdcall stopped_or_terminated (waitq *, pinfo *);
118 static DWORD WINAPI wait_subproc (VOID *);
119
120 /* Determine if the parent process is alive.
121  */
122
123 BOOL __stdcall
124 my_parent_is_alive ()
125 {
126   DWORD res;
127   if (!parent_alive)
128     {
129       debug_printf ("No parent_alive mutex");
130       res = FALSE;
131     }
132   else
133     for (int i = 0; i < 2; i++)
134       switch (res = WaitForSingleObject (parent_alive, 0))
135         {
136           case WAIT_OBJECT_0:
137             debug_printf ("parent dead.");
138             res = FALSE;
139             goto out;
140           case WAIT_TIMEOUT:
141             debug_printf ("parent still alive");
142             res = TRUE;
143             goto out;
144           case WAIT_FAILED:
145             DWORD werr = GetLastError ();
146             if (werr == ERROR_INVALID_HANDLE && i == 0)
147               continue;
148             system_printf ("WFSO for parent_alive(%p) failed, error %d",
149                            parent_alive, werr);
150             res = FALSE;
151             goto out;
152         }
153 out:
154   return res;
155 }
156
157 __inline static void
158 wait_for_me ()
159 {
160   /* See if this is the first signal call after initialization.
161    * If so, wait for notification that all initialization has completed.
162    * Then set the handle to NULL to avoid checking this again.
163    */
164   if (wait_sig_inited)
165     {
166       (void) WaitForSingleObject (wait_sig_inited, INFINITE);
167       (void) ForceCloseHandle (wait_sig_inited);
168       wait_sig_inited = NULL;
169     }
170 }
171
172 static BOOL __stdcall
173 proc_can_be_signalled (pinfo *p)
174 {
175   if (p == myself_nowait || p == myself_nowait_nonmain || p == myself)
176     {
177       wait_for_me ();
178       return 1;
179     }
180
181   return ISSTATE (p, PID_INITIALIZING) ||
182          (((p)->process_state & (PID_ACTIVE | PID_IN_USE)) ==
183           (PID_ACTIVE | PID_IN_USE));
184 }
185
186 /* Test to determine if a process really exists and is processing
187  * signals.
188  */
189 BOOL __stdcall
190 proc_exists (pinfo *p)
191 {
192   HANDLE h;
193
194   if (p == NULL)
195     return FALSE;
196
197   if (p == myself || p == myself_nowait_nonmain || p == myself_nowait)
198     return TRUE;
199
200   if (p->process_state == PID_NOT_IN_USE || !p->dwProcessId)
201     return FALSE;
202
203   sip_printf ("checking for existence of pid %d, window pid %d", p->pid,
204               p->dwProcessId);
205   if (p->ppid == myself->pid && p->hProcess != NULL)
206     {
207       sip_printf ("it's mine, process_state %x", p->process_state);
208       return proc_can_be_signalled (p);
209     }
210
211   /* Note: Process is alive if OpenProcess() call fails due to permissions */
212   if (((h = OpenProcess (STANDARD_RIGHTS_REQUIRED, FALSE, p->dwProcessId))
213       != NULL) || (GetLastError () == ERROR_ACCESS_DENIED))
214     {
215       sip_printf ("it exists, %p", h);
216       if (h)
217         {
218           DWORD rc = WaitForSingleObject (h, 0);
219           CloseHandle (h);
220           if (rc == WAIT_OBJECT_0)
221             return 0;
222         }
223       return proc_can_be_signalled (p);
224     }
225
226   sip_printf ("it doesn't exist");
227   /* If the parent pid does not exist, clean this process out of the pinfo
228    * table.  It must have died abnormally.
229    */
230   if ((p->pid == p->ppid) || (p->ppid == 1) || !proc_exists (procinfo (p->ppid)))
231     {
232       p->hProcess = NULL;
233       p->process_state = PID_NOT_IN_USE;
234     }
235   return FALSE;
236 }
237
238 /* Handle all subprocess requests
239  */
240 #define vchild ((pinfo *) val)
241 int __stdcall
242 proc_subproc (DWORD what, DWORD val)
243 {
244   int rc = 1;
245   int potential_match;
246   DWORD exitcode;
247   pinfo *child;
248   int clearing;
249   waitq *w;
250
251 #define wval     ((waitq *) val)
252
253   sip_printf ("args: %x, %d", what, val);
254
255   if (!get_proc_lock (what, val))       // Serialize access to this function
256     {
257       sip_printf ("I am not ready");
258       goto out1;
259     }
260
261   switch (what)
262     {
263     /* Add a new subprocess to the children arrays.
264      * (usually called from the main thread)
265      */
266     case PROC_ADDCHILD:
267       if (nchildren >= PSIZE - 1)
268         system_printf ("nchildren too large %d", nchildren);
269       if (WaitForSingleObject (vchild->hProcess, 0) != WAIT_TIMEOUT)
270         {
271           system_printf ("invalid process handle %p.  pid %d, win pid %d",
272                         vchild->hProcess, vchild->pid, vchild->dwProcessId);
273           rc = 0;
274           break;
275         }
276
277       pchildren[nchildren] = vchild;
278       hchildren[nchildren] = vchild->hProcess;
279       ProtectHandle (vchild->hProcess);
280       sip_printf ("added pid %d to wait list, slot %d, winpid %p, handle %p",
281                   vchild->pid, nchildren, vchild->dwProcessId,
282                   vchild->hProcess);
283
284       nchildren++;
285       wake_wait_subproc ();
286       break;
287
288     /* A child process had terminated.
289      * Possibly this is just due to an exec().  Cygwin implements an exec()
290      * as a "handoff" from one windows process to another.  If child->hProcess
291      * is different from what is recorded in hchildren, then this is an exec().
292      * Otherwise this is a normal child termination event.
293      * (called from wait_subproc thread)
294      */
295     case PROC_CHILDTERMINATED:
296       rc = 0;
297       child = pchildren[val];
298       if (GetExitCodeProcess (hchildren[val], &exitcode) &&
299           hchildren[val] != child->hProcess)
300         {
301           sip_printf ("pid %d[%d], reparented old hProcess %p, new %p",
302                       child->pid, val, hchildren[val], child->hProcess);
303           ForceCloseHandle1 (hchildren[val], childhProc);
304           hchildren[val] = child->hProcess; /* Filled out by child */
305           ProtectHandle1 (child->hProcess, childhProc);
306           break;                        // This was an exec()
307         }
308
309       sip_printf ("pid %d[%d] terminated, handle %p, nchildren %d, nzombies %d",
310                   child->pid, val, hchildren[val], nchildren, nzombies);
311       remove_child (val);               // Remove from children arrays
312       zombies[nzombies++] = child;      // Add to zombie array
313       child->process_state = PID_ZOMBIE;// Walking dead
314       if (!proc_loop_wait)              // Don't bother if wait_subproc is
315         break;                          //  exiting
316
317       /* Send a SIGCHLD to myself. */
318       rc = sig_send (myself_nowait, SIGCHLD);   // Send a SIGCHLD
319       break;
320
321     /* A child is in the stopped state.  Scan wait() queue to see if anyone
322      * should be notified.  (Called from wait_sig thread)
323      */
324     case PROC_CHILDSTOPPED:
325       child = myself;           // Just to avoid accidental NULL dereference
326       sip_printf ("Received stopped notification");
327       clearing = 0;
328       goto scan_wait;
329
330     /* Clear all waiting threads.  Called from exceptions.cc prior to
331      * the main thread's dispatch to a signal handler function.
332      * (called from wait_sig thread)
333      */
334     case PROC_CLEARWAIT:
335       /* Clear all "wait"ing threads. */
336       if (val)
337         sip_printf ("clear waiting threads");
338       else
339         sip_printf ("looking for processes to reap");
340       clearing = val;
341
342     scan_wait:
343       /* Scan the linked list of wait()ing threads.  If a wait's parameters
344        * match this pid, then activate it.
345        */
346       for (w = &waitq_head; w->next != NULL; w = w->next)
347         {
348           if ((potential_match = checkstate (w)) > 0)
349             sip_printf ("released waiting thread");
350           else if (!clearing && potential_match < 0)
351             sip_printf ("only found non-terminated children");
352           else if (potential_match <= 0)                // nothing matched
353             {
354               sip_printf ("waiting thread found no children");
355               HANDLE oldw = w->next->ev;
356               if (clearing)
357                 w->next->status = -1;           /* flag that a signal was received */
358               else
359                 w->next->ev = NULL;
360               if (!SetEvent (oldw))
361                 system_printf ("couldn't wake up wait event %p, %E", oldw);
362               w->next = w->next->next;
363             }
364           if (w->next == NULL)
365             break;
366         }
367
368       if (!clearing)
369         sip_printf ("finished processing terminated/stopped child");
370       else
371         {
372           waitq_head.next = NULL;
373           sip_printf ("finished clearing");
374         }
375       break;
376
377     /* Handle a wait4() operation.  Allocates an event for the calling
378      * thread which is signaled when the appropriate pid exits or stops.
379      * (usually called from the main thread)
380      */
381     case PROC_WAIT:
382       wval->ev = NULL;          // Don't know event flag yet
383
384       if (wval->pid <= 0)
385         child = NULL;           // Not looking for a specific pid
386       else if ((child = procinfo (wval->pid)) == NULL)
387         goto out;               // invalid pid.  flag no such child
388
389       wval->status = 0;         // Don't know status yet
390
391       /* Put waitq structure at the end of a linked list. */
392       for (w = &waitq_head; w->next != NULL; w = w->next)
393         if (w->next == wval && (w->next = w->next->next) == NULL)
394           break;
395
396       wval->next = NULL;        /* This will be last in the list */
397       sip_printf ("wval->pid %d, wval->options %d", wval->pid, wval->options);
398
399       /* If the first time for this thread, create a new event, otherwise
400        * reset the event.
401        */
402       if ((wval->ev = wval->thread_ev) == NULL)
403         {
404           wval->ev = wval->thread_ev = CreateEvent (&sec_none_nih, TRUE,
405                                                     FALSE, NULL);
406           ProtectHandle (wval->ev);
407         }
408       ResetEvent (wval->ev);
409
410       /* Scan list of children to see if any have died.
411        * If so, the event flag is set so that the wait* ()
412        * process will return immediately.
413        *
414        * If no children were found and the wait option was WNOHANG,
415        * then set the pid to 0 and remove the waitq value from
416        * consideration.
417        */
418       w->next = wval;           /* set at end of wait queue */
419       if ((potential_match = checkstate (w)) <= 0)
420         {
421           if (!potential_match)
422             {
423               w->next = NULL;           // don't want to keep looking
424               wval->ev = NULL;          // flag that there are no children
425               sip_printf ("no appropriate children, %p, %p",
426                           wval->thread_ev, wval->ev);
427             }
428           else if (wval->options & WNOHANG)
429             {
430               w->next = NULL;           // don't want to keep looking
431               wval->pid = 0;            // didn't find a pid
432               if (!SetEvent (wval->ev)) // wake up wait4 () immediately
433                 system_printf ("Couldn't wake up wait event, %E");
434               sip_printf ("WNOHANG and no terminated children, %p, %p",
435                           wval->thread_ev, wval->ev);
436             }
437         }
438       if (w->next != NULL)
439         sip_printf ("wait activated %p, %p", wval->thread_ev, wval->ev);
440       else if (wval->ev != NULL)
441         sip_printf ("wait activated %p.  Reaped zombie.", wval->ev);
442       else
443         sip_printf ("wait not activated %p, %p", wval->thread_ev, wval->ev);
444       break;
445   }
446
447 out:
448   sync_proc_subproc->release ();        // Release the lock
449 out1:
450   sip_printf ("returning %d", rc);
451   return rc;
452 }
453
454 /* Terminate the wait_subproc thread.
455  * Called on process exit.
456  * Also called by spawn_guts to disassociate any subprocesses from this
457  * process.  Subprocesses will then know to clean up after themselves and
458  * will not become zombies.
459  */
460 void __stdcall
461 proc_terminate (void)
462 {
463   sip_printf ("nchildren %d, nzombies %d", nchildren, nzombies);
464   /* Signal processing is assumed to be blocked in this routine. */
465   if (hwait_subproc)
466     {
467       int rc;
468       proc_loop_wait = 0;       // Tell wait_subproc thread to exit
469       wake_wait_subproc ();     // Wake wait_subproc loop
470
471       /* Wait for wait_subproc thread to exit (but not *too* long) */
472       if ((rc = WaitForSingleObject (hwait_subproc, WWSP)) != WAIT_OBJECT_0)
473         if (rc == WAIT_TIMEOUT)
474           system_printf ("WFSO(hwait_subproc) timed out");
475         else
476           system_printf ("WFSO(hwait_subproc), rc %d, %E", rc);
477
478       HANDLE h = hwait_subproc;
479       hwait_subproc = NULL;
480       ForceCloseHandle1 (h, hwait_subproc);
481
482       sync_proc_subproc->acquire(WPSP);
483       (void) proc_subproc (PROC_CLEARWAIT, 1);
484
485       lock_pinfo_for_update (INFINITE);
486       /* Clean out zombie processes from the pid list. */
487       int i;
488       for (i = 0; i < nzombies; i++)
489         {
490           pinfo *child;
491           if ((child = zombies[i])->hProcess)
492             {
493               ForceCloseHandle1 (child->hProcess, childhProc);
494               child->hProcess = NULL;
495             }
496           child->process_state = PID_NOT_IN_USE;
497         }
498
499       /* Disassociate my subprocesses */
500       for (i = 0; i < nchildren; i++)
501         {
502           pinfo *child;
503           if ((child = pchildren[i])->process_state == PID_NOT_IN_USE)
504             continue;           // Should never happen
505           if (!child->hProcess)
506             sip_printf ("%d(%d) hProcess cleared already?", child->pid,
507                         child->dwProcessId);
508           else
509             {
510               ForceCloseHandle1 (child->hProcess, childhProc);
511               child->hProcess = NULL;
512               if (!proc_exists (child))
513                 {
514                   sip_printf ("%d(%d) doesn't exist", child->pid,
515                               child->dwProcessId);
516                   child->process_state = PID_NOT_IN_USE;        /* a reaped child */
517                 }
518               else
519                 {
520                   sip_printf ("%d(%d) closing active child handle", child->pid,
521                               child->dwProcessId);
522                   child->ppid = 1;
523                   if (child->pgid == myself->pid)
524                     child->process_state |= PID_ORPHANED;
525                 }
526             }
527         }
528       unlock_pinfo ();
529       nchildren = nzombies = 0;
530
531       /* Attempt to close and release sync_proc_subproc in a
532        * non-raceable manner.
533        */
534       muto *m = sync_proc_subproc;
535       if (m)
536         {
537           sync_proc_subproc = NULL;
538           delete m;
539         }
540     }
541   sip_printf ("leaving");
542 }
543
544 /* Clear pending signal from the sigtodo array
545  */
546 void __stdcall
547 sig_clear (int sig)
548 {
549   (void) InterlockedExchange (myself->getsigtodo(sig), 0L);
550   return;
551 }
552
553 /* Force the wait_sig thread to wake up and scan the sigtodo array.
554  */
555 extern "C" int __stdcall
556 sig_dispatch_pending (int justwake)
557 {
558   if (!hwait_sig)
559     return 0;
560
561   int was_pending = pending_signals;
562 #ifdef DEBUGGING
563   sip_printf ("pending_signals %d", was_pending);
564 #endif
565   if (!was_pending && !justwake)
566 #ifdef DEBUGGING
567     sip_printf ("no need to wake anything up");
568 #else
569     ;
570 #endif
571   else
572     {
573       wait_for_me ();
574       if (!justwake)
575         (void) sig_send (myself, __SIGFLUSH);
576       else if (ReleaseSemaphore (sigcatch_nosync, 1, NULL))
577 #ifdef DEBUGGING
578         sip_printf ("woke up wait_sig");
579 #else
580         ;
581 #endif
582       else if (no_signals_available ())
583         /*sip_printf ("I'm going away now")*/;
584       else
585         system_printf ("%E releasing sigcatch_nosync(%p)", sigcatch_nosync);
586  
587     }
588   return was_pending;
589 }
590
591 /* Message initialization.  Called from dll_crt0_1
592  *
593  * This routine starts the signal handling thread.  The wait_sig_inited
594  * event is used to signal that the thread is ready to handle signals.
595  * We don't wait for this during initialization but instead detect it
596  * in sig_send to gain a little concurrency.
597  */
598 void __stdcall
599 sigproc_init ()
600 {
601   wait_sig_inited = CreateEvent (&sec_none_nih, FALSE, FALSE, NULL);
602   ProtectHandle (wait_sig_inited);
603
604   /* local event signaled when main thread has been dispatched
605      to a signal handler function. */
606   signal_arrived = CreateEvent(&sec_none_nih, TRUE, FALSE, NULL);
607
608   maintid = GetCurrentThreadId ();// For use in determining if signals
609                                   //  should be blocked.
610
611   if (!(hwait_sig = makethread (wait_sig, NULL, 0, "sig")))
612     {
613       system_printf ("cannot create wait_sig thread, %E");
614       api_fatal ("terminating");
615     }
616
617   ProtectHandle (hwait_sig);
618
619   /* sync_proc_subproc is used by proc_subproc.  It serialises
620    * access to the children and zombie arrays.
621    */
622   sync_proc_subproc = new_muto (FALSE, "sync_proc_subproc");
623
624   /* Initialize waitq structure for main thread.  A waitq structure is
625    * allocated for each thread that executes a wait to allow multiple threads
626    * to perform waits.  Pre-allocate a waitq structure for the main thread.
627    */
628   waitq *w;
629   if ((w = (waitq *)waitq_storage.get ()) == NULL)
630     {
631       w = &waitq_main;
632       waitq_storage.set (w);
633     }
634   memset (w, 0, sizeof *w);     // Just to be safe
635
636   sip_printf ("process/signal handling enabled(%x)", myself->process_state);
637   return;
638 }
639
640 /* Called on process termination to terminate signal and process threads.
641  */
642 void __stdcall
643 sigproc_terminate (void)
644 {
645   HANDLE h = hwait_sig;
646   hwait_sig = NULL;
647
648   if (GetCurrentThreadId () == sigtid)
649     {
650       ForceCloseHandle (sigcomplete_main);
651       for (int i = 0; i < 20; i++)
652         (void) ReleaseSemaphore (sigcomplete_nonmain, 1, NULL);
653       ForceCloseHandle (sigcomplete_nonmain);
654       ForceCloseHandle (sigcatch_main);
655       ForceCloseHandle (sigcatch_nonmain);
656       ForceCloseHandle (sigcatch_nosync);
657     }
658   proc_terminate ();            // Terminate process handling thread
659
660   if (!sig_loop_wait)
661     sip_printf ("sigproc_terminate: sigproc handling not active");
662   else
663     {
664       sigproc_printf ("entering");
665       sig_loop_wait = 0;        // Tell wait_sig to exit when it is
666                                 //  finished with anything it is doing
667       sig_dispatch_pending (TRUE);      // wake up and die
668
669       /* If !hwait_sig, then the process probably hasn't even finished
670        * its initialization phase.
671        */
672       if (hwait_sig)
673         {
674           if (GetCurrentThreadId () != sigtid)
675             WaitForSingleObject (h, 10000);
676           ForceCloseHandle1 (h, hwait_sig);
677
678           /* Exiting thread.  Cleanup.  Don't set to inactive if a child has been
679              execed with the same pid. */
680           if (!myself->dwProcessId || myself->dwProcessId == GetCurrentProcessId ())
681             myself->process_state &= ~PID_ACTIVE;
682           else
683             sip_printf ("Did not clear PID_ACTIVE since %d != %d",
684                         myself->dwProcessId, GetCurrentProcessId ());
685
686           /* In case of a sigsuspend */
687           SetEvent (signal_arrived);
688
689           if (GetCurrentThreadId () != sigtid)
690             {
691               ForceCloseHandle (sigcomplete_main);
692               ForceCloseHandle (sigcomplete_nonmain);
693               ForceCloseHandle (sigcatch_main);
694               ForceCloseHandle (sigcatch_nonmain);
695               ForceCloseHandle (sigcatch_nosync);
696             }
697         }
698       sip_printf ("done");
699     }
700
701   /* Set this so that subsequent tests will succeed. */
702   if (!myself->dwProcessId)
703     myself->dwProcessId = GetCurrentProcessId ();
704
705   return;
706 }
707
708 /* Send a signal to another process by raising its signal semaphore.
709  * If pinfo *p == NULL, send to the current process.
710  * If sending to this process, wait for notification that a signal has
711  * completed before returning.
712  */
713 int __stdcall
714 sig_send (pinfo *p, int sig, DWORD ebp)
715 {
716   int rc = 1;
717   DWORD tid = GetCurrentThreadId ();
718   BOOL its_me;
719   HANDLE thiscatch = NULL;
720   HANDLE thiscomplete = NULL;
721   BOOL wait_for_completion;
722   extern signal_dispatch sigsave;
723
724   if (p == myself_nowait_nonmain)
725     p = (tid == maintid) ? myself : myself_nowait;
726   if (!(its_me = (p == NULL || p == myself || p == myself_nowait)))
727     wait_for_completion = FALSE;
728   else
729     {
730       if (no_signals_available ())
731         goto out;               // Either exiting or not yet initializing
732       wait_for_me ();
733       wait_for_completion = p != myself_nowait;
734       p = myself;
735     }
736
737   /* It is possible that the process is not yet ready to receive messages
738    * or that it has exited.  Detect this.
739    */
740   if (!proc_can_be_signalled (p))       /* Is the process accepting messages? */
741     {
742       sip_printf ("invalid pid %d(%x), signal %d",
743                   p->pid, p->process_state, sig);
744       set_errno (ESRCH);
745       goto out;
746     }
747
748   sip_printf ("pid %d, signal %d, its_me %d", p->pid, sig, its_me);
749
750   if (its_me)
751     {
752       if (!wait_for_completion)
753         thiscatch = sigcatch_nosync;
754       else if (tid != maintid)
755         {
756           thiscatch = sigcatch_nonmain;
757           thiscomplete = sigcomplete_nonmain;
758         }
759       else
760         {
761           thiscatch = sigcatch_main;
762           thiscomplete = sigcomplete_main;
763           sigsave.ebp = ebp ?: (DWORD) __builtin_frame_address (1);
764         }
765     }
766   else if (!(thiscatch = getsem (p, "sigcatch", 0, 0)))
767     goto out;             // Couldn't get the semaphore.  getsem issued
768                           //  an error, if appropriate.
769
770 #if WHEN_MULTI_THREAD_SIGNALS_WORK
771   signal_dispatch *sd;
772   sd = signal_dispatch_storage.get ();
773   if (sd == NULL)
774     sd = signal_dispatch_storage.create ();
775 #endif
776
777   /* Increment the sigtodo array to signify which signal to assert.
778    */
779   (void) InterlockedIncrement (p->getsigtodo(sig));
780
781   /* Notify the process that a signal has arrived.
782    */
783   SetLastError (0);
784
785 #if 0
786   int prio;
787   prio = GetThreadPriority (GetCurrentThread ());
788   (void) SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_TIME_CRITICAL);
789 #endif
790
791   if (!ReleaseSemaphore (thiscatch, 1, NULL) && (int) GetLastError () > 0)
792     {
793 sigproc_printf ("ReleaseSemaphore failed, %E");
794       /* Couldn't signal the semaphore.  This probably means that the
795        * process is exiting.
796        */
797       if (!its_me)
798         ForceCloseHandle (thiscatch);
799       else
800         {
801           if (no_signals_available ())
802             sip_printf ("I'm going away now");
803           else if ((int) GetLastError () == -1)
804             rc = WaitForSingleObject (thiscomplete, 500);
805           else
806             system_printf ("error sending signal %d to pid %d, semaphore %p, %E",
807                           sig, p->pid, thiscatch);
808         }
809       goto out;
810     }
811 sigproc_printf ("ReleaseSemaphore succeeded");
812
813   /* No need to wait for signal completion unless this was a signal to
814    * this process.
815    *
816    * If it was a signal to this process, wait for a dispatched signal.
817    * Otherwise just wait for the wait_sig to signal that it has finished
818    * processing the signal.
819    */
820   if (!wait_for_completion)
821     {
822       rc = WAIT_OBJECT_0;
823       sip_printf ("Not waiting for sigcomplete.  its_me %d sig %d", its_me, sig);
824       if (!its_me)
825         ForceCloseHandle (thiscatch);
826     }
827   else
828     {
829       sip_printf ("Waiting for thiscomplete %p", thiscomplete);
830
831       SetLastError (0);
832       rc = WaitForSingleObject (thiscomplete, WSSC);
833       /* Check for strangeness due to this thread being redirected by the
834          signal handler.  Sometimes a WAIT_TIMEOUT will occur when the
835          thread hasn't really timed out.  So, check again.
836          FIXME: This isn't foolproof. */
837       if (rc != WAIT_OBJECT_0 &&
838           WaitForSingleObject (thiscomplete, 0) == WAIT_OBJECT_0)
839         rc = WAIT_OBJECT_0;
840     }
841
842 #if 0
843   SetThreadPriority (GetCurrentThread (), prio);
844 #endif
845
846   if (rc == WAIT_OBJECT_0)
847     rc = 0;             // Successful exit
848   else
849     {
850       /* It's an error unless sig_loop_wait == 0 (the process is exiting). */
851       if (!no_signals_available ())
852         system_printf ("wait for sig_complete event failed, sig %d, rc %d, %E",
853                       sig, rc);
854       set_errno (ENOSYS);
855       rc = -1;
856     }
857
858 out:
859   sip_printf ("returning %d from sending signal %d", rc, sig);
860   return rc;
861 }
862
863 /* Set pending signal from the sigtodo array
864  */
865 void __stdcall
866 sig_set_pending (int sig)
867 {
868   (void) InterlockedIncrement (myself->getsigtodo(sig));
869   return;
870 }
871
872 /* Initialize the wait_subproc thread.
873  * Called from fork() or spawn() to initialize the handling of subprocesses.
874  */
875 void __stdcall
876 subproc_init (void)
877 {
878   if (hwait_subproc)
879     return;
880
881   /* A "wakeup" handle which can be toggled to make wait_subproc reexamine
882    * the hchildren array.
883    */
884   events[0] = CreateEvent (&sec_none_nih, FALSE, FALSE, NULL);
885   if (!(hwait_subproc = makethread (wait_subproc, NULL, 0, "+proc")))
886     system_printf ("cannot create wait_subproc thread, %E");
887   ProtectHandle (events[0]);
888   ProtectHandle (hwait_subproc);
889   sip_printf ("started wait_subproc thread %p", hwait_subproc);
890 }
891
892 /* Initialize some of the memory block passed to child processes
893    by fork/spawn/exec. */
894
895 void __stdcall
896 init_child_info (DWORD chtype, child_info *ch, int pid, HANDLE subproc_ready)
897 {
898   subproc_init ();
899   memset (ch, 0, sizeof *ch);
900   ch->cb = sizeof *ch;
901   ch->type = chtype;
902   ch->cygpid = pid;
903   ch->shared_h = cygwin_shared_h;
904   ch->console_h = console_shared_h;
905   ch->subproc_ready = subproc_ready;
906   if (chtype != PROC_EXEC || !parent_alive)
907     ch->parent_alive = hwait_subproc;
908   else if (parent_alive)
909     DuplicateHandle (hMainProc, parent_alive, hMainProc, &ch->parent_alive,
910                      0, 1, DUPLICATE_SAME_ACCESS);
911 }
912
913 /* Check the state of all of our children to see if any are stopped or
914  * terminated.
915  */
916 static int __stdcall
917 checkstate (waitq *w)
918 {
919   int i, x, potential_match = 0;
920   pinfo *child;
921
922   sip_printf ("nchildren %d, nzombies %d", nchildren, nzombies);
923
924   /* Check already dead processes first to see if they match the criteria
925    * given in w->next.
926    */
927   for (i = 0; i < nzombies; i++)
928     if ((x = stopped_or_terminated (w, child = zombies[i])) < 0)
929       potential_match = -1;
930     else if (x > 0)
931       {
932         remove_zombie (i);
933         potential_match = 1;
934         goto out;
935       }
936
937   sip_printf ("checking alive children");
938
939   /* No dead terminated children matched.  Check for stopped children. */
940   for (i = 0; i < nchildren; i++)
941     if ((x = stopped_or_terminated (w, pchildren[i])) < 0)
942       potential_match = -1;
943     else if (x > 0)
944       {
945         potential_match = 1;
946         break;
947       }
948
949 out:
950   sip_printf ("returning %d", potential_match);
951   return potential_match;
952 }
953
954 /* Get or create a process specific semaphore used in message passing.
955  */
956 static HANDLE __stdcall
957 getsem (pinfo *p, const char *str, int init, int max)
958 {
959   HANDLE h;
960
961   if (p != NULL)
962     {
963       if (!proc_can_be_signalled (p))
964         {
965           set_errno (ESRCH);
966           return NULL;
967         }
968       int wait = 10000;
969       sip_printf ("pid %d, ppid %d, wait %d, initializing %x", p->pid, p->ppid, wait,
970                   ISSTATE (p, PID_INITIALIZING));
971       for (int i = 0; ISSTATE (p, PID_INITIALIZING) && i < wait; i++)
972         Sleep (1);
973     }
974
975   SetLastError (0);
976   if (p == NULL)
977     {
978       char sa_buf[1024];
979
980       DWORD winpid = GetCurrentProcessId ();
981       h = CreateSemaphore (allow_ntsec ? sec_user (sa_buf) : &sec_none_nih,
982                            init, max, str = shared_name (str, winpid));
983       p = myself;
984     }
985   else
986     {
987       h = OpenSemaphore (SEMAPHORE_ALL_ACCESS, FALSE,
988                          str = shared_name (str, p->dwProcessId));
989
990       if (h == NULL)
991         {
992           if (GetLastError () == ERROR_FILE_NOT_FOUND && !proc_exists (p))
993             set_errno (ESRCH);
994           else
995             set_errno (EPERM);
996           return NULL;
997         }
998     }
999
1000   if (!h)
1001     {
1002       system_printf ("can't %s %s, %E", p ? "open" : "create", str);
1003       set_errno (ESRCH);
1004     }
1005   return h;
1006 }
1007
1008 /* Get the sync_proc_subproc muto to control access to
1009  * children, zombie arrays.
1010  * Attempt to handle case where process is exiting as we try to grab
1011  * the mutex.
1012  */
1013 static __inline__ BOOL
1014 get_proc_lock (DWORD what, DWORD val)
1015 {
1016   Static int lastwhat = -1;
1017   if (!sync_proc_subproc)
1018     return FALSE;
1019   if (sync_proc_subproc->acquire (WPSP))
1020     {
1021       lastwhat = what;
1022       return TRUE;
1023     }
1024   if (!sync_proc_subproc)
1025     return FALSE;
1026   system_printf ("Couldn't aquire sync_proc_subproc for(%d,%d), %E, last %d",
1027                   what, val, lastwhat);
1028   return TRUE;
1029 }
1030
1031 /* Remove a child from pchildren/hchildren by swapping it with the
1032  * last child in the list.
1033  */
1034 static void __stdcall
1035 remove_child (int ci)
1036 {
1037   sip_printf ("removing [%d], pid %d, handle %p, nchildren %d",
1038               ci, pchildren[ci]->pid, hchildren[ci], nchildren);
1039   if (ci < --nchildren)
1040     {
1041       pchildren[ci] = pchildren[nchildren];
1042       hchildren[ci] = hchildren[nchildren];
1043     }
1044
1045   return;
1046 }
1047
1048 /* Remove a zombie from zombies by swapping it with the last child in the list.
1049  */
1050 static void __stdcall
1051 remove_zombie (int ci)
1052 {
1053   sip_printf ("removing %d, pid %d, nzombies %d", ci, zombies[ci]->pid,
1054               nzombies);
1055   if (ci < --nzombies)
1056     zombies[ci] = zombies[nzombies];
1057
1058   return;
1059 }
1060
1061 /* Check status of child process vs. waitq member.
1062  *
1063  * parent_w is the pointer to the parent of the waitq member in question.
1064  * child is the subprocess being considered.
1065  *
1066  * Returns
1067  *   1 if stopped or terminated child matches parent_w->next criteria
1068  *  -1 if a non-stopped/terminated child matches parent_w->next criteria
1069  *   0 if child does not match parent_w->next criteria
1070  */
1071 static int __stdcall
1072 stopped_or_terminated (waitq *parent_w, pinfo *child)
1073 {
1074   int potential_match;
1075   waitq *w = parent_w->next;
1076
1077   sip_printf ("considering pid %d", child->pid);
1078   if (w->pid == -1)
1079     potential_match = 1;
1080   else if (w->pid == 0)
1081     potential_match = child->pgid == myself->pgid;
1082   else if (w->pid < 0)
1083     potential_match = child->pgid == -w->pid;
1084   else
1085     potential_match = (w->pid == child->pid);
1086
1087   if (!potential_match)
1088     return 0;
1089
1090   BOOL terminated;
1091
1092   if ((terminated = child->process_state == PID_ZOMBIE) ||
1093       (w->options & WUNTRACED) && child->stopsig)
1094     {
1095       parent_w->next = w->next; /* successful wait.  remove from wait queue */
1096       w->pid = child->pid;
1097
1098       if (!terminated)
1099         {
1100           sip_printf ("stopped child");
1101           w->status = (child->stopsig << 8) | 0x7f;
1102           child->stopsig = 0;
1103         }
1104       else
1105         {
1106           DWORD status;
1107           if (!GetExitCodeProcess (child->hProcess, &status))
1108             status = 0xffff;
1109           if (status & EXIT_SIGNAL)
1110             w->status = (status >> 8) & 0xff;   /* exited due to signal */
1111           else
1112             w->status = (status & 0xff) << 8;   /* exited via "exit ()" */
1113
1114           add_rusage (&myself->rusage_children, &child->rusage_children);
1115           add_rusage (&myself->rusage_children, &child->rusage_self);
1116
1117           if (w->rusage)
1118             {
1119               add_rusage ((struct rusage *) w->rusage, &child->rusage_children);
1120               add_rusage ((struct rusage *) w->rusage, &child->rusage_self);
1121             }
1122           ForceCloseHandle1 (child->hProcess, childhProc);
1123           child->hProcess = NULL;
1124           child->process_state = PID_NOT_IN_USE;        /* a reaped child */
1125         }
1126
1127       if (!SetEvent (w->ev))    /* wake up wait4 () immediately */
1128         system_printf ("couldn't wake up wait event %p, %E", w->ev);
1129       return 1;
1130     }
1131
1132   return -potential_match;
1133 }
1134
1135 /* Process signals by waiting for a semaphore to become signaled.
1136  * Then scan an in-memory array representing queued signals.
1137  * Executes in a separate thread.
1138  *
1139  * Signals sent from this process are sent a completion signal so
1140  * that returns from kill/raise do not occur until the signal has
1141  * has been handled, as per POSIX.
1142  */
1143 static DWORD WINAPI
1144 wait_sig (VOID *)
1145 {
1146   /* Initialization */
1147   (void) SetThreadPriority (hwait_sig, WAIT_SIG_PRIORITY);
1148
1149   /* sigcatch_nosync       - semaphore incremented by sig_dispatch_pending and
1150    *                         by foreign processes to force an examination of
1151    *                         the sigtodo array.
1152    * sigcatch_main         - ditto for local main thread.
1153    * sigcatch_nonmain      - ditto for local non-main threads.
1154    *
1155    * sigcomplete_main      - event used to signal main thread on signal
1156    *                         completion
1157    * sigcomplete_nonmain   - semaphore signaled for non-main thread on signal
1158    *                         completion
1159    */
1160   sigcatch_nosync = getsem (NULL, "sigcatch", 0, MAXLONG);
1161   sigcatch_nonmain = CreateSemaphore (&sec_none_nih, 0, MAXLONG, NULL);
1162   sigcatch_main = CreateSemaphore (&sec_none_nih, 0, MAXLONG, NULL);
1163   sigcomplete_nonmain = CreateSemaphore (&sec_none_nih, 0, MAXLONG, NULL);
1164   sigcomplete_main = CreateEvent (&sec_none_nih, FALSE, FALSE, NULL);
1165   sigproc_printf ("sigcatch_nonmain %p", sigcatch_nonmain);
1166
1167   /* Setting dwProcessId flags that this process is now capable of receiving
1168    * signals.  Prior to this, dwProcessId was set to the windows pid of
1169    * of the original windows process which spawned us unless this was a
1170    * "toplevel" process.
1171    */
1172   myself->dwProcessId = GetCurrentProcessId ();
1173   myself->process_state |= PID_ACTIVE;
1174   myself->process_state &= ~PID_INITIALIZING;
1175
1176   ProtectHandle (sigcatch_nosync);
1177   ProtectHandle (sigcatch_nonmain);
1178   ProtectHandle (sigcatch_main);
1179   ProtectHandle (sigcomplete_nonmain);
1180   ProtectHandle (sigcomplete_main);
1181
1182   /* If we've been execed, then there is still a stub left in the previous
1183    * windows process waiting to see if it's started a cygwin process or not.
1184    * Signalling subproc_ready indicates that we are a cygwin process.
1185    */
1186   if (child_proc_info && child_proc_info->type == PROC_EXEC)
1187     {
1188       debug_printf ("subproc_ready %p", child_proc_info->subproc_ready);
1189       if (!SetEvent (child_proc_info->subproc_ready))
1190         system_printf ("SetEvent (subproc_ready) failed, %E");
1191       ForceCloseHandle (child_proc_info->subproc_ready);
1192     }
1193
1194   SetEvent (wait_sig_inited);
1195   sigtid = GetCurrentThreadId ();
1196
1197   /* If we got something like a SIGINT while we were initializing, the
1198      signal thread should be waiting for this event.  This signals the
1199      thread that it's ok to send the signal since the wait_sig thread
1200      is now active. */
1201   extern HANDLE console_handler_thread_waiter;
1202   SetEvent (console_handler_thread_waiter);
1203
1204   HANDLE catchem[] = {sigcatch_main, sigcatch_nonmain, sigcatch_nosync};
1205   sigproc_printf ("Ready.  dwProcessid %d", myself->dwProcessId);
1206   for (;;)
1207     {
1208       DWORD rc = WaitForMultipleObjects (3, catchem, FALSE, sig_loop_wait);
1209
1210       /* sigproc_terminate sets sig_loop_wait to zero to indicate that
1211        * this thread should terminate.
1212        */
1213       if (rc == WAIT_TIMEOUT)
1214         if (!sig_loop_wait)
1215           break;                        // Exiting
1216         else
1217           continue;
1218
1219       if (rc == WAIT_FAILED)
1220         {
1221           if (sig_loop_wait != 0)
1222             system_printf ("WFMO failed, %E");
1223           break;
1224         }
1225
1226       rc -= WAIT_OBJECT_0;
1227       int dispatched = FALSE;
1228       sip_printf ("awake");
1229       /* A sigcatch semaphore has been signaled.  Scan the sigtodo
1230        * array looking for any unprocessed signals.
1231        */
1232       pending_signals = 0;
1233       int saw_sigchld = 0;
1234       int dispatched_sigchld = 0;
1235       for (int sig = -__SIGOFFSET; sig < NSIG; sig++)
1236         {
1237           while (InterlockedDecrement (myself->getsigtodo(sig)) >= 0)
1238             {
1239               if (sig == SIGCHLD)
1240                 saw_sigchld = 1;
1241               if (sig > 0 && sig != SIGCONT && sig != SIGKILL && sig != SIGSTOP &&
1242                   (sigismember (& myself->getsigmask (), sig) ||
1243                    myself->process_state & PID_STOPPED))
1244                 {
1245                   sip_printf ("sig %d blocked", sig);
1246                   break;
1247                 }
1248
1249               /* Found a signal to process */
1250               sip_printf ("processing signal %d", sig);
1251               switch (sig)
1252                 {
1253                 case __SIGFLUSH:
1254                   /* just forcing the loop */
1255                   break;
1256
1257                 /* Internal signal to force a flush of strace data to disk. */
1258                 case __SIGSTRACE:
1259                   // proc_strace ();    // Dump cached strace.prntf stuff.
1260                   break;
1261
1262                 /* Signalled from a child process that it has stopped */
1263                 case __SIGCHILDSTOPPED:
1264                   sip_printf ("Received child stopped notification");
1265                   dispatched |= sig_handle (SIGCHLD, rc);
1266                   if (proc_subproc (PROC_CHILDSTOPPED, 0))
1267                     dispatched |= 1;
1268                   break;
1269
1270                 /* A normal UNIX signal */
1271                 default:
1272                   sip_printf ("Got signal %d", sig);
1273                   int wasdispatched = sig_handle (sig, rc);
1274                   dispatched |= wasdispatched;
1275                   if (sig == SIGCHLD && wasdispatched)
1276                     dispatched_sigchld = 1;
1277                   goto nextsig;
1278                 }
1279             }
1280           /* Decremented too far. */
1281           if (InterlockedIncrement (myself->getsigtodo(sig)) > 0)
1282             pending_signals = 1;
1283         nextsig:
1284           continue;
1285         }
1286
1287       if (saw_sigchld && !dispatched_sigchld)
1288         proc_subproc (PROC_CLEARWAIT, 0);
1289       /* Signal completion of signal handling depending on which semaphore
1290        * woke up the WaitForMultipleObjects above.
1291        */
1292       switch (rc)
1293         {
1294         case 0:
1295           SetEvent (sigcomplete_main);
1296 sigproc_printf ("signalled sigcomplete_main %p", sigcomplete_main);
1297           break;
1298         case 1:
1299           ReleaseSemaphore (sigcomplete_nonmain, 1, NULL);
1300 sigproc_printf ("signalled sigcomplete_nonmain %p", sigcomplete_nonmain);
1301           break;
1302         default:
1303 sigproc_printf ("Did not signal anyone");
1304           /* Signal from another process.  No need to synchronize. */
1305           break;
1306         }
1307
1308       if (dispatched < 0)
1309         pending_signals = 1;
1310       sip_printf ("looping");
1311     }
1312
1313   sip_printf ("done");
1314   return 0;
1315 }
1316
1317 /* Wait for subprocesses to terminate. Executes in a separate thread. */
1318 static DWORD WINAPI
1319 wait_subproc (VOID *)
1320 {
1321   sip_printf ("starting");
1322   int errloop = 0;
1323
1324   for (;;)
1325     {
1326       DWORD rc = WaitForMultipleObjects (nchildren + 1, events, FALSE,
1327                                          proc_loop_wait);
1328       if (rc == WAIT_TIMEOUT)
1329         if (!proc_loop_wait)
1330           break;                        // Exiting
1331         else
1332           continue;
1333
1334       if (rc == WAIT_FAILED)
1335         {
1336           if (!proc_loop_wait)
1337             break;
1338
1339           /* It's ok to get an ERROR_INVALID_HANDLE since another thread may have
1340              closed a handle in the children[] array.  So, we try looping a couple
1341              of times to stabilize. FIXME - this is not foolproof.  Probably, this
1342              thread should be responsible for closing the children. */
1343           if (++errloop < 10 && GetLastError () == ERROR_INVALID_HANDLE)
1344             continue;
1345
1346           system_printf ("wait failed. nchildren %d, wait %d, %E",
1347                         nchildren, proc_loop_wait);
1348
1349           for (int i = 0; i < nchildren + 1; i++)
1350             if ((rc = WaitForSingleObject (events[i], 0)) == WAIT_OBJECT_0 ||
1351                 rc == WAIT_TIMEOUT)
1352               continue;
1353             else
1354               system_printf ("event[%d] %p, %E", i, events[0]);
1355           break;
1356         }
1357
1358       errloop = 0;
1359       rc -= WAIT_OBJECT_0;
1360       if (rc-- != 0)
1361         (void)proc_subproc (PROC_CHILDTERMINATED, rc);
1362       sip_printf ("looping");
1363     }
1364
1365   ForceCloseHandle (events[0]);
1366   events[0] = NULL;
1367   sip_printf ("done");
1368   return 0;
1369 }