summaryrefslogtreecommitdiff
path: root/signal.c
blob: 65b45cf6bda1e57184f8e5181dfe419d6c4294e1 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
/**********************************************************************

  signal.c -

  $Author$
  created at: Tue Dec 20 10:13:44 JST 1994

  Copyright (C) 1993-2007 Yukihiro Matsumoto
  Copyright (C) 2000  Network Applied Communication Laboratory, Inc.
  Copyright (C) 2000  Information-technology Promotion Agency, Japan

**********************************************************************/

#include "internal.h"
#include "vm_core.h"
#include <signal.h>
#include <stdio.h>
#include <errno.h>
#include "ruby_atomic.h"
#include "eval_intern.h"
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_SYS_UIO_H
#include <sys/uio.h>
#endif
#ifdef HAVE_UCONTEXT_H
#include <ucontext.h>
#endif

#ifdef HAVE_VALGRIND_MEMCHECK_H
# include <valgrind/memcheck.h>
# ifndef VALGRIND_MAKE_MEM_DEFINED
#  define VALGRIND_MAKE_MEM_DEFINED(p, n) VALGRIND_MAKE_READABLE((p), (n))
# endif
# ifndef VALGRIND_MAKE_MEM_UNDEFINED
#  define VALGRIND_MAKE_MEM_UNDEFINED(p, n) VALGRIND_MAKE_WRITABLE((p), (n))
# endif
#else
# define VALGRIND_MAKE_MEM_DEFINED(p, n) 0
# define VALGRIND_MAKE_MEM_UNDEFINED(p, n) 0
#endif

#ifdef NEED_RUBY_ATOMIC_OPS
rb_atomic_t
ruby_atomic_exchange(rb_atomic_t *ptr, rb_atomic_t val)
{
    rb_atomic_t old = *ptr;
    *ptr = val;
    return old;
}

rb_atomic_t
ruby_atomic_compare_and_swap(rb_atomic_t *ptr, rb_atomic_t cmp,
			     rb_atomic_t newval)
{
    rb_atomic_t old = *ptr;
    if (old == cmp) {
	*ptr = newval;
    }
    return old;
}
#endif

#define FOREACH_SIGNAL(sig, offset) \
    for (sig = siglist + (offset); sig < siglist + numberof(siglist); ++sig)
enum { LONGEST_SIGNAME = 7 }; /* MIGRATE and RETRACT */
static const struct signals {
    char signm[LONGEST_SIGNAME + 1];
    int  signo;
} siglist [] = {
    {"EXIT", 0},
#ifdef SIGHUP
    {"HUP", SIGHUP},
#endif
    {"INT", SIGINT},
#ifdef SIGQUIT
    {"QUIT", SIGQUIT},
#endif
#ifdef SIGILL
    {"ILL", SIGILL},
#endif
#ifdef SIGTRAP
    {"TRAP", SIGTRAP},
#endif
#ifdef SIGABRT
    {"ABRT", SIGABRT},
#endif
#ifdef SIGIOT
    {"IOT", SIGIOT},
#endif
#ifdef SIGEMT
    {"EMT", SIGEMT},
#endif
#ifdef SIGFPE
    {"FPE", SIGFPE},
#endif
#ifdef SIGKILL
    {"KILL", SIGKILL},
#endif
#ifdef SIGBUS
    {"BUS", SIGBUS},
#endif
#ifdef SIGSEGV
    {"SEGV", SIGSEGV},
#endif
#ifdef SIGSYS
    {"SYS", SIGSYS},
#endif
#ifdef SIGPIPE
    {"PIPE", SIGPIPE},
#endif
#ifdef SIGALRM
    {"ALRM", SIGALRM},
#endif
#ifdef SIGTERM
    {"TERM", SIGTERM},
#endif
#ifdef SIGURG
    {"URG", SIGURG},
#endif
#ifdef SIGSTOP
    {"STOP", SIGSTOP},
#endif
#ifdef SIGTSTP
    {"TSTP", SIGTSTP},
#endif
#ifdef SIGCONT
    {"CONT", SIGCONT},
#endif
#if RUBY_SIGCHLD
    {"CHLD", RUBY_SIGCHLD },
    {"CLD", RUBY_SIGCHLD },
#endif
#ifdef SIGTTIN
    {"TTIN", SIGTTIN},
#endif
#ifdef SIGTTOU
    {"TTOU", SIGTTOU},
#endif
#ifdef SIGIO
    {"IO", SIGIO},
#endif
#ifdef SIGXCPU
    {"XCPU", SIGXCPU},
#endif
#ifdef SIGXFSZ
    {"XFSZ", SIGXFSZ},
#endif
#ifdef SIGVTALRM
    {"VTALRM", SIGVTALRM},
#endif
#ifdef SIGPROF
    {"PROF", SIGPROF},
#endif
#ifdef SIGWINCH
    {"WINCH", SIGWINCH},
#endif
#ifdef SIGUSR1
    {"USR1", SIGUSR1},
#endif
#ifdef SIGUSR2
    {"USR2", SIGUSR2},
#endif
#ifdef SIGLOST
    {"LOST", SIGLOST},
#endif
#ifdef SIGMSG
    {"MSG", SIGMSG},
#endif
#ifdef SIGPWR
    {"PWR", SIGPWR},
#endif
#ifdef SIGPOLL
    {"POLL", SIGPOLL},
#endif
#ifdef SIGDANGER
    {"DANGER", SIGDANGER},
#endif
#ifdef SIGMIGRATE
    {"MIGRATE", SIGMIGRATE},
#endif
#ifdef SIGPRE
    {"PRE", SIGPRE},
#endif
#ifdef SIGGRANT
    {"GRANT", SIGGRANT},
#endif
#ifdef SIGRETRACT
    {"RETRACT", SIGRETRACT},
#endif
#ifdef SIGSOUND
    {"SOUND", SIGSOUND},
#endif
#ifdef SIGINFO
    {"INFO", SIGINFO},
#endif
};

static const char signame_prefix[3] = "SIG";
static const int signame_prefix_len = (int)sizeof(signame_prefix);

static int
signm2signo(VALUE *sig_ptr, int negative, int exit, int *prefix_ptr)
{
    const struct signals *sigs;
    VALUE vsig = *sig_ptr;
    const char *nm;
    long len, nmlen;
    int prefix = 0;

    if (RB_SYMBOL_P(vsig)) {
	*sig_ptr = vsig = rb_sym2str(vsig);
    }
    else if (!RB_TYPE_P(vsig, T_STRING)) {
	VALUE str = rb_check_string_type(vsig);
	if (NIL_P(str)) {
	    rb_raise(rb_eArgError, "bad signal type %s",
		     rb_obj_classname(vsig));
	}
	*sig_ptr = vsig = str;
    }

    rb_must_asciicompat(vsig);
    RSTRING_GETMEM(vsig, nm, len);
    if (memchr(nm, '\0', len)) {
	rb_raise(rb_eArgError, "signal name with null byte");
    }

    if (len > 0 && nm[0] == '-') {
	if (!negative)
	    rb_raise(rb_eArgError, "negative signal name: % "PRIsVALUE, vsig);
	prefix = 1;
    }
    else {
	negative = 0;
    }
    if (len >= prefix + signame_prefix_len) {
	if (memcmp(nm + prefix, signame_prefix, sizeof(signame_prefix)) == 0)
	    prefix += signame_prefix_len;
    }
    if (len <= (long)prefix) {
      unsupported:
	if (prefix == signame_prefix_len) {
	    prefix = 0;
	}
	else if (prefix > signame_prefix_len) {
	    prefix -= signame_prefix_len;
	    len -= prefix;
	    vsig = rb_str_subseq(vsig, prefix, len);
	    prefix = 0;
	}
	else {
	    len -= prefix;
	    vsig = rb_str_subseq(vsig, prefix, len);
	    prefix = signame_prefix_len;
	}
	rb_raise(rb_eArgError, "unsupported signal `%.*s%"PRIsVALUE"'",
		 prefix, signame_prefix, vsig);
    }

    if (prefix_ptr) *prefix_ptr = prefix;
    nmlen = len - prefix;
    nm += prefix;
    if (nmlen > LONGEST_SIGNAME) goto unsupported;
    FOREACH_SIGNAL(sigs, !exit) {
	if (memcmp(sigs->signm, nm, nmlen) == 0 &&
	    sigs->signm[nmlen] == '\0') {
	    return negative ? -sigs->signo : sigs->signo;
	}
    }
    goto unsupported;
}

static const char*
signo2signm(int no)
{
    const struct signals *sigs;

    FOREACH_SIGNAL(sigs, 0) {
	if (sigs->signo == no)
	    return sigs->signm;
    }
    return 0;
}

/*
 * call-seq:
 *     Signal.signame(signo)  ->  string or nil
 *
 *  Convert signal number to signal name.
 *  Returns +nil+ if the signo is an invalid signal number.
 *
 *     Signal.trap("INT") { |signo| puts Signal.signame(signo) }
 *     Process.kill("INT", 0)
 *
 *  <em>produces:</em>
 *
 *     INT
 */
static VALUE
sig_signame(VALUE recv, VALUE signo)
{
    const char *signame = signo2signm(NUM2INT(signo));
    if (!signame) return Qnil;
    return rb_str_new_cstr(signame);
}

const char *
ruby_signal_name(int no)
{
    return signo2signm(no);
}

static VALUE
rb_signo2signm(int signo)
{
    const char *const signm = signo2signm(signo);
    if (signm) {
	return rb_sprintf("SIG%s", signm);
    }
    else {
	return rb_sprintf("SIG%u", signo);
    }
}

/*
 * call-seq:
 *    SignalException.new(sig_name)              ->  signal_exception
 *    SignalException.new(sig_number [, name])   ->  signal_exception
 *
 *  Construct a new SignalException object.  +sig_name+ should be a known
 *  signal name.
 */

static VALUE
esignal_init(int argc, VALUE *argv, VALUE self)
{
    int argnum = 1;
    VALUE sig = Qnil;
    int signo;

    if (argc > 0) {
	sig = rb_check_to_integer(argv[0], "to_int");
	if (!NIL_P(sig)) argnum = 2;
	else sig = argv[0];
    }
    rb_check_arity(argc, 1, argnum);
    if (argnum == 2) {
	signo = NUM2INT(sig);
	if (signo < 0 || signo > NSIG) {
	    rb_raise(rb_eArgError, "invalid signal number (%d)", signo);
	}
	if (argc > 1) {
	    sig = argv[1];
	}
	else {
	    sig = rb_signo2signm(signo);
	}
    }
    else {
	int prefix;
	signo = signm2signo(&sig, FALSE, FALSE, &prefix);
	if (prefix != signame_prefix_len) {
	    sig = rb_str_append(rb_str_new_cstr("SIG"), sig);
	}
    }
    rb_call_super(1, &sig);
    rb_ivar_set(self, id_signo, INT2NUM(signo));

    return self;
}

/*
 * call-seq:
 *    signal_exception.signo   ->  num
 *
 *  Returns a signal number.
 */

static VALUE
esignal_signo(VALUE self)
{
    return rb_ivar_get(self, id_signo);
}

/* :nodoc: */
static VALUE
interrupt_init(int argc, VALUE *argv, VALUE self)
{
    VALUE args[2];

    args[0] = INT2FIX(SIGINT);
    rb_scan_args(argc, argv, "01", &args[1]);
    return rb_call_super(2, args);
}

void
ruby_default_signal(int sig)
{
    signal(sig, SIG_DFL);
    raise(sig);
}

static RETSIGTYPE sighandler(int sig);
static int signal_ignored(int sig);
static void signal_enque(int sig);

/*
 *  call-seq:
 *     Process.kill(signal, pid, ...)    -> integer
 *
 *  Sends the given signal to the specified process id(s) if _pid_ is positive.
 *  If _pid_ is zero _signal_ is sent to all processes whose group ID is equal
 *  to the group ID of the process. _signal_ may be an integer signal number or
 *  a POSIX signal name (either with or without a +SIG+ prefix). If _signal_ is
 *  negative (or starts with a minus sign), kills process groups instead of
 *  processes. Not all signals are available on all platforms.
 *  The keys and values of +Signal.list+ are known signal names and numbers,
 *  respectively.
 *
 *     pid = fork do
 *        Signal.trap("HUP") { puts "Ouch!"; exit }
 *        # ... do some work ...
 *     end
 *     # ...
 *     Process.kill("HUP", pid)
 *     Process.wait
 *
 *  <em>produces:</em>
 *
 *     Ouch!
 *
 *  If _signal_ is an integer but wrong for signal,
 *  <code>Errno::EINVAL</code> or +RangeError+ will be raised.
 *  Otherwise unless _signal_ is a +String+ or a +Symbol+, and a known
 *  signal name, +ArgumentError+ will be raised.
 *
 *  Also, <code>Errno::ESRCH</code> or +RangeError+ for invalid _pid_,
 *  <code>Errno::EPERM</code> when failed because of no privilege,
 *  will be raised.  In these cases, signals may have been sent to
 *  preceding processes.
 */

VALUE
rb_f_kill(int argc, const VALUE *argv)
{
#ifndef HAVE_KILLPG
#define killpg(pg, sig) kill(-(pg), (sig))
#endif
    int sig;
    int i;
    VALUE str;

    rb_check_arity(argc, 2, UNLIMITED_ARGUMENTS);

    if (FIXNUM_P(argv[0])) {
	sig = FIX2INT(argv[0]);
    }
    else {
	str = argv[0];
	sig = signm2signo(&str, TRUE, FALSE, NULL);
    }

    if (argc <= 1) return INT2FIX(0);

    if (sig < 0) {
	sig = -sig;
	for (i=1; i<argc; i++) {
	    if (killpg(NUM2PIDT(argv[i]), sig) < 0)
		rb_sys_fail(0);
	}
    }
    else {
	const rb_pid_t self = (GET_THREAD() == GET_VM()->main_thread) ? getpid() : -1;
	int wakeup = 0;

	for (i=1; i<argc; i++) {
	    rb_pid_t pid = NUM2PIDT(argv[i]);

	    if ((sig != 0) && (self != -1) && (pid == self)) {
		int t;
		/*
		 * When target pid is self, many caller assume signal will be
		 * delivered immediately and synchronously.
		 */
		switch (sig) {
		  case SIGSEGV:
#ifdef SIGBUS
		  case SIGBUS:
#endif
#ifdef SIGKILL
		  case SIGKILL:
#endif
#ifdef SIGILL
		  case SIGILL:
#endif
#ifdef SIGFPE
		  case SIGFPE:
#endif
#ifdef SIGSTOP
		  case SIGSTOP:
#endif
		    kill(pid, sig);
		    break;
		  default:
		    t = signal_ignored(sig);
		    if (t) {
			if (t < 0 && kill(pid, sig))
			    rb_sys_fail(0);
			break;
		    }
		    signal_enque(sig);
		    wakeup = 1;
		}
	    }
	    else if (kill(pid, sig) < 0) {
		rb_sys_fail(0);
	    }
	}
	if (wakeup) {
	    rb_threadptr_check_signal(GET_VM()->main_thread);
	}
    }
    rb_thread_execute_interrupts(rb_thread_current());

    return INT2FIX(i-1);
}

static struct {
    rb_atomic_t cnt[RUBY_NSIG];
    rb_atomic_t size;
} signal_buff;
volatile unsigned int ruby_nocldwait;

#ifdef __dietlibc__
#define sighandler_t sh_t
#else
#define sighandler_t ruby_sighandler_t
#endif

typedef RETSIGTYPE (*sighandler_t)(int);
#ifdef USE_SIGALTSTACK
typedef void ruby_sigaction_t(int, siginfo_t*, void*);
#define SIGINFO_ARG , siginfo_t *info, void *ctx
#define SIGINFO_CTX ctx
#else
typedef RETSIGTYPE ruby_sigaction_t(int);
#define SIGINFO_ARG
#define SIGINFO_CTX 0
#endif

#ifdef USE_SIGALTSTACK
static int
rb_sigaltstack_size(void)
{
    /* XXX: BSD_vfprintf() uses >1500KiB stack and x86-64 need >5KiB stack. */
    int size = 16*1024;

#ifdef MINSIGSTKSZ
    if (size < MINSIGSTKSZ)
	size = MINSIGSTKSZ;
#endif
#if defined(HAVE_SYSCONF) && defined(_SC_PAGE_SIZE)
    {
	int pagesize;
	pagesize = (int)sysconf(_SC_PAGE_SIZE);
	if (size < pagesize)
	    size = pagesize;
    }
#endif

    return size;
}

/* alternate stack for SIGSEGV */
void *
rb_register_sigaltstack(void)
{
    stack_t newSS, oldSS;

    newSS.ss_size = rb_sigaltstack_size();
    newSS.ss_sp = xmalloc(newSS.ss_size);
    newSS.ss_flags = 0;

    sigaltstack(&newSS, &oldSS); /* ignore error. */

    return newSS.ss_sp;
}
#endif /* USE_SIGALTSTACK */

#ifdef POSIX_SIGNAL
static sighandler_t
ruby_signal(int signum, sighandler_t handler)
{
    struct sigaction sigact, old;

#if 0
    rb_trap_accept_nativethreads[signum] = 0;
#endif

    sigemptyset(&sigact.sa_mask);
#ifdef USE_SIGALTSTACK
    if (handler == SIG_IGN || handler == SIG_DFL) {
        sigact.sa_handler = handler;
        sigact.sa_flags = 0;
    }
    else {
        sigact.sa_sigaction = (ruby_sigaction_t*)handler;
        sigact.sa_flags = SA_SIGINFO;
    }
#else
    sigact.sa_handler = handler;
    sigact.sa_flags = 0;
#endif

    switch (signum) {
      case SIGCHLD:
	if (handler == SIG_IGN) {
	    ruby_nocldwait = 1;
	    if (sigact.sa_flags & SA_SIGINFO) {
		sigact.sa_sigaction = (ruby_sigaction_t*)sighandler;
	    }
	    else {
		sigact.sa_handler = sighandler;
	    }
	}
	else {
	    ruby_nocldwait = 0;
	}
	break;
#if defined(SA_ONSTACK) && defined(USE_SIGALTSTACK)
      case SIGSEGV:
#ifdef SIGBUS
      case SIGBUS:
#endif
	sigact.sa_flags |= SA_ONSTACK;
	break;
#endif
    }
    (void)VALGRIND_MAKE_MEM_DEFINED(&old, sizeof(old));
    if (sigaction(signum, &sigact, &old) < 0) {
	return SIG_ERR;
    }
    if (old.sa_flags & SA_SIGINFO)
	handler = (sighandler_t)old.sa_sigaction;
    else
	handler = old.sa_handler;
    ASSUME(handler != SIG_ERR);
    return handler;
}

sighandler_t
posix_signal(int signum, sighandler_t handler)
{
    return ruby_signal(signum, handler);
}

#elif defined _WIN32
static inline sighandler_t
ruby_signal(int signum, sighandler_t handler)
{
    if (signum == SIGKILL) {
	errno = EINVAL;
	return SIG_ERR;
    }
    return signal(signum, handler);
}

#else /* !POSIX_SIGNAL */
#define ruby_signal(sig,handler) (/* rb_trap_accept_nativethreads[(sig)] = 0,*/ signal((sig),(handler)))
#if 0 /* def HAVE_NATIVETHREAD */
static sighandler_t
ruby_nativethread_signal(int signum, sighandler_t handler)
{
    sighandler_t old;

    old = signal(signum, handler);
    rb_trap_accept_nativethreads[signum] = 1;
    return old;
}
#endif
#endif

static int
signal_ignored(int sig)
{
    sighandler_t func;
#ifdef POSIX_SIGNAL
    struct sigaction old;
    (void)VALGRIND_MAKE_MEM_DEFINED(&old, sizeof(old));
    if (sigaction(sig, NULL, &old) < 0) return FALSE;
    func = old.sa_handler;
#else
    sighandler_t old = signal(sig, SIG_DFL);
    signal(sig, old);
    func = old;
#endif
    if (func == SIG_IGN) return 1;
    return func == sighandler ? 0 : -1;
}

static void
signal_enque(int sig)
{
    ATOMIC_INC(signal_buff.cnt[sig]);
    ATOMIC_INC(signal_buff.size);
}

static rb_atomic_t sigchld_hit;

static RETSIGTYPE
sighandler(int sig)
{
    int old_errnum = errno;

    /* the VM always needs to handle SIGCHLD for rb_waitpid */
    if (sig == RUBY_SIGCHLD) {
        rb_vm_t *vm = GET_VM();
        ATOMIC_EXCHANGE(sigchld_hit, 1);

        /* avoid spurious wakeup in main thread iff nobody uses trap(:CHLD) */
        if (vm && ACCESS_ONCE(VALUE, vm->trap_list.cmd[sig])) {
            signal_enque(sig);
        }
    }
    else {
        signal_enque(sig);
    }
    rb_thread_wakeup_timer_thread(sig);
#if !defined(BSD_SIGNAL) && !defined(POSIX_SIGNAL)
    ruby_signal(sig, sighandler);
#endif

    errno = old_errnum;
}

int
rb_signal_buff_size(void)
{
    return signal_buff.size;
}

#if HAVE_PTHREAD_H
#include <pthread.h>
#endif

static void
rb_disable_interrupt(void)
{
#ifdef HAVE_PTHREAD_SIGMASK
    sigset_t mask;
    sigfillset(&mask);
    pthread_sigmask(SIG_SETMASK, &mask, NULL);
#endif
}

static void
rb_enable_interrupt(void)
{
#ifdef HAVE_PTHREAD_SIGMASK
    sigset_t mask;
    sigemptyset(&mask);
    pthread_sigmask(SIG_SETMASK, &mask, NULL);
#endif
}

int
rb_get_next_signal(void)
{
    int i, sig = 0;

    if (signal_buff.size != 0) {
	for (i=1; i<RUBY_NSIG; i++) {
	    if (signal_buff.cnt[i] > 0) {
		ATOMIC_DEC(signal_buff.cnt[i]);
		ATOMIC_DEC(signal_buff.size);
		sig = i;
		break;
	    }
	}
    }
    return sig;
}

#if defined SIGSEGV || defined SIGBUS || defined SIGILL || defined SIGFPE
static const char *received_signal;
# define clear_received_signal() (void)(ruby_disable_gc = 0, received_signal = 0)
#else
# define clear_received_signal() ((void)0)
#endif

#if defined(USE_SIGALTSTACK) || defined(_WIN32)
NORETURN(void rb_ec_stack_overflow(rb_execution_context_t *ec, int crit));
# if defined __HAIKU__
#   define USE_UCONTEXT_REG 1
# elif !(defined(HAVE_UCONTEXT_H) && (defined __i386__ || defined __x86_64__ || defined __amd64__))
# elif defined __linux__
#   define USE_UCONTEXT_REG 1
# elif defined __APPLE__
#   define USE_UCONTEXT_REG 1
# elif defined __FreeBSD__
#   define USE_UCONTEXT_REG 1
# endif
#if defined(HAVE_PTHREAD_SIGMASK)
# define ruby_sigunmask pthread_sigmask
#elif defined(HAVE_SIGPROCMASK)
# define ruby_sigunmask sigprocmask
#endif
static void
reset_sigmask(int sig)
{
#if defined(ruby_sigunmask)
    sigset_t mask;
#endif
    clear_received_signal();
#if defined(ruby_sigunmask)
    sigemptyset(&mask);
    sigaddset(&mask, sig);
    if (ruby_sigunmask(SIG_UNBLOCK, &mask, NULL)) {
	rb_bug_errno(STRINGIZE(ruby_sigunmask)":unblock", errno);
    }
#endif
}

# ifdef USE_UCONTEXT_REG
static void
check_stack_overflow(int sig, const uintptr_t addr, const ucontext_t *ctx)
{
    const DEFINE_MCONTEXT_PTR(mctx, ctx);
# if defined __linux__
#   if defined REG_RSP
    const greg_t sp = mctx->gregs[REG_RSP];
    const greg_t bp = mctx->gregs[REG_RBP];
#   else
    const greg_t sp = mctx->gregs[REG_ESP];
    const greg_t bp = mctx->gregs[REG_EBP];
#   endif
# elif defined __APPLE__
#   if defined(__LP64__)
    const uintptr_t sp = mctx->__ss.__rsp;
    const uintptr_t bp = mctx->__ss.__rbp;
#   else
    const uintptr_t sp = mctx->__ss.__esp;
    const uintptr_t bp = mctx->__ss.__ebp;
#   endif
# elif defined __FreeBSD__
#   if defined(__amd64__)
    const __register_t sp = mctx->mc_rsp;
    const __register_t bp = mctx->mc_rbp;
#   else
    const __register_t sp = mctx->mc_esp;
    const __register_t bp = mctx->mc_ebp;
#   endif
# elif defined __HAIKU__
#   if defined(__amd64__)
    const unsigned long sp = mctx->rsp;
    const unsigned long bp = mctx->rbp;
#   else
    const unsigned long sp = mctx->esp;
    const unsigned long bp = mctx->ebp;
#   endif
# endif
    enum {pagesize = 4096};
    const uintptr_t sp_page = (uintptr_t)sp / pagesize;
    const uintptr_t bp_page = (uintptr_t)bp / pagesize;
    const uintptr_t fault_page = addr / pagesize;

    /* SP in ucontext is not decremented yet when `push` failed, so
     * the fault page can be the next. */
    if (sp_page == fault_page || sp_page == fault_page + 1 ||
	sp_page <= fault_page && fault_page <= bp_page) {
	rb_execution_context_t *ec = GET_EC();
	int crit = FALSE;
	if ((uintptr_t)ec->tag->buf / pagesize <= fault_page + 1) {
	    /* drop the last tag if it is close to the fault,
	     * otherwise it can cause stack overflow again at the same
	     * place. */
	    ec->tag = ec->tag->prev;
	    crit = TRUE;
	}
	reset_sigmask(sig);
	rb_ec_stack_overflow(ec, crit);
    }
}
# else
static void
check_stack_overflow(int sig, const void *addr)
{
    int ruby_stack_overflowed_p(const rb_thread_t *, const void *);
    rb_thread_t *th = GET_THREAD();
    if (ruby_stack_overflowed_p(th, addr)) {
	reset_sigmask(sig);
	rb_ec_stack_overflow(th->ec, FALSE);
    }
}
# endif
# ifdef _WIN32
#   define CHECK_STACK_OVERFLOW() check_stack_overflow(sig, 0)
# else
#   define FAULT_ADDRESS info->si_addr
#   ifdef USE_UCONTEXT_REG
#     define CHECK_STACK_OVERFLOW() check_stack_overflow(sig, (uintptr_t)FAULT_ADDRESS, ctx)
#   else
#     define CHECK_STACK_OVERFLOW() check_stack_overflow(sig, FAULT_ADDRESS)
#   endif
#   define MESSAGE_FAULT_ADDRESS " at %p", FAULT_ADDRESS
# endif
#else
# define CHECK_STACK_OVERFLOW() (void)0
#endif
#ifndef MESSAGE_FAULT_ADDRESS
# define MESSAGE_FAULT_ADDRESS
#endif

#if defined SIGSEGV || defined SIGBUS || defined SIGILL || defined SIGFPE
NOINLINE(static void check_reserved_signal_(const char *name, size_t name_len));
/* noinine to reduce stack usage in signal handers */

#define check_reserved_signal(name) check_reserved_signal_(name, sizeof(name)-1)

#ifdef SIGBUS

NORETURN(static ruby_sigaction_t sigbus);

static RETSIGTYPE
sigbus(int sig SIGINFO_ARG)
{
    check_reserved_signal("BUS");
/*
 * Mac OS X makes KERN_PROTECTION_FAILURE when thread touch guard page.
 * and it's delivered as SIGBUS instead of SIGSEGV to userland. It's crazy
 * wrong IMHO. but anyway we have to care it. Sigh.
 */
    /* Seems Linux also delivers SIGBUS. */
#if defined __APPLE__ || defined __linux__
    CHECK_STACK_OVERFLOW();
#endif
    rb_bug_context(SIGINFO_CTX, "Bus Error" MESSAGE_FAULT_ADDRESS);
}
#endif

NORETURN(static void ruby_abort(void));

static void
ruby_abort(void)
{
#ifdef __sun
    /* Solaris's abort() is async signal unsafe. Of course, it is not
     *  POSIX compliant.
     */
    raise(SIGABRT);
#else
    abort();
#endif

}

#ifdef SIGSEGV

NORETURN(static ruby_sigaction_t sigsegv);

static RETSIGTYPE
sigsegv(int sig SIGINFO_ARG)
{
    check_reserved_signal("SEGV");
    CHECK_STACK_OVERFLOW();
    rb_bug_context(SIGINFO_CTX, "Segmentation fault" MESSAGE_FAULT_ADDRESS);
}
#endif

#ifdef SIGILL

NORETURN(static ruby_sigaction_t sigill);

static RETSIGTYPE
sigill(int sig SIGINFO_ARG)
{
    check_reserved_signal("ILL");
#if defined __APPLE__
    CHECK_STACK_OVERFLOW();
#endif
    rb_bug_context(SIGINFO_CTX, "Illegal instruction" MESSAGE_FAULT_ADDRESS);
}
#endif

static void
check_reserved_signal_(const char *name, size_t name_len)
{
    const char *prev = ATOMIC_PTR_EXCHANGE(received_signal, name);

    if (prev) {
	ssize_t RB_UNUSED_VAR(err);
#define NOZ(name, str) name[sizeof(str)-1] = str
	static const char NOZ(msg1, " received in ");
	static const char NOZ(msg2, " handler\n");

#ifdef HAVE_WRITEV
	struct iovec iov[4];

	iov[0].iov_base = (void *)name;
	iov[0].iov_len = name_len;
	iov[1].iov_base = (void *)msg1;
	iov[1].iov_len = sizeof(msg1);
	iov[2].iov_base = (void *)prev;
	iov[2].iov_len = strlen(prev);
	iov[3].iov_base = (void *)msg2;
	iov[3].iov_len = sizeof(msg2);
	err = writev(2, iov, 4);
#else
	err = write(2, name, name_len);
	err = write(2, msg1, sizeof(msg1));
	err = write(2, prev, strlen(prev));
	err = write(2, msg2, sizeof(msg2));
#endif
	ruby_abort();
    }

    ruby_disable_gc = 1;
}
#endif

#if defined SIGPIPE || defined SIGSYS
static RETSIGTYPE
sig_do_nothing(int sig)
{
}
#endif

static void
signal_exec(VALUE cmd, int safe, int sig)
{
    rb_execution_context_t *ec = GET_EC();
    volatile rb_atomic_t old_interrupt_mask = ec->interrupt_mask;
    enum ruby_tag_type state;

    /*
     * workaround the following race:
     * 1. signal_enque queues signal for execution
     * 2. user calls trap(sig, "IGNORE"), setting SIG_IGN
     * 3. rb_signal_exec runs on queued signal
     */
    if (IMMEDIATE_P(cmd))
	return;

    ec->interrupt_mask |= TRAP_INTERRUPT_MASK;
    EC_PUSH_TAG(ec);
    if ((state = EC_EXEC_TAG()) == TAG_NONE) {
	VALUE signum = INT2NUM(sig);
	rb_eval_cmd(cmd, rb_ary_new3(1, signum), safe);
    }
    EC_POP_TAG();
    ec = GET_EC();
    ec->interrupt_mask = old_interrupt_mask;

    if (state) {
	/* XXX: should be replaced with rb_threadptr_pending_interrupt_enque() */
	EC_JUMP_TAG(ec, state);
    }
}

void
rb_trap_exit(void)
{
    rb_vm_t *vm = GET_VM();
    VALUE trap_exit = vm->trap_list.cmd[0];

    if (trap_exit) {
	vm->trap_list.cmd[0] = 0;
	signal_exec(trap_exit, vm->trap_list.safe[0], 0);
    }
}

void ruby_waitpid_all(rb_vm_t *); /* process.c */

void
ruby_sigchld_handler(rb_vm_t *vm)
{
    if (SIGCHLD_LOSSY || ATOMIC_EXCHANGE(sigchld_hit, 0)) {
        ruby_waitpid_all(vm);
    }
}

void
rb_signal_exec(rb_thread_t *th, int sig)
{
    rb_vm_t *vm = GET_VM();
    VALUE cmd = vm->trap_list.cmd[sig];
    int safe = vm->trap_list.safe[sig];

    if (cmd == 0) {
	switch (sig) {
	  case SIGINT:
	    rb_interrupt();
	    break;
#ifdef SIGHUP
	  case SIGHUP:
#endif
#ifdef SIGQUIT
	  case SIGQUIT:
#endif
#ifdef SIGTERM
	  case SIGTERM:
#endif
#ifdef SIGALRM
	  case SIGALRM:
#endif
#ifdef SIGUSR1
	  case SIGUSR1:
#endif
#ifdef SIGUSR2
	  case SIGUSR2:
#endif
	    rb_threadptr_signal_raise(th, sig);
	    break;
	}
    }
    else if (cmd == Qundef) {
	rb_threadptr_signal_exit(th);
    }
    else {
	signal_exec(cmd, safe, sig);
    }
}

static sighandler_t
default_handler(int sig)
{
    sighandler_t func;
    switch (sig) {
      case SIGINT:
#ifdef SIGHUP
      case SIGHUP:
#endif
#ifdef SIGQUIT
      case SIGQUIT:
#endif
#ifdef SIGTERM
      case SIGTERM:
#endif
#ifdef SIGALRM
      case SIGALRM:
#endif
#ifdef SIGUSR1
      case SIGUSR1:
#endif
#ifdef SIGUSR2
      case SIGUSR2:
#endif
#if RUBY_SIGCHLD
      case RUBY_SIGCHLD:
#endif
        func = sighandler;
        break;
#ifdef SIGBUS
      case SIGBUS:
        func = (sighandler_t)sigbus;
        break;
#endif
#ifdef SIGSEGV
      case SIGSEGV:
        func = (sighandler_t)sigsegv;
        break;
#endif
#ifdef SIGPIPE
      case SIGPIPE:
        func = sig_do_nothing;
        break;
#endif
#ifdef SIGSYS
      case SIGSYS:
        func = sig_do_nothing;
        break;
#endif
      default:
        func = SIG_DFL;
        break;
    }

    return func;
}

static sighandler_t
trap_handler(VALUE *cmd, int sig)
{
    sighandler_t func = sighandler;
    VALUE command;

    if (NIL_P(*cmd)) {
	func = SIG_IGN;
    }
    else {
	command = rb_check_string_type(*cmd);
	if (NIL_P(command) && SYMBOL_P(*cmd)) {
	    command = rb_sym2str(*cmd);
	    if (!command) rb_raise(rb_eArgError, "bad handler");
	}
	if (!NIL_P(command)) {
	    const char *cptr;
	    long len;
	    SafeStringValue(command);	/* taint check */
	    *cmd = command;
	    RSTRING_GETMEM(command, cptr, len);
	    switch (len) {
	      case 0:
                goto sig_ign;
		break;
              case 14:
		if (memcmp(cptr, "SYSTEM_DEFAULT", 14) == 0) {
                    if (sig == RUBY_SIGCHLD) {
                        goto sig_dfl;
                    }
                    func = SIG_DFL;
                    *cmd = 0;
		}
                break;
	      case 7:
		if (memcmp(cptr, "SIG_IGN", 7) == 0) {
sig_ign:
                    func = SIG_IGN;
                    *cmd = Qtrue;
		}
		else if (memcmp(cptr, "SIG_DFL", 7) == 0) {
sig_dfl:
                    func = default_handler(sig);
                    *cmd = 0;
		}
		else if (memcmp(cptr, "DEFAULT", 7) == 0) {
                    goto sig_dfl;
		}
		break;
	      case 6:
		if (memcmp(cptr, "IGNORE", 6) == 0) {
                    goto sig_ign;
		}
		break;
	      case 4:
		if (memcmp(cptr, "EXIT", 4) == 0) {
		    *cmd = Qundef;
		}
		break;
	    }
	}
	else {
	    rb_proc_t *proc;
	    GetProcPtr(*cmd, proc);
	    (void)proc;
	}
    }

    return func;
}

static int
trap_signm(VALUE vsig)
{
    int sig = -1;

    if (FIXNUM_P(vsig)) {
	sig = FIX2INT(vsig);
	if (sig < 0 || sig >= NSIG) {
	    rb_raise(rb_eArgError, "invalid signal number (%d)", sig);
	}
    }
    else {
	sig = signm2signo(&vsig, FALSE, TRUE, NULL);
    }
    return sig;
}

static VALUE
trap(int sig, sighandler_t func, VALUE command)
{
    sighandler_t oldfunc;
    VALUE oldcmd;
    rb_vm_t *vm = GET_VM();

    /*
     * Be careful. ruby_signal() and trap_list.cmd[sig] must be changed
     * atomically. In current implementation, we only need to don't call
     * RUBY_VM_CHECK_INTS().
     */
    if (sig == 0) {
	oldfunc = SIG_ERR;
    }
    else {
	oldfunc = ruby_signal(sig, func);
	if (oldfunc == SIG_ERR) rb_sys_fail_str(rb_signo2signm(sig));
    }
    oldcmd = vm->trap_list.cmd[sig];
    switch (oldcmd) {
      case 0:
      case Qtrue:
	if (oldfunc == SIG_IGN) oldcmd = rb_str_new2("IGNORE");
        else if (oldfunc == SIG_DFL) oldcmd = rb_str_new2("SYSTEM_DEFAULT");
	else if (oldfunc == sighandler) oldcmd = rb_str_new2("DEFAULT");
	else oldcmd = Qnil;
	break;
      case Qnil:
	break;
      case Qundef:
	oldcmd = rb_str_new2("EXIT");
	break;
    }

    ACCESS_ONCE(VALUE, vm->trap_list.cmd[sig]) = command;
    vm->trap_list.safe[sig] = rb_safe_level();

    return oldcmd;
}

static int
reserved_signal_p(int signo)
{
/* Synchronous signal can't deliver to main thread */
#ifdef SIGSEGV
    if (signo == SIGSEGV)
	return 1;
#endif
#ifdef SIGBUS
    if (signo == SIGBUS)
	return 1;
#endif
#ifdef SIGILL
    if (signo == SIGILL)
	return 1;
#endif
#ifdef SIGFPE
    if (signo == SIGFPE)
	return 1;
#endif

/* used ubf internal see thread_pthread.c. */
#ifdef SIGVTALRM
    if (signo == SIGVTALRM)
	return 1;
#endif

    return 0;
}

/*
 * call-seq:
 *   Signal.trap( signal, command ) -> obj
 *   Signal.trap( signal ) {| | block } -> obj
 *
 * Specifies the handling of signals. The first parameter is a signal
 * name (a string such as ``SIGALRM'', ``SIGUSR1'', and so on) or a
 * signal number. The characters ``SIG'' may be omitted from the
 * signal name. The command or block specifies code to be run when the
 * signal is raised.
 * If the command is the string ``IGNORE'' or ``SIG_IGN'', the signal
 * will be ignored.
 * If the command is ``DEFAULT'' or ``SIG_DFL'', the Ruby's default handler
 * will be invoked.
 * If the command is ``EXIT'', the script will be terminated by the signal.
 * If the command is ``SYSTEM_DEFAULT'', the operating system's default
 * handler will be invoked.
 * Otherwise, the given command or block will be run.
 * The special signal name ``EXIT'' or signal number zero will be
 * invoked just prior to program termination.
 * trap returns the previous handler for the given signal.
 *
 *     Signal.trap(0, proc { puts "Terminating: #{$$}" })
 *     Signal.trap("CLD")  { puts "Child died" }
 *     fork && Process.wait
 *
 * produces:
 *     Terminating: 27461
 *     Child died
 *     Terminating: 27460
 */
static VALUE
sig_trap(int argc, VALUE *argv)
{
    int sig;
    sighandler_t func;
    VALUE cmd;

    rb_check_arity(argc, 1, 2);

    sig = trap_signm(argv[0]);
    if (reserved_signal_p(sig)) {
        const char *name = signo2signm(sig);
        if (name)
            rb_raise(rb_eArgError, "can't trap reserved signal: SIG%s", name);
        else
            rb_raise(rb_eArgError, "can't trap reserved signal: %d", sig);
    }

    if (argc == 1) {
	cmd = rb_block_proc();
	func = sighandler;
    }
    else {
	cmd = argv[1];
	func = trap_handler(&cmd, sig);
    }

    if (OBJ_TAINTED(cmd)) {
	rb_raise(rb_eSecurityError, "Insecure: tainted signal trap");
    }

    return trap(sig, func, cmd);
}

/*
 * call-seq:
 *   Signal.list -> a_hash
 *
 * Returns a list of signal names mapped to the corresponding
 * underlying signal numbers.
 *
 *   Signal.list   #=> {"EXIT"=>0, "HUP"=>1, "INT"=>2, "QUIT"=>3, "ILL"=>4, "TRAP"=>5, "IOT"=>6, "ABRT"=>6, "FPE"=>8, "KILL"=>9, "BUS"=>7, "SEGV"=>11, "SYS"=>31, "PIPE"=>13, "ALRM"=>14, "TERM"=>15, "URG"=>23, "STOP"=>19, "TSTP"=>20, "CONT"=>18, "CHLD"=>17, "CLD"=>17, "TTIN"=>21, "TTOU"=>22, "IO"=>29, "XCPU"=>24, "XFSZ"=>25, "VTALRM"=>26, "PROF"=>27, "WINCH"=>28, "USR1"=>10, "USR2"=>12, "PWR"=>30, "POLL"=>29}
 */
static VALUE
sig_list(void)
{
    VALUE h = rb_hash_new();
    const struct signals *sigs;

    FOREACH_SIGNAL(sigs, 0) {
	rb_hash_aset(h, rb_fstring_cstr(sigs->signm), INT2FIX(sigs->signo));
    }
    return h;
}

#define INSTALL_SIGHANDLER(cond, signame, signum) do {	\
	static const char failed[] = "failed to install "signame" handler"; \
	if (!(cond)) break; \
	if (reserved_signal_p(signum)) rb_bug(failed); \
	perror(failed); \
    } while (0)
static int
install_sighandler(int signum, sighandler_t handler)
{
    sighandler_t old;

    old = ruby_signal(signum, handler);
    if (old == SIG_ERR) return -1;
    /* signal handler should be inherited during exec. */
    if (old != SIG_DFL) {
	ruby_signal(signum, old);
    }
    return 0;
}

#  define install_sighandler(signum, handler) \
    INSTALL_SIGHANDLER(install_sighandler(signum, handler), #signum, signum)

#if RUBY_SIGCHLD
static int
init_sigchld(int sig)
{
    sighandler_t oldfunc;
    sighandler_t func = sighandler;

    oldfunc = ruby_signal(sig, SIG_DFL);
    if (oldfunc == SIG_ERR) return -1;
    ruby_signal(sig, func);
    ACCESS_ONCE(VALUE, GET_VM()->trap_list.cmd[sig]) = 0;

    return 0;
}

#    define init_sigchld(signum) \
    INSTALL_SIGHANDLER(init_sigchld(signum), #signum, signum)
#endif

void
ruby_sig_finalize(void)
{
    sighandler_t oldfunc;

    oldfunc = ruby_signal(SIGINT, SIG_IGN);
    if (oldfunc == sighandler) {
	ruby_signal(SIGINT, SIG_DFL);
    }
}


int ruby_enable_coredump = 0;

/*
 * Many operating systems allow signals to be sent to running
 * processes. Some signals have a defined effect on the process, while
 * others may be trapped at the code level and acted upon. For
 * example, your process may trap the USR1 signal and use it to toggle
 * debugging, and may use TERM to initiate a controlled shutdown.
 *
 *     pid = fork do
 *       Signal.trap("USR1") do
 *         $debug = !$debug
 *         puts "Debug now: #$debug"
 *       end
 *       Signal.trap("TERM") do
 *         puts "Terminating..."
 *         shutdown()
 *       end
 *       # . . . do some work . . .
 *     end
 *
 *     Process.detach(pid)
 *
 *     # Controlling program:
 *     Process.kill("USR1", pid)
 *     # ...
 *     Process.kill("USR1", pid)
 *     # ...
 *     Process.kill("TERM", pid)
 *
 * produces:
 *     Debug now: true
 *     Debug now: false
 *    Terminating...
 *
 * The list of available signal names and their interpretation is
 * system dependent. Signal delivery semantics may also vary between
 * systems; in particular signal delivery may not always be reliable.
 */
void
Init_signal(void)
{
    VALUE mSignal = rb_define_module("Signal");

    rb_define_global_function("trap", sig_trap, -1);
    rb_define_module_function(mSignal, "trap", sig_trap, -1);
    rb_define_module_function(mSignal, "list", sig_list, 0);
    rb_define_module_function(mSignal, "signame", sig_signame, 1);

    rb_define_method(rb_eSignal, "initialize", esignal_init, -1);
    rb_define_method(rb_eSignal, "signo", esignal_signo, 0);
    rb_alias(rb_eSignal, rb_intern_const("signm"), rb_intern_const("message"));
    rb_define_method(rb_eInterrupt, "initialize", interrupt_init, -1);

    /* At this time, there is no subthread. Then sigmask guarantee atomics. */
    rb_disable_interrupt();

    install_sighandler(SIGINT, sighandler);
#ifdef SIGHUP
    install_sighandler(SIGHUP, sighandler);
#endif
#ifdef SIGQUIT
    install_sighandler(SIGQUIT, sighandler);
#endif
#ifdef SIGTERM
    install_sighandler(SIGTERM, sighandler);
#endif
#ifdef SIGALRM
    install_sighandler(SIGALRM, sighandler);
#endif
#ifdef SIGUSR1
    install_sighandler(SIGUSR1, sighandler);
#endif
#ifdef SIGUSR2
    install_sighandler(SIGUSR2, sighandler);
#endif

    if (!ruby_enable_coredump) {
#ifdef SIGBUS
	install_sighandler(SIGBUS, (sighandler_t)sigbus);
#endif
#ifdef SIGILL
	install_sighandler(SIGILL, (sighandler_t)sigill);
#endif
#ifdef SIGSEGV
	RB_ALTSTACK_INIT(GET_VM()->main_altstack);
	install_sighandler(SIGSEGV, (sighandler_t)sigsegv);
#endif
    }
#ifdef SIGPIPE
    install_sighandler(SIGPIPE, sig_do_nothing);
#endif
#ifdef SIGSYS
    install_sighandler(SIGSYS, sig_do_nothing);
#endif

#if RUBY_SIGCHLD
    init_sigchld(RUBY_SIGCHLD);
#endif

    rb_enable_interrupt();
}

#if defined(HAVE_GRANTPT)
extern int grantpt(int);
#else
static int
fake_grantfd(int masterfd)
{
    errno = ENOSYS;
    return -1;
}
#define grantpt(fd) fake_grantfd(fd)
#endif

int
rb_grantpt(int masterfd)
{
    if (RUBY_SIGCHLD) {
        rb_vm_t *vm = GET_VM();
        int ret, e;

        /*
         * Prevent waitpid calls from Ruby by taking waitpid_lock.
         * Pedantically, grantpt(3) is undefined if a non-default
         * SIGCHLD handler is defined, but preventing conflicting
         * waitpid calls ought to be sufficient.
         *
         * We could install the default sighandler temporarily, but that
         * could cause SIGCHLD to be missed by other threads.  Blocking
         * SIGCHLD won't work here, either, unless we stop and restart
         * timer-thread (as only timer-thread sees SIGCHLD), but that
         * seems like overkill.
         */
        rb_nativethread_lock_lock(&vm->waitpid_lock);
        {
            ret = grantpt(masterfd); /* may spawn `pt_chown' and wait on it */
            if (ret < 0) e = errno;
        }
        rb_nativethread_lock_unlock(&vm->waitpid_lock);

        if (ret < 0) errno = e;
        return ret;
    }
    else {
        return grantpt(masterfd);
    }
}