-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathsigproc.cc
1498 lines (1363 loc) · 39.4 KB
/
sigproc.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* sigproc.cc: inter/intra signal and sub process handler
This file is part of Cygwin.
This software is a copyrighted work licensed under the terms of the
Cygwin license. Please consult the file "CYGWIN_LICENSE" for
details. */
#include "winsup.h"
#include "miscfuncs.h"
#include <stdlib.h>
#include <sys/cygwin.h>
#include "cygerrno.h"
#include "sigproc.h"
#include "path.h"
#include "fhandler.h"
#include "dtable.h"
#include "cygheap.h"
#include "child_info_magic.h"
#include "shared_info.h"
#include "cygtls.h"
#include "ntdll.h"
#include "exception.h"
/*
* Convenience defines
*/
#define WSSC 60000 // Wait for signal completion
#define WPSP 40000 // Wait for proc_subproc mutex
/*
* Global variables
*/
struct sigaction *global_sigs;
const char *__sp_fn ;
int __sp_ln;
bool no_thread_exit_protect::flag;
/* Flag to sig_send that signal goes to current process but no wait is
required. */
char NO_COPY myself_nowait_dummy[1] = {'0'};
/* All my children info. Avoid expensive constructor ops at DLL
startup.
This class can allocate memory. But there's no need to free it
because only one instance of the class is created per process. */
class child_procs {
static const int _NPROCS = 1024;
static const int _NPROCS_2 = 4095;
int _count;
uint8_t _procs[_NPROCS * sizeof (pinfo)] __attribute__ ((__aligned__));
pinfo *_procs_2;
public:
int count () const { return _count; }
int add_one () { return ++_count; }
int del_one () { return --_count; }
int reset () { return _count = 0; }
pinfo &operator[] (int idx)
{
if (idx >= _NPROCS)
{
if (!_procs_2)
{
/* Use HeapAlloc to avoid propagating this memory area
to the child processes. */
_procs_2 = (pinfo *) HeapAlloc (GetProcessHeap (),
HEAP_GENERATE_EXCEPTIONS
| HEAP_ZERO_MEMORY,
(_NPROCS_2 + 1) * sizeof (pinfo));
}
return _procs_2[idx - _NPROCS];
}
return ((pinfo *) _procs)[idx];
}
int max_child_procs () const { return _NPROCS + _NPROCS_2; }
};
static NO_COPY child_procs chld_procs;
/* Start of queue for waiting threads. */
static NO_COPY waitq waitq_head;
/* Controls access to subproc stuff. */
static NO_COPY muto sync_proc_subproc;
_cygtls NO_COPY *_sig_tls;
static NO_COPY HANDLE my_sendsig;
static NO_COPY HANDLE my_readsig;
/* Used in select if a signalfd is part of the read descriptor set */
HANDLE NO_COPY my_pendingsigs_evt;
/* Function declarations */
static int checkstate (waitq *);
static __inline__ bool get_proc_lock (DWORD, DWORD);
static int remove_proc (int);
static bool stopped_or_terminated (waitq *, _pinfo *);
static void wait_sig (VOID *arg);
/* wait_sig bookkeeping */
class pending_signals
{
sigpacket sigs[_NSIG + 1];
sigpacket start;
bool retry;
public:
void add (sigpacket&);
bool pending () {retry = true; return !!start.next;}
void clear (int sig) {sigs[sig].si.si_signo = 0;}
void clear (_cygtls *tls);
friend void sig_dispatch_pending (bool);
friend void wait_sig (VOID *arg);
};
static NO_COPY pending_signals sigq;
/* Functions */
void
sigalloc ()
{
cygheap->sigs = global_sigs =
(struct sigaction *) ccalloc_abort (HEAP_SIGS, _NSIG, sizeof (struct sigaction));
global_sigs[SIGSTOP].sa_flags = SA_RESTART | SA_NODEFER;
}
void
signal_fixup_after_exec ()
{
global_sigs = cygheap->sigs;
/* Set up child's signal handlers */
for (int i = 0; i < _NSIG; i++)
{
global_sigs[i].sa_mask = 0;
if (global_sigs[i].sa_handler != SIG_IGN)
{
global_sigs[i].sa_handler = SIG_DFL;
global_sigs[i].sa_flags &= ~ SA_SIGINFO;
}
}
}
/* Get the sync_proc_subproc muto to control access to
* children, proc arrays.
* Attempt to handle case where process is exiting as we try to grab
* the mutex.
*/
static bool
get_proc_lock (DWORD what, DWORD val)
{
if (!cygwin_finished_initializing)
return true;
static NO_COPY int lastwhat = -1;
if (!sync_proc_subproc)
{
sigproc_printf ("sync_proc_subproc is NULL");
return false;
}
if (sync_proc_subproc.acquire (WPSP))
{
lastwhat = what;
return true;
}
system_printf ("Couldn't acquire %s for(%d,%d), last %d, %E",
sync_proc_subproc.name, what, val, lastwhat);
return false;
}
static bool
proc_can_be_signalled (_pinfo *p)
{
if (!(p->exitcode & EXITCODE_SET))
{
if (ISSTATE (p, PID_INITIALIZING) ||
(((p)->process_state & (PID_ACTIVE | PID_IN_USE)) ==
(PID_ACTIVE | PID_IN_USE)))
return true;
}
set_errno (ESRCH);
return false;
}
bool
pid_exists (pid_t pid)
{
pinfo p (pid);
return p && p->exists ();
}
/* Return true if this is one of our children, false otherwise. */
static inline bool
mychild (int pid)
{
for (int i = 0; i < chld_procs.count (); i++)
if (chld_procs[i]->pid == pid)
return true;
return false;
}
/* Handle all subprocess requests
*/
int
proc_subproc (DWORD what, uintptr_t val)
{
int slot;
int rc = 1;
int potential_match;
int clearing;
waitq *w;
#define wval ((waitq *) val)
#define vchild (*((pinfo *) val))
sigproc_printf ("args: %x, %d", what, val);
if (!get_proc_lock (what, val)) // Serialize access to this function
{
system_printf ("couldn't get proc lock. what %d, val %d", what, val);
goto out1;
}
switch (what)
{
/* Add a new subprocess to the children arrays.
* (usually called from the main thread)
*/
case PROC_ADD_CHILD:
/* Filled up process table? */
if (chld_procs.count () >= chld_procs.max_child_procs ())
{
sigproc_printf ("proc table overflow: hit %d processes, pid %d\n",
chld_procs.count (), vchild->pid);
rc = 0;
set_errno (EAGAIN);
break;
}
if (vchild != myself)
{
vchild->uid = myself->uid;
vchild->gid = myself->gid;
vchild->pgid = myself->pgid;
vchild->sid = myself->sid;
vchild->ctty = myself->ctty;
vchild->cygstarted = true;
vchild->process_state |= PID_INITIALIZING;
vchild->ppid = myself->pid; /* always set last */
}
break;
case PROC_ATTACH_CHILD:
slot = chld_procs.count ();
chld_procs[slot] = vchild;
rc = chld_procs[slot].wait ();
if (rc)
{
sigproc_printf ("added pid %d to proc table, slot %d", vchild->pid,
slot);
chld_procs.add_one ();
}
break;
/* Handle a wait4() operation. Allocates an event for the calling
* thread which is signaled when the appropriate pid exits or stops.
* (usually called from the main thread)
*/
case PROC_WAIT:
wval->ev = NULL; // Don't know event flag yet
if (wval->pid != -1 && wval->pid && !mychild (wval->pid))
goto out; // invalid pid. flag no such child
wval->status = 0; // Don't know status yet
sigproc_printf ("wval->pid %d, wval->options %d", wval->pid, wval->options);
/* If the first time for this thread, create a new event, otherwise
* reset the event.
*/
if ((wval->ev = wval->thread_ev) == NULL)
{
wval->ev = wval->thread_ev = CreateEvent (&sec_none_nih, TRUE, FALSE,
NULL);
ProtectHandle1 (wval->ev, wq_ev);
}
ResetEvent (wval->ev);
w = waitq_head.next;
waitq_head.next = wval; /* Add at the beginning. */
wval->next = w; /* Link in rest of the list. */
clearing = false;
goto scan_wait;
case PROC_EXEC_CLEANUP:
/* Cleanup backwards to eliminate redundant copying of chld_procs
array members inside remove_proc. */
while (chld_procs.count ())
remove_proc (chld_procs.count () - 1);
for (w = &waitq_head; w->next != NULL; w = w->next)
CloseHandle (w->next->ev);
break;
/* Clear all waiting threads. Called from exceptions.cc prior to
the main thread's dispatch to a signal handler function.
(called from wait_sig thread) */
case PROC_CLEARWAIT:
/* Clear all "wait"ing threads. */
if (val)
sigproc_printf ("clear waiting threads");
else
sigproc_printf ("looking for processes to reap, count %d",
chld_procs.count ());
clearing = val;
scan_wait:
/* Scan the linked list of wait()ing threads. If a wait's parameters
match this pid, then activate it. */
for (w = &waitq_head; w->next != NULL; w = w->next)
{
if ((potential_match = checkstate (w)) > 0)
sigproc_printf ("released waiting thread");
else if (!clearing && !(w->next->options & WNOHANG) && potential_match < 0)
sigproc_printf ("only found non-terminated children");
else if (potential_match <= 0) // nothing matched
{
sigproc_printf ("waiting thread found no children");
HANDLE oldw = w->next->ev;
w->next->pid = 0;
if (clearing)
w->next->status = -1; /* flag that a signal was received */
else if (!potential_match || !(w->next->options & WNOHANG))
w->next->ev = NULL;
if (!SetEvent (oldw))
system_printf ("couldn't wake up wait event %p, %E", oldw);
w->next = w->next->next;
}
if (w->next == NULL)
break;
}
if (!clearing)
sigproc_printf ("finished processing terminated/stopped child");
else
{
waitq_head.next = NULL;
sigproc_printf ("finished clearing");
}
if (global_sigs[SIGCHLD].sa_handler == (void *) SIG_IGN)
for (int i = 0; i < chld_procs.count (); i += remove_proc (i))
continue;
}
out:
sync_proc_subproc.release (); // Release the lock
out1:
sigproc_printf ("returning %d", rc);
return rc;
#undef wval
#undef vchild
}
// FIXME: This is inelegant
void
_cygtls::remove_wq (DWORD wait)
{
if (wq.thread_ev)
{
if (exit_state < ES_FINAL && waitq_head.next && sync_proc_subproc
&& sync_proc_subproc.acquire (wait))
{
ForceCloseHandle1 (wq.thread_ev, wq_ev);
wq.thread_ev = NULL;
for (waitq *w = &waitq_head; w->next != NULL; w = w->next)
if (w->next == &wq)
{
w->next = wq.next;
break;
}
sync_proc_subproc.release ();
}
}
}
/* Terminate the wait_subproc thread.
Called on process exit.
Also called by spawn_guts to disassociate any subprocesses from this
process. Subprocesses will then know to clean up after themselves and
will not become chld_procs. */
void
proc_terminate ()
{
sigproc_printf ("child_procs count %d", chld_procs.count ());
if (chld_procs.count ())
{
sync_proc_subproc.acquire (WPSP);
proc_subproc (PROC_CLEARWAIT, 1);
/* Clean out proc processes from the pid list. */
for (int i = 0; i < chld_procs.count (); i++)
{
/* If we've execed then the execed process will handle setting ppid
to 1 iff it is a Cygwin process. */
if (!have_execed || !have_execed_cygwin)
chld_procs[i]->ppid = 1;
if (chld_procs[i].wait_thread)
if (!CancelSynchronousIo (chld_procs[i].wait_thread->thread_handle ()))
chld_procs[i].wait_thread->terminate_thread ();
/* Release memory associated with this process unless it is 'myself'.
'myself' is only in the chld_procs table when we've execed. We
reach here when the next process has finished initializing but we
still can't free the memory used by 'myself' since it is used
later on during cygwin tear down. */
if (chld_procs[i] != myself)
chld_procs[i].release ();
}
chld_procs.reset ();
sync_proc_subproc.release ();
}
sigproc_printf ("leaving");
}
/* Clear pending signal */
void
sig_clear (int sig)
{
sigq.clear (sig);
}
/* Clear pending signals of specific thread. Called under TLS lock from
_cygtls::remove_pending_sigs. */
void
pending_signals::clear (_cygtls *tls)
{
sigpacket *q = &start, *qnext;
while ((qnext = q->next))
if (qnext->sigtls == tls)
{
qnext->si.si_signo = 0;
q->next = qnext->next;
}
else
q = qnext;
}
/* Clear pending signals of specific thread. Called from _cygtls::remove */
void
_cygtls::remove_pending_sigs ()
{
sigq.clear (this);
}
extern "C" int
sigpending (sigset_t *mask)
{
sigset_t outset = sig_send (myself, __SIGPENDING, &_my_tls);
if (outset == SIG_BAD_MASK)
return -1;
*mask = outset;
return 0;
}
/* Force the wait_sig thread to wake up and scan for pending signals */
void
sig_dispatch_pending (bool fast)
{
/* Non-atomically test for any signals pending and wake up wait_sig if any are
found. It's ok if there's a race here since the next call to this function
should catch it. */
if (sigq.pending () && &_my_tls != _sig_tls)
sig_send (myself, fast ? __SIGFLUSHFAST : __SIGFLUSH);
}
/* Signal thread initialization. Called from dll_crt0_1.
This routine starts the signal handling thread. */
void
sigproc_init ()
{
char char_sa_buf[1024];
PSECURITY_ATTRIBUTES sa = sec_user_nih ((PSECURITY_ATTRIBUTES) char_sa_buf, cygheap->user.sid());
DWORD err = fhandler_pipe::create (sa, &my_readsig, &my_sendsig,
_NSIG * sizeof (sigpacket), "sigwait",
PIPE_ADD_PID);
if (err)
{
SetLastError (err);
api_fatal ("couldn't create signal pipe, %E");
}
ProtectHandle (my_readsig);
myself->sendsig = my_sendsig;
my_pendingsigs_evt = CreateEvent (NULL, TRUE, FALSE, NULL);
if (!my_pendingsigs_evt)
api_fatal ("couldn't create pending signal event, %E");
/* sync_proc_subproc is used by proc_subproc. It serializes
access to the children and proc arrays. */
sync_proc_subproc.init ("sync_proc_subproc");
new cygthread (wait_sig, cygself, "sig");
}
/* Exit the current thread very carefully.
See cgf-000017 in DevNotes for more details on why this is
necessary. */
void
exit_thread (DWORD res)
{
# undef ExitThread
if (no_thread_exit_protect ())
ExitThread (res);
sigfillset (&_my_tls.sigmask); /* No signals wanted */
/* CV 2014-11-21: Disable the code sending a signal. The problem with
this code is that it allows deadlocks under signal-rich multithreading
conditions.
The original problem reported in 2012 couldn't be reproduced anymore,
even disabling this code. Tested on XP 32, Vista 32, W7 32, WOW64, 64,
W8.1 WOW64, 64. */
#if 0
lock_process for_now; /* May block indefinitely when exiting. */
HANDLE h;
if (!DuplicateHandle (GetCurrentProcess (), GetCurrentThread (),
GetCurrentProcess (), &h,
0, FALSE, DUPLICATE_SAME_ACCESS))
{
#ifdef DEBUGGING
system_printf ("couldn't duplicate the current thread, %E");
#endif
for_now.release ();
ExitThread (res);
}
ProtectHandle1 (h, exit_thread);
/* Tell wait_sig to wait for this thread to exit. It can then release
the lock below and close the above-opened handle. */
siginfo_t si = {__SIGTHREADEXIT, SI_KERNEL};
si.si_cyg = h;
sig_send (myself_nowait, si, &_my_tls);
#endif
ExitThread (res);
}
sigset_t
sig_send (_pinfo *p, int sig, _cygtls *tls)
{
siginfo_t si = {};
si.si_signo = sig;
si.si_code = SI_KERNEL;
return sig_send (p, si, tls);
}
/* Send a signal to another process by raising its signal semaphore.
If pinfo *p == NULL, send to the current process.
If sending to this process, wait for notification that a signal has
completed before returning. */
sigset_t
sig_send (_pinfo *p, siginfo_t& si, _cygtls *tls)
{
int rc = 1;
bool its_me;
HANDLE sendsig;
sigpacket pack;
bool communing = si.si_signo == __SIGCOMMUNE;
pack.wakeup = NULL;
bool wait_for_completion;
if (!(its_me = p == NULL || p == myself || p == myself_nowait))
{
/* It is possible that the process is not yet ready to receive messages
* or that it has exited. Detect this.
*/
if (!proc_can_be_signalled (p)) /* Is the process accepting messages? */
{
sigproc_printf ("invalid pid %d(%x), signal %d",
p->pid, p->process_state, si.si_signo);
goto out;
}
wait_for_completion = false;
}
else
{
wait_for_completion = p != myself_nowait;
p = myself;
}
/* If myself is the stub process, send signal to the child process
rather than myself. The fact that myself->dwProcessId is not equal
to the current process id indicates myself is the stub process. */
if (its_me && myself->dwProcessId != GetCurrentProcessId ())
{
wait_for_completion = false;
its_me = false;
}
if (its_me)
sendsig = my_sendsig;
else
{
HANDLE dupsig;
DWORD dwProcessId;
for (int i = 0; !p->sendsig && i < 10000; i++)
yield ();
if (p->sendsig)
{
dupsig = p->sendsig;
dwProcessId = p->dwProcessId;
}
else
{
dupsig = p->exec_sendsig;
dwProcessId = p->exec_dwProcessId;
}
if (!dupsig)
{
set_errno (EAGAIN);
sigproc_printf ("sendsig handle never materialized");
goto out;
}
HANDLE hp = OpenProcess (PROCESS_DUP_HANDLE, false, dwProcessId);
if (!hp)
{
__seterrno ();
sigproc_printf ("OpenProcess failed, %E");
goto out;
}
VerifyHandle (hp);
if (!DuplicateHandle (hp, dupsig, GetCurrentProcess (), &sendsig, 0,
false, DUPLICATE_SAME_ACCESS) || !sendsig)
{
__seterrno ();
sigproc_printf ("DuplicateHandle failed, %E");
CloseHandle (hp);
goto out;
}
VerifyHandle (sendsig);
if (!communing)
{
CloseHandle (hp);
DWORD flag = PIPE_NOWAIT;
/* Set PIPE_NOWAIT here to avoid blocking when sending a signal.
(Yes, I know MSDN says not to use this)
We can't ever block here because it causes a deadlock when
debugging with gdb. */
BOOL res = SetNamedPipeHandleState (sendsig, &flag, NULL, NULL);
sigproc_printf ("%d = SetNamedPipeHandleState (%y, PIPE_NOWAIT, NULL, NULL)", res, sendsig);
}
else
{
si._si_commune._si_process_handle = hp;
HANDLE& tome = si._si_commune._si_write_handle;
HANDLE& fromthem = si._si_commune._si_read_handle;
if (!CreatePipeOverlapped (&fromthem, &tome, &sec_all_nih))
{
sigproc_printf ("CreatePipe for __SIGCOMMUNE failed, %E");
__seterrno ();
goto out;
}
if (!DuplicateHandle (GetCurrentProcess (), tome, hp, &tome, 0, false,
DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE))
{
sigproc_printf ("DuplicateHandle for __SIGCOMMUNE failed, %E");
__seterrno ();
goto out;
}
}
}
sigproc_printf ("sendsig %p, pid %d, signal %d, its_me %d", sendsig, p->pid,
si.si_signo, its_me);
sigset_t pending;
if (!its_me)
pack.mask = NULL;
else if (si.si_signo == __SIGPENDING || si.si_signo == __SIGPENDINGALL)
pack.mask = &pending;
else if (si.si_signo == __SIGFLUSH || si.si_signo > 0)
{
threadlist_t *tl_entry = cygheap->find_tls (tls ? tls : _main_tls);
pack.mask = tls ? &tls->sigmask : &_main_tls->sigmask;
cygheap->unlock_tls (tl_entry);
}
else
pack.mask = NULL;
pack.si = si;
if (!pack.si.si_pid)
pack.si.si_pid = myself->pid;
if (!pack.si.si_uid)
pack.si.si_uid = myself->uid;
pack.pid = myself->pid;
pack.sigtls = tls;
if (wait_for_completion)
{
pack.wakeup = CreateEvent (&sec_none_nih, FALSE, FALSE, NULL);
sigproc_printf ("wakeup %p", pack.wakeup);
ProtectHandle (pack.wakeup);
}
char *leader;
size_t packsize;
if (!communing || !(si._si_commune._si_code & PICOM_EXTRASTR))
{
leader = (char *) &pack;
packsize = sizeof (pack);
}
else
{
size_t n = strlen (si._si_commune._si_str);
packsize = sizeof (pack) + sizeof (n) + n;
char *p = leader = (char *) alloca (packsize);
memcpy (p, &pack, sizeof (pack)); p += sizeof (pack);
memcpy (p, &n, sizeof (n)); p += sizeof (n);
memcpy (p, si._si_commune._si_str, n); p += n;
}
DWORD nb;
BOOL res;
/* Try multiple times to send if packsize != nb since that probably
means that the pipe buffer is full. */
for (int i = 0; i < 100; i++)
{
res = WriteFile (sendsig, leader, packsize, &nb, NULL);
if (!res || packsize == nb)
break;
Sleep (10);
res = 0;
}
if (!res)
{
/* Couldn't send to the pipe. This probably means that the
process is exiting. */
if (!its_me)
{
sigproc_printf ("WriteFile for pipe %p failed, %E", sendsig);
ForceCloseHandle (sendsig);
}
else if (!p->exec_sendsig && !exit_state)
system_printf ("error sending signal %d, pid %u, pipe handle %p, nb %u, packsize %u, %E",
si.si_signo, p->pid, sendsig, nb, packsize);
if (GetLastError () == ERROR_BROKEN_PIPE)
set_errno (ESRCH);
else
__seterrno ();
goto out;
}
/* No need to wait for signal completion unless this was a signal to
this process.
If it was a signal to this process, wait for a dispatched signal.
Otherwise just wait for the wait_sig to signal that it has finished
processing the signal. */
if (wait_for_completion)
{
sigproc_printf ("Waiting for pack.wakeup %p", pack.wakeup);
rc = WaitForSingleObject (pack.wakeup, WSSC);
ForceCloseHandle (pack.wakeup);
}
else
{
rc = WAIT_OBJECT_0;
sigproc_printf ("Not waiting for sigcomplete. its_me %d signal %d",
its_me, si.si_signo);
if (!its_me)
ForceCloseHandle (sendsig);
}
pack.wakeup = NULL;
if (rc == WAIT_OBJECT_0)
rc = 0; // Successful exit
else
{
set_errno (ENOSYS);
rc = -1;
}
if (wait_for_completion && si.si_signo != __SIGFLUSHFAST)
_my_tls.call_signal_handler ();
out:
if (communing && rc)
{
if (si._si_commune._si_process_handle)
CloseHandle (si._si_commune._si_process_handle);
if (si._si_commune._si_read_handle)
CloseHandle (si._si_commune._si_read_handle);
}
if (pack.wakeup)
ForceCloseHandle (pack.wakeup);
if (si.si_signo != __SIGPENDING && si.si_signo != __SIGPENDINGALL)
/* nothing */;
else if (!rc)
rc = pending;
else
rc = SIG_BAD_MASK;
sigproc_printf ("returning %p from sending signal %d", rc, si.si_signo);
return rc;
}
int child_info::retry_count = 0;
/* Initialize some of the memory block passed to child processes
by fork/spawn/exec. */
child_info::child_info (unsigned in_cb, child_info_types chtype,
bool need_subproc_ready):
msv_count (0), cb (in_cb), intro (PROC_MAGIC_GENERIC),
magic (CHILD_INFO_MAGIC ^ MSYS2_RUNTIME_COMMIT_HEX), type (chtype), cygheap (::cygheap),
cygheap_max (::cygheap_max), flag (0), retry (child_info::retry_count),
rd_proc_pipe (NULL), wr_proc_pipe (NULL), sigmask (_my_tls.sigmask)
{
fhandler_union_cb = sizeof (fhandler_union);
user_h = cygwin_user_h;
if (strace.active ())
{
NTSTATUS status;
ULONG DebugFlags;
/* Only propagate _CI_STRACED to child if strace is actually tracing
child processes of this process. The undocumented ProcessDebugFlags
returns 0 if EPROCESS->NoDebugInherit is TRUE, 1 otherwise.
This avoids a hang when stracing a forking or spawning process
with the -f flag set to "don't follow fork". */
status = NtQueryInformationProcess (GetCurrentProcess (),
ProcessDebugFlags, &DebugFlags,
sizeof (DebugFlags), NULL);
if (NT_SUCCESS (status) && DebugFlags)
flag |= _CI_STRACED;
}
if (need_subproc_ready)
{
subproc_ready = CreateEvent (&sec_all, FALSE, FALSE, NULL);
flag |= _CI_ISCYGWIN;
}
sigproc_printf ("subproc_ready %p", subproc_ready);
/* Create an inheritable handle to pass to the child process. This will
allow the child to copy cygheap etc. from the parent to itself. If
we're forking, we also need handle duplicate access. */
parent = NULL;
DWORD perms = PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ
| PROCESS_VM_OPERATION | SYNCHRONIZE;
if (type == _CH_FORK)
perms |= PROCESS_DUP_HANDLE;
if (!DuplicateHandle (GetCurrentProcess (), GetCurrentProcess (),
GetCurrentProcess (), &parent, perms, TRUE, 0))
system_printf ("couldn't create handle to myself for child, %E");
}
child_info::~child_info ()
{
cleanup ();
}
child_info_fork::child_info_fork () :
child_info (sizeof *this, _CH_FORK, true),
forker_finished (NULL)
{
}
child_info_spawn::child_info_spawn (child_info_types chtype, bool need_subproc_ready) :
child_info (sizeof *this, chtype, need_subproc_ready)
{
if (type == _CH_EXEC)
{
hExeced = NULL;
if (my_wr_proc_pipe)
ev = NULL;
else if (!(ev = CreateEvent (&sec_none_nih, false, false, NULL)))
api_fatal ("couldn't create signalling event for exec, %E");
get_proc_lock (PROC_EXECING, 0);
/* exit with lock held */
}
}
cygheap_exec_info *
cygheap_exec_info::alloc ()
{
cygheap_exec_info *res =
(cygheap_exec_info *) ccalloc_abort (HEAP_1_EXEC, 1,
sizeof (cygheap_exec_info)
+ (chld_procs.count ()
* sizeof (children[0])));
return res;
}
void
child_info_spawn::wait_for_myself ()
{
postfork (myself);
if (myself.remember ())
myself.attach ();
WaitForSingleObject (ev, INFINITE);
}
void
child_info::cleanup ()
{
if (subproc_ready)
{
CloseHandle (subproc_ready);
subproc_ready = NULL;
}
if (parent)
{
CloseHandle (parent);
parent = NULL;
}
if (rd_proc_pipe)
{
ForceCloseHandle (rd_proc_pipe);
rd_proc_pipe = NULL;
}
if (wr_proc_pipe)
{
ForceCloseHandle (wr_proc_pipe);
wr_proc_pipe = NULL;
}
}
void
child_info_spawn::cleanup ()
{
if (moreinfo)
{
if (moreinfo->envp)
{
for (char **e = moreinfo->envp; *e; e++)
cfree (*e);
cfree (moreinfo->envp);
}
if (type != _CH_SPAWN && moreinfo->myself_pinfo)
CloseHandle (moreinfo->myself_pinfo);
cfree (moreinfo);
}
moreinfo = NULL;
if (ev)
{
CloseHandle (ev);
ev = NULL;
}
if (type == _CH_EXEC)
{
if (iscygwin () && hExeced)
proc_subproc (PROC_EXEC_CLEANUP, 0);
sync_proc_subproc.release ();
}
type = _CH_NADA;
child_info::cleanup ();
}
/* Record any non-reaped subprocesses to be passed to about-to-be-execed
process. FIXME: There is a race here if the process exits while we
are recording it. */
inline void
cygheap_exec_info::record_children ()
{
for (nchildren = 0; nchildren < chld_procs.count (); nchildren++)
{
children[nchildren].pid = chld_procs[nchildren]->pid;
children[nchildren].p = chld_procs[nchildren];
/* Set inheritance of required child handles for reattach_children
in the about-to-be-execed process. */
children[nchildren].p.set_inheritance (true);
}
}
void
child_info_spawn::record_children ()
{
if (type == _CH_EXEC && iscygwin ())
moreinfo->record_children ();
}
/* Reattach non-reaped subprocesses passed in from the cygwin process
which previously operated under this pid. FIXME: Is there a race here
if the process exits during cygwin's exec handoff? */
inline void
cygheap_exec_info::reattach_children (HANDLE parent)
{
for (int i = 0; i < nchildren; i++)
{
pinfo p (parent, children[i].p, children[i].pid);
if (!p)
debug_only_printf ("couldn't reattach child %d from previous process", children[i].pid);
else if (!p.attach ())
debug_only_printf ("attach of child process %d failed", children[i].pid);
else
debug_only_printf ("reattached pid %d<%u>, process handle %p, rd_proc_pipe %p->%p",
p->pid, p->dwProcessId, p.hProcess,
children[i].p.rd_proc_pipe, p.rd_proc_pipe);
}